id
stringlengths 11
116
| type
stringclasses 1
value | granularity
stringclasses 4
values | content
stringlengths 16
477k
| metadata
dict |
|---|---|---|---|---|
file_storage_impl_-1279733294048394195
|
clm
|
file
|
// Repository: hyperswitch
// Crate: storage_impl
// File: crates/storage_impl/src/mock_db.rs
// Contains: 1 structs, 0 enums
use std::sync::Arc;
use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState};
use diesel_models as store;
use error_stack::ResultExt;
use futures::lock::{Mutex, MutexGuard};
use hyperswitch_domain_models::{
behaviour::{Conversion, ReverseConversion},
merchant_key_store::MerchantKeyStore,
payments::{payment_attempt::PaymentAttempt, PaymentIntent},
};
use redis_interface::RedisSettings;
use crate::{errors::StorageError, redis::RedisStore};
pub mod payment_attempt;
pub mod payment_intent;
#[cfg(feature = "payouts")]
pub mod payout_attempt;
#[cfg(feature = "payouts")]
pub mod payouts;
pub mod redis_conn;
#[cfg(not(feature = "payouts"))]
use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
#[derive(Clone)]
pub struct MockDb {
pub addresses: Arc<Mutex<Vec<store::Address>>>,
pub configs: Arc<Mutex<Vec<store::Config>>>,
pub merchant_accounts: Arc<Mutex<Vec<store::MerchantAccount>>>,
pub merchant_connector_accounts: Arc<Mutex<Vec<store::MerchantConnectorAccount>>>,
pub payment_attempts: Arc<Mutex<Vec<PaymentAttempt>>>,
pub payment_intents: Arc<Mutex<Vec<PaymentIntent>>>,
pub payment_methods: Arc<Mutex<Vec<store::PaymentMethod>>>,
pub customers: Arc<Mutex<Vec<store::Customer>>>,
pub refunds: Arc<Mutex<Vec<store::Refund>>>,
pub processes: Arc<Mutex<Vec<store::ProcessTracker>>>,
pub redis: Arc<RedisStore>,
pub api_keys: Arc<Mutex<Vec<store::ApiKey>>>,
pub ephemeral_keys: Arc<Mutex<Vec<store::EphemeralKey>>>,
pub cards_info: Arc<Mutex<Vec<store::CardInfo>>>,
pub events: Arc<Mutex<Vec<store::Event>>>,
pub disputes: Arc<Mutex<Vec<store::Dispute>>>,
pub lockers: Arc<Mutex<Vec<store::LockerMockUp>>>,
pub mandates: Arc<Mutex<Vec<store::Mandate>>>,
pub captures: Arc<Mutex<Vec<store::capture::Capture>>>,
pub merchant_key_store: Arc<Mutex<Vec<store::merchant_key_store::MerchantKeyStore>>>,
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
pub tokenizations: Arc<Mutex<Vec<store::tokenization::Tokenization>>>,
pub business_profiles: Arc<Mutex<Vec<store::business_profile::Profile>>>,
pub reverse_lookups: Arc<Mutex<Vec<store::ReverseLookup>>>,
pub payment_link: Arc<Mutex<Vec<store::payment_link::PaymentLink>>>,
pub organizations: Arc<Mutex<Vec<store::organization::Organization>>>,
pub users: Arc<Mutex<Vec<store::user::User>>>,
pub user_roles: Arc<Mutex<Vec<store::user_role::UserRole>>>,
pub authorizations: Arc<Mutex<Vec<store::authorization::Authorization>>>,
pub dashboard_metadata: Arc<Mutex<Vec<store::user::dashboard_metadata::DashboardMetadata>>>,
#[cfg(feature = "payouts")]
pub payout_attempt: Arc<Mutex<Vec<store::payout_attempt::PayoutAttempt>>>,
#[cfg(feature = "payouts")]
pub payouts: Arc<Mutex<Vec<store::payouts::Payouts>>>,
pub authentications: Arc<Mutex<Vec<store::authentication::Authentication>>>,
pub roles: Arc<Mutex<Vec<store::role::Role>>>,
pub user_key_store: Arc<Mutex<Vec<store::user_key_store::UserKeyStore>>>,
pub user_authentication_methods:
Arc<Mutex<Vec<store::user_authentication_method::UserAuthenticationMethod>>>,
pub themes: Arc<Mutex<Vec<store::user::theme::Theme>>>,
pub hyperswitch_ai_interactions:
Arc<Mutex<Vec<store::hyperswitch_ai_interaction::HyperswitchAiInteraction>>>,
}
impl MockDb {
pub async fn new(redis: &RedisSettings) -> error_stack::Result<Self, StorageError> {
Ok(Self {
addresses: Default::default(),
configs: Default::default(),
merchant_accounts: Default::default(),
merchant_connector_accounts: Default::default(),
payment_attempts: Default::default(),
payment_intents: Default::default(),
payment_methods: Default::default(),
customers: Default::default(),
refunds: Default::default(),
processes: Default::default(),
redis: Arc::new(
RedisStore::new(redis)
.await
.change_context(StorageError::InitializationError)?,
),
api_keys: Default::default(),
ephemeral_keys: Default::default(),
cards_info: Default::default(),
events: Default::default(),
disputes: Default::default(),
lockers: Default::default(),
mandates: Default::default(),
captures: Default::default(),
merchant_key_store: Default::default(),
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
tokenizations: Default::default(),
business_profiles: Default::default(),
reverse_lookups: Default::default(),
payment_link: Default::default(),
organizations: Default::default(),
users: Default::default(),
user_roles: Default::default(),
authorizations: Default::default(),
dashboard_metadata: Default::default(),
#[cfg(feature = "payouts")]
payout_attempt: Default::default(),
#[cfg(feature = "payouts")]
payouts: Default::default(),
authentications: Default::default(),
roles: Default::default(),
user_key_store: Default::default(),
user_authentication_methods: Default::default(),
themes: Default::default(),
hyperswitch_ai_interactions: Default::default(),
})
}
/// Returns an option of the resource if it exists
pub async fn find_resource<D, R>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
resources: MutexGuard<'_, Vec<D>>,
filter_fn: impl Fn(&&D) -> bool,
) -> CustomResult<Option<R>, StorageError>
where
D: Sync + ReverseConversion<R> + Clone,
R: Conversion,
{
let resource = resources.iter().find(filter_fn).cloned();
match resource {
Some(res) => Ok(Some(
res.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?,
)),
None => Ok(None),
}
}
/// Throws errors when the requested resource is not found
pub async fn get_resource<D, R>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
resources: MutexGuard<'_, Vec<D>>,
filter_fn: impl Fn(&&D) -> bool,
error_message: String,
) -> CustomResult<R, StorageError>
where
D: Sync + ReverseConversion<R> + Clone,
R: Conversion,
{
match self
.find_resource(state, key_store, resources, filter_fn)
.await?
{
Some(res) => Ok(res),
None => Err(StorageError::ValueNotFound(error_message).into()),
}
}
pub async fn get_resources<D, R>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
resources: MutexGuard<'_, Vec<D>>,
filter_fn: impl Fn(&&D) -> bool,
error_message: String,
) -> CustomResult<Vec<R>, StorageError>
where
D: Sync + ReverseConversion<R> + Clone,
R: Conversion,
{
let resources: Vec<_> = resources.iter().filter(filter_fn).cloned().collect();
if resources.is_empty() {
Err(StorageError::ValueNotFound(error_message).into())
} else {
let pm_futures = resources
.into_iter()
.map(|pm| async {
pm.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.collect::<Vec<_>>();
let domain_resources = futures::future::try_join_all(pm_futures).await?;
Ok(domain_resources)
}
}
pub async fn update_resource<D, R>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
mut resources: MutexGuard<'_, Vec<D>>,
resource_updated: D,
filter_fn: impl Fn(&&mut D) -> bool,
error_message: String,
) -> CustomResult<R, StorageError>
where
D: Sync + ReverseConversion<R> + Clone,
R: Conversion,
{
if let Some(pm) = resources.iter_mut().find(filter_fn) {
*pm = resource_updated.clone();
let result = resource_updated
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?;
Ok(result)
} else {
Err(StorageError::ValueNotFound(error_message).into())
}
}
pub fn master_key(&self) -> &[u8] {
&[
1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24,
25, 26, 27, 28, 29, 30, 31, 32,
]
}
}
#[cfg(not(feature = "payouts"))]
impl PayoutsInterface for MockDb {}
#[cfg(not(feature = "payouts"))]
impl PayoutAttemptInterface for MockDb {}
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/mock_db.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_storage_impl_-885193815745525373
|
clm
|
file
|
// Repository: hyperswitch
// Crate: storage_impl
// File: crates/storage_impl/src/config.rs
// Contains: 1 structs, 1 enums
use common_utils::DbConnectionParams;
use hyperswitch_domain_models::master_key::MasterKeyInterface;
use masking::{PeekInterface, Secret};
use crate::{kv_router_store, DatabaseStore, MockDb, RouterStore};
#[derive(Debug, Clone, serde::Deserialize)]
pub struct Database {
pub username: String,
pub password: Secret<String>,
pub host: String,
pub port: u16,
pub dbname: String,
pub pool_size: u32,
pub connection_timeout: u64,
pub queue_strategy: QueueStrategy,
pub min_idle: Option<u32>,
pub max_lifetime: Option<u64>,
}
impl DbConnectionParams for Database {
fn get_username(&self) -> &str {
&self.username
}
fn get_password(&self) -> Secret<String> {
self.password.clone()
}
fn get_host(&self) -> &str {
&self.host
}
fn get_port(&self) -> u16 {
self.port
}
fn get_dbname(&self) -> &str {
&self.dbname
}
}
#[derive(Debug, serde::Deserialize, Clone, Copy, Default)]
#[serde(rename_all = "PascalCase")]
pub enum QueueStrategy {
#[default]
Fifo,
Lifo,
}
impl From<QueueStrategy> for bb8::QueueStrategy {
fn from(value: QueueStrategy) -> Self {
match value {
QueueStrategy::Fifo => Self::Fifo,
QueueStrategy::Lifo => Self::Lifo,
}
}
}
impl Default for Database {
fn default() -> Self {
Self {
username: String::new(),
password: Secret::<String>::default(),
host: "localhost".into(),
port: 5432,
dbname: String::new(),
pool_size: 5,
connection_timeout: 10,
queue_strategy: QueueStrategy::default(),
min_idle: None,
max_lifetime: None,
}
}
}
impl<T: DatabaseStore> MasterKeyInterface for kv_router_store::KVRouterStore<T> {
fn get_master_key(&self) -> &[u8] {
self.master_key().peek()
}
}
impl<T: DatabaseStore> MasterKeyInterface for RouterStore<T> {
fn get_master_key(&self) -> &[u8] {
self.master_key().peek()
}
}
/// Default dummy key for MockDb
impl MasterKeyInterface for MockDb {
fn get_master_key(&self) -> &[u8] {
self.master_key()
}
}
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/config.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_storage_impl_-1840274334618533077
|
clm
|
file
|
// Repository: hyperswitch
// Crate: storage_impl
// File: crates/storage_impl/src/lib.rs
// Contains: 1 structs, 0 enums
use std::{fmt::Debug, sync::Arc};
use common_utils::types::TenantConfig;
use diesel_models as store;
use error_stack::ResultExt;
use hyperswitch_domain_models::{
behaviour::{Conversion, ReverseConversion},
merchant_key_store::MerchantKeyStore,
};
use masking::StrongSecret;
use redis::{kv_store::RedisConnInterface, pub_sub::PubSubInterface, RedisStore};
mod address;
pub mod business_profile;
pub mod callback_mapper;
pub mod cards_info;
pub mod config;
pub mod configs;
pub mod connection;
pub mod customers;
pub mod database;
pub mod errors;
pub mod invoice;
pub mod kv_router_store;
pub mod lookup;
pub mod mandate;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod merchant_key_store;
pub mod metrics;
pub mod mock_db;
pub mod payment_method;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
pub mod redis;
pub mod refund;
mod reverse_lookup;
pub mod subscription;
pub mod utils;
use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState};
use database::store::PgPool;
pub mod tokenization;
#[cfg(not(feature = "payouts"))]
use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
pub use mock_db::MockDb;
use redis_interface::{errors::RedisError, RedisConnectionPool, SaddReply};
#[cfg(not(feature = "payouts"))]
pub use crate::database::store::Store;
pub use crate::{database::store::DatabaseStore, errors::StorageError};
#[derive(Debug, Clone)]
pub struct RouterStore<T: DatabaseStore> {
db_store: T,
cache_store: Arc<RedisStore>,
master_encryption_key: StrongSecret<Vec<u8>>,
pub request_id: Option<String>,
}
#[async_trait::async_trait]
impl<T: DatabaseStore> DatabaseStore for RouterStore<T>
where
T::Config: Send,
{
type Config = (
T::Config,
redis_interface::RedisSettings,
StrongSecret<Vec<u8>>,
tokio::sync::oneshot::Sender<()>,
&'static str,
);
async fn new(
config: Self::Config,
tenant_config: &dyn TenantConfig,
test_transaction: bool,
) -> error_stack::Result<Self, StorageError> {
let (db_conf, cache_conf, encryption_key, cache_error_signal, inmemory_cache_stream) =
config;
if test_transaction {
Self::test_store(db_conf, tenant_config, &cache_conf, encryption_key)
.await
.attach_printable("failed to create test router store")
} else {
Self::from_config(
db_conf,
tenant_config,
encryption_key,
Self::cache_store(&cache_conf, cache_error_signal).await?,
inmemory_cache_stream,
)
.await
.attach_printable("failed to create store")
}
}
fn get_master_pool(&self) -> &PgPool {
self.db_store.get_master_pool()
}
fn get_replica_pool(&self) -> &PgPool {
self.db_store.get_replica_pool()
}
fn get_accounts_master_pool(&self) -> &PgPool {
self.db_store.get_accounts_master_pool()
}
fn get_accounts_replica_pool(&self) -> &PgPool {
self.db_store.get_accounts_replica_pool()
}
}
impl<T: DatabaseStore> RedisConnInterface for RouterStore<T> {
fn get_redis_conn(&self) -> error_stack::Result<Arc<RedisConnectionPool>, RedisError> {
self.cache_store.get_redis_conn()
}
}
impl<T: DatabaseStore> RouterStore<T> {
pub async fn from_config(
db_conf: T::Config,
tenant_config: &dyn TenantConfig,
encryption_key: StrongSecret<Vec<u8>>,
cache_store: Arc<RedisStore>,
inmemory_cache_stream: &str,
) -> error_stack::Result<Self, StorageError> {
let db_store = T::new(db_conf, tenant_config, false).await?;
let redis_conn = cache_store.redis_conn.clone();
let cache_store = Arc::new(RedisStore {
redis_conn: Arc::new(RedisConnectionPool::clone(
&redis_conn,
tenant_config.get_redis_key_prefix(),
)),
});
cache_store
.redis_conn
.subscribe(inmemory_cache_stream)
.await
.change_context(StorageError::InitializationError)
.attach_printable("Failed to subscribe to inmemory cache stream")?;
Ok(Self {
db_store,
cache_store,
master_encryption_key: encryption_key,
request_id: None,
})
}
pub async fn cache_store(
cache_conf: &redis_interface::RedisSettings,
cache_error_signal: tokio::sync::oneshot::Sender<()>,
) -> error_stack::Result<Arc<RedisStore>, StorageError> {
let cache_store = RedisStore::new(cache_conf)
.await
.change_context(StorageError::InitializationError)
.attach_printable("Failed to create cache store")?;
cache_store.set_error_callback(cache_error_signal);
Ok(Arc::new(cache_store))
}
pub fn master_key(&self) -> &StrongSecret<Vec<u8>> {
&self.master_encryption_key
}
pub async fn call_database<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
execute_query: R,
) -> error_stack::Result<D, StorageError>
where
D: Debug + Sync + Conversion,
R: futures::Future<Output = error_stack::Result<M, diesel_models::errors::DatabaseError>>
+ Send,
M: ReverseConversion<D>,
{
execute_query
.await
.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})?
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
pub async fn find_optional_resource<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
execute_query_fut: R,
) -> error_stack::Result<Option<D>, StorageError>
where
D: Debug + Sync + Conversion,
R: futures::Future<
Output = error_stack::Result<Option<M>, diesel_models::errors::DatabaseError>,
> + Send,
M: ReverseConversion<D>,
{
match execute_query_fut.await.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})? {
Some(resource) => Ok(Some(
resource
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?,
)),
None => Ok(None),
}
}
pub async fn find_resources<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
execute_query: R,
) -> error_stack::Result<Vec<D>, StorageError>
where
D: Debug + Sync + Conversion,
R: futures::Future<
Output = error_stack::Result<Vec<M>, diesel_models::errors::DatabaseError>,
> + Send,
M: ReverseConversion<D>,
{
let resource_futures = execute_query
.await
.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})?
.into_iter()
.map(|resource| async {
resource
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.collect::<Vec<_>>();
let resources = futures::future::try_join_all(resource_futures).await?;
Ok(resources)
}
/// # Panics
///
/// Will panic if `CONNECTOR_AUTH_FILE_PATH` is not set
pub async fn test_store(
db_conf: T::Config,
tenant_config: &dyn TenantConfig,
cache_conf: &redis_interface::RedisSettings,
encryption_key: StrongSecret<Vec<u8>>,
) -> error_stack::Result<Self, StorageError> {
// TODO: create an error enum and return proper error here
let db_store = T::new(db_conf, tenant_config, true).await?;
let cache_store = RedisStore::new(cache_conf)
.await
.change_context(StorageError::InitializationError)
.attach_printable("failed to create redis cache")?;
Ok(Self {
db_store,
cache_store: Arc::new(cache_store),
master_encryption_key: encryption_key,
request_id: None,
})
}
}
// TODO: This should not be used beyond this crate
// Remove the pub modified once StorageScheme usage is completed
pub trait DataModelExt {
type StorageModel;
fn to_storage_model(self) -> Self::StorageModel;
fn from_storage_model(storage_model: Self::StorageModel) -> Self;
}
pub(crate) fn diesel_error_to_data_error(
diesel_error: diesel_models::errors::DatabaseError,
) -> StorageError {
match diesel_error {
diesel_models::errors::DatabaseError::DatabaseConnectionError => {
StorageError::DatabaseConnectionError
}
diesel_models::errors::DatabaseError::NotFound => {
StorageError::ValueNotFound("Value not found".to_string())
}
diesel_models::errors::DatabaseError::UniqueViolation => StorageError::DuplicateValue {
entity: "entity ",
key: None,
},
_ => StorageError::DatabaseError(error_stack::report!(diesel_error)),
}
}
#[async_trait::async_trait]
pub trait UniqueConstraints {
fn unique_constraints(&self) -> Vec<String>;
fn table_name(&self) -> &str;
async fn check_for_constraints(
&self,
redis_conn: &Arc<RedisConnectionPool>,
) -> CustomResult<(), RedisError> {
let constraints = self.unique_constraints();
let sadd_result = redis_conn
.sadd(
&format!("unique_constraint:{}", self.table_name()).into(),
constraints,
)
.await?;
match sadd_result {
SaddReply::KeyNotSet => Err(error_stack::report!(RedisError::SetAddMembersFailed)),
SaddReply::KeySet => Ok(()),
}
}
}
impl UniqueConstraints for diesel_models::Address {
fn unique_constraints(&self) -> Vec<String> {
vec![format!("address_{}", self.address_id)]
}
fn table_name(&self) -> &str {
"Address"
}
}
#[cfg(feature = "v2")]
impl UniqueConstraints for diesel_models::PaymentIntent {
fn unique_constraints(&self) -> Vec<String> {
vec![self.id.get_string_repr().to_owned()]
}
fn table_name(&self) -> &str {
"PaymentIntent"
}
}
#[cfg(feature = "v1")]
impl UniqueConstraints for diesel_models::PaymentIntent {
#[cfg(feature = "v1")]
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"pi_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr()
)]
}
#[cfg(feature = "v2")]
fn unique_constraints(&self) -> Vec<String> {
vec![format!("pi_{}", self.id.get_string_repr())]
}
fn table_name(&self) -> &str {
"PaymentIntent"
}
}
#[cfg(feature = "v1")]
impl UniqueConstraints for diesel_models::PaymentAttempt {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"pa_{}_{}_{}",
self.merchant_id.get_string_repr(),
self.payment_id.get_string_repr(),
self.attempt_id
)]
}
fn table_name(&self) -> &str {
"PaymentAttempt"
}
}
#[cfg(feature = "v2")]
impl UniqueConstraints for diesel_models::PaymentAttempt {
fn unique_constraints(&self) -> Vec<String> {
vec![format!("pa_{}", self.id.get_string_repr())]
}
fn table_name(&self) -> &str {
"PaymentAttempt"
}
}
#[cfg(feature = "v1")]
impl UniqueConstraints for diesel_models::Refund {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"refund_{}_{}",
self.merchant_id.get_string_repr(),
self.refund_id
)]
}
fn table_name(&self) -> &str {
"Refund"
}
}
#[cfg(feature = "v2")]
impl UniqueConstraints for diesel_models::Refund {
fn unique_constraints(&self) -> Vec<String> {
vec![self.id.get_string_repr().to_owned()]
}
fn table_name(&self) -> &str {
"Refund"
}
}
impl UniqueConstraints for diesel_models::ReverseLookup {
fn unique_constraints(&self) -> Vec<String> {
vec![format!("reverselookup_{}", self.lookup_id)]
}
fn table_name(&self) -> &str {
"ReverseLookup"
}
}
#[cfg(feature = "payouts")]
impl UniqueConstraints for diesel_models::Payouts {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"po_{}_{}",
self.merchant_id.get_string_repr(),
self.payout_id.get_string_repr()
)]
}
fn table_name(&self) -> &str {
"Payouts"
}
}
#[cfg(feature = "payouts")]
impl UniqueConstraints for diesel_models::PayoutAttempt {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"poa_{}_{}",
self.merchant_id.get_string_repr(),
self.payout_attempt_id
)]
}
fn table_name(&self) -> &str {
"PayoutAttempt"
}
}
#[cfg(feature = "v1")]
impl UniqueConstraints for diesel_models::PaymentMethod {
fn unique_constraints(&self) -> Vec<String> {
vec![format!("paymentmethod_{}", self.payment_method_id)]
}
fn table_name(&self) -> &str {
"PaymentMethod"
}
}
#[cfg(feature = "v2")]
impl UniqueConstraints for diesel_models::PaymentMethod {
fn unique_constraints(&self) -> Vec<String> {
vec![self.id.get_string_repr().to_owned()]
}
fn table_name(&self) -> &str {
"PaymentMethod"
}
}
impl UniqueConstraints for diesel_models::Mandate {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"mand_{}_{}",
self.merchant_id.get_string_repr(),
self.mandate_id
)]
}
fn table_name(&self) -> &str {
"Mandate"
}
}
#[cfg(feature = "v1")]
impl UniqueConstraints for diesel_models::Customer {
fn unique_constraints(&self) -> Vec<String> {
vec![format!(
"customer_{}_{}",
self.customer_id.get_string_repr(),
self.merchant_id.get_string_repr(),
)]
}
fn table_name(&self) -> &str {
"Customer"
}
}
#[cfg(feature = "v2")]
impl UniqueConstraints for diesel_models::Customer {
fn unique_constraints(&self) -> Vec<String> {
vec![format!("customer_{}", self.id.get_string_repr())]
}
fn table_name(&self) -> &str {
"Customer"
}
}
#[cfg(not(feature = "payouts"))]
impl<T: DatabaseStore> PayoutAttemptInterface for RouterStore<T> {}
#[cfg(not(feature = "payouts"))]
impl<T: DatabaseStore> PayoutsInterface for RouterStore<T> {}
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
impl UniqueConstraints for diesel_models::tokenization::Tokenization {
fn unique_constraints(&self) -> Vec<String> {
vec![format!("id_{}", self.id.get_string_repr())]
}
fn table_name(&self) -> &str {
"tokenization"
}
}
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/lib.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_storage_impl_-7221812085936325475
|
clm
|
file
|
// Repository: hyperswitch
// Crate: storage_impl
// File: crates/storage_impl/src/kv_router_store.rs
// Contains: 1 structs, 0 enums
use std::{fmt::Debug, sync::Arc};
use common_enums::enums::MerchantStorageScheme;
use common_utils::{fallback_reverse_lookup_not_found, types::keymanager::KeyManagerState};
use diesel_models::{errors::DatabaseError, kv};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
behaviour::{Conversion, ReverseConversion},
merchant_key_store::MerchantKeyStore,
};
#[cfg(not(feature = "payouts"))]
use hyperswitch_domain_models::{PayoutAttemptInterface, PayoutsInterface};
use masking::StrongSecret;
use redis_interface::{errors::RedisError, types::HsetnxReply, RedisConnectionPool};
use router_env::logger;
use serde::de;
#[cfg(not(feature = "payouts"))]
pub use crate::database::store::Store;
pub use crate::{database::store::DatabaseStore, mock_db::MockDb};
use crate::{
database::store::PgPool,
diesel_error_to_data_error,
errors::{self, RedisErrorExt, StorageResult},
lookup::ReverseLookupInterface,
metrics,
redis::kv_store::{
decide_storage_scheme, kv_wrapper, KvOperation, KvStorePartition, Op, PartitionKey,
RedisConnInterface,
},
utils::{find_all_combined_kv_database, try_redis_get_else_try_database_get},
RouterStore, TenantConfig, UniqueConstraints,
};
#[derive(Debug, Clone)]
pub struct KVRouterStore<T: DatabaseStore> {
pub router_store: RouterStore<T>,
drainer_stream_name: String,
drainer_num_partitions: u8,
pub ttl_for_kv: u32,
pub request_id: Option<String>,
pub soft_kill_mode: bool,
}
pub struct InsertResourceParams<'a> {
pub insertable: kv::Insertable,
pub reverse_lookups: Vec<String>,
pub key: PartitionKey<'a>,
// secondary key
pub identifier: String,
// type of resource Eg: "payment_attempt"
pub resource_type: &'static str,
}
pub struct UpdateResourceParams<'a> {
pub updateable: kv::Updateable,
pub operation: Op<'a>,
}
pub struct FilterResourceParams<'a> {
pub key: PartitionKey<'a>,
pub pattern: &'static str,
pub limit: Option<i64>,
}
pub enum FindResourceBy<'a> {
Id(String, PartitionKey<'a>),
LookupId(String),
}
pub trait DomainType: Debug + Sync + Conversion {}
impl<T: Debug + Sync + Conversion> DomainType for T {}
/// Storage model with all required capabilities for KV operations
pub trait StorageModel<D: Conversion>:
de::DeserializeOwned
+ serde::Serialize
+ Debug
+ KvStorePartition
+ UniqueConstraints
+ Sync
+ Send
+ ReverseConversion<D>
{
}
impl<T, D> StorageModel<D> for T
where
T: de::DeserializeOwned
+ serde::Serialize
+ Debug
+ KvStorePartition
+ UniqueConstraints
+ Sync
+ Send
+ ReverseConversion<D>,
D: DomainType,
{
}
#[async_trait::async_trait]
impl<T> DatabaseStore for KVRouterStore<T>
where
RouterStore<T>: DatabaseStore,
T: DatabaseStore,
{
type Config = (RouterStore<T>, String, u8, u32, Option<bool>);
async fn new(
config: Self::Config,
tenant_config: &dyn TenantConfig,
_test_transaction: bool,
) -> StorageResult<Self> {
let (router_store, _, drainer_num_partitions, ttl_for_kv, soft_kill_mode) = config;
let drainer_stream_name = format!("{}_{}", tenant_config.get_schema(), config.1);
Ok(Self::from_store(
router_store,
drainer_stream_name,
drainer_num_partitions,
ttl_for_kv,
soft_kill_mode,
))
}
fn get_master_pool(&self) -> &PgPool {
self.router_store.get_master_pool()
}
fn get_replica_pool(&self) -> &PgPool {
self.router_store.get_replica_pool()
}
fn get_accounts_master_pool(&self) -> &PgPool {
self.router_store.get_accounts_master_pool()
}
fn get_accounts_replica_pool(&self) -> &PgPool {
self.router_store.get_accounts_replica_pool()
}
}
impl<T: DatabaseStore> RedisConnInterface for KVRouterStore<T> {
fn get_redis_conn(&self) -> error_stack::Result<Arc<RedisConnectionPool>, RedisError> {
self.router_store.get_redis_conn()
}
}
impl<T: DatabaseStore> KVRouterStore<T> {
pub fn from_store(
store: RouterStore<T>,
drainer_stream_name: String,
drainer_num_partitions: u8,
ttl_for_kv: u32,
soft_kill: Option<bool>,
) -> Self {
let request_id = store.request_id.clone();
Self {
router_store: store,
drainer_stream_name,
drainer_num_partitions,
ttl_for_kv,
request_id,
soft_kill_mode: soft_kill.unwrap_or(false),
}
}
pub fn master_key(&self) -> &StrongSecret<Vec<u8>> {
self.router_store.master_key()
}
pub fn get_drainer_stream_name(&self, shard_key: &str) -> String {
format!("{{{}}}_{}", shard_key, self.drainer_stream_name)
}
pub async fn push_to_drainer_stream<R>(
&self,
redis_entry: kv::TypedSql,
partition_key: PartitionKey<'_>,
) -> error_stack::Result<(), RedisError>
where
R: KvStorePartition,
{
let global_id = format!("{partition_key}");
let request_id = self.request_id.clone().unwrap_or_default();
let shard_key = R::shard_key(partition_key, self.drainer_num_partitions);
let stream_name = self.get_drainer_stream_name(&shard_key);
self.router_store
.cache_store
.redis_conn
.stream_append_entry(
&stream_name.into(),
&redis_interface::RedisEntryId::AutoGeneratedID,
redis_entry
.to_field_value_pairs(request_id, global_id)
.change_context(RedisError::JsonSerializationFailed)?,
)
.await
.map(|_| metrics::KV_PUSHED_TO_DRAINER.add(1, &[]))
.inspect_err(|error| {
metrics::KV_FAILED_TO_PUSH_TO_DRAINER.add(1, &[]);
logger::error!(?error, "Failed to add entry in drainer stream");
})
.change_context(RedisError::StreamAppendFailed)
}
pub async fn find_resource_by_id<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
find_resource_db_fut: R,
find_by: FindResourceBy<'_>,
) -> error_stack::Result<D, errors::StorageError>
where
D: DomainType,
M: StorageModel<D>,
R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send,
{
let database_call = || async {
find_resource_db_fut.await.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})
};
let storage_scheme = Box::pin(decide_storage_scheme::<T, M>(
self,
storage_scheme,
Op::Find,
))
.await;
let res = || async {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let (field, key) = match find_by {
FindResourceBy::Id(field, key) => (field, key),
FindResourceBy::LookupId(lookup_id) => {
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
database_call().await
);
(
lookup.clone().sk_id,
PartitionKey::CombinationKey {
combination: &lookup.clone().pk_id,
},
)
}
};
Box::pin(try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(self, KvOperation::<M>::HGet(&field), key))
.await?
.try_into_hget()
},
database_call,
))
.await
}
}
};
res()
.await?
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
pub async fn find_optional_resource_by_id<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
find_resource_db_fut: R,
find_by: FindResourceBy<'_>,
) -> error_stack::Result<Option<D>, errors::StorageError>
where
D: DomainType,
M: StorageModel<D>,
R: futures::Future<Output = error_stack::Result<Option<M>, DatabaseError>> + Send,
{
let database_call = || async {
find_resource_db_fut.await.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})
};
let storage_scheme = Box::pin(decide_storage_scheme::<T, M>(
self,
storage_scheme,
Op::Find,
))
.await;
let res = || async {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let (field, key) = match find_by {
FindResourceBy::Id(field, key) => (field, key),
FindResourceBy::LookupId(lookup_id) => {
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
database_call().await
);
(
lookup.clone().sk_id,
PartitionKey::CombinationKey {
combination: &lookup.clone().pk_id,
},
)
}
};
Box::pin(try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(self, KvOperation::<M>::HGet(&field), key))
.await?
.try_into_hget()
.map(Some)
},
database_call,
))
.await
}
}
};
match res().await? {
Some(resource) => Ok(Some(
resource
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?,
)),
None => Ok(None),
}
}
pub async fn insert_resource<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
create_resource_fut: R,
resource_new: M,
InsertResourceParams {
insertable,
reverse_lookups,
key,
identifier,
resource_type,
}: InsertResourceParams<'_>,
) -> error_stack::Result<D, errors::StorageError>
where
D: Debug + Sync + Conversion,
M: StorageModel<D>,
R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send,
{
let storage_scheme = Box::pin(decide_storage_scheme::<_, M>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => create_resource_fut.await.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
}),
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let reverse_lookup_entry = |v: String| diesel_models::ReverseLookupNew {
sk_id: identifier.clone(),
pk_id: key_str.clone(),
lookup_id: v,
source: resource_type.to_string(),
updated_by: storage_scheme.to_string(),
};
let results = reverse_lookups
.into_iter()
.map(|v| self.insert_reverse_lookup(reverse_lookup_entry(v), storage_scheme));
futures::future::try_join_all(results).await?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(insertable),
},
};
match Box::pin(kv_wrapper::<M, _, _>(
self,
KvOperation::<M>::HSetNx(&identifier, &resource_new, redis_entry),
key.clone(),
))
.await
.map_err(|err| err.to_redis_failed_response(&key.to_string()))?
.try_into_hsetnx()
{
Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
entity: resource_type,
key: Some(key_str),
}
.into()),
Ok(HsetnxReply::KeySet) => Ok(resource_new),
Err(er) => Err(er).change_context(errors::StorageError::KVError),
}
}
}?
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
pub async fn update_resource<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
update_resource_fut: R,
updated_resource: M,
UpdateResourceParams {
updateable,
operation,
}: UpdateResourceParams<'_>,
) -> error_stack::Result<D, errors::StorageError>
where
D: Debug + Sync + Conversion,
M: StorageModel<D>,
R: futures::Future<Output = error_stack::Result<M, DatabaseError>> + Send,
{
match operation {
Op::Update(key, field, updated_by) => {
let storage_scheme = Box::pin(decide_storage_scheme::<_, M>(
self,
storage_scheme,
Op::Update(key.clone(), field, updated_by),
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
update_resource_fut.await.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})
}
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let redis_value = serde_json::to_string(&updated_resource)
.change_context(errors::StorageError::SerializationFailed)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
updatable: Box::new(updateable),
},
};
Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<M>::Hset((field, redis_value), redis_entry),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hset()
.change_context(errors::StorageError::KVError)?;
Ok(updated_resource)
}
}
}
_ => Err(errors::StorageError::KVError.into()),
}?
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
}
pub async fn filter_resources<D, R, M>(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
filter_resource_db_fut: R,
filter_fn: impl Fn(&M) -> bool,
FilterResourceParams {
key,
pattern,
limit,
}: FilterResourceParams<'_>,
) -> error_stack::Result<Vec<D>, errors::StorageError>
where
D: Debug + Sync + Conversion,
M: StorageModel<D>,
R: futures::Future<Output = error_stack::Result<Vec<M>, DatabaseError>> + Send,
{
let db_call = || async {
filter_resource_db_fut.await.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})
};
let resources = match storage_scheme {
MerchantStorageScheme::PostgresOnly => db_call().await,
MerchantStorageScheme::RedisKv => {
let redis_fut = async {
let kv_result = Box::pin(kv_wrapper::<M, _, _>(
self,
KvOperation::<M>::Scan(pattern),
key,
))
.await?
.try_into_scan();
kv_result.map(|records| records.into_iter().filter(filter_fn).collect())
};
Box::pin(find_all_combined_kv_database(redis_fut, db_call, limit)).await
}
}?;
let resource_futures = resources
.into_iter()
.map(|pm| async {
pm.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)
})
.collect::<Vec<_>>();
futures::future::try_join_all(resource_futures).await
}
}
#[cfg(not(feature = "payouts"))]
impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {}
#[cfg(not(feature = "payouts"))]
impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {}
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/kv_router_store.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_storage_impl_-3094499605474430919
|
clm
|
file
|
// Repository: hyperswitch
// Crate: storage_impl
// File: crates/storage_impl/src/redis.rs
// Contains: 1 structs, 0 enums
pub mod cache;
pub mod kv_store;
pub mod pub_sub;
use std::sync::{atomic, Arc};
use router_env::tracing::Instrument;
use self::{kv_store::RedisConnInterface, pub_sub::PubSubInterface};
#[derive(Clone)]
pub struct RedisStore {
// Maybe expose the redis_conn via traits instead of the making the field public
pub(crate) redis_conn: Arc<redis_interface::RedisConnectionPool>,
}
impl std::fmt::Debug for RedisStore {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("CacheStore")
.field("redis_conn", &"Redis conn doesn't implement debug")
.finish()
}
}
impl RedisStore {
pub async fn new(
conf: &redis_interface::RedisSettings,
) -> error_stack::Result<Self, redis_interface::errors::RedisError> {
Ok(Self {
redis_conn: Arc::new(redis_interface::RedisConnectionPool::new(conf).await?),
})
}
pub fn set_error_callback(&self, callback: tokio::sync::oneshot::Sender<()>) {
let redis_clone = self.redis_conn.clone();
let _task_handle = tokio::spawn(
async move {
redis_clone.on_error(callback).await;
}
.in_current_span(),
);
}
}
impl RedisConnInterface for RedisStore {
fn get_redis_conn(
&self,
) -> error_stack::Result<
Arc<redis_interface::RedisConnectionPool>,
redis_interface::errors::RedisError,
> {
if self
.redis_conn
.is_redis_available
.load(atomic::Ordering::SeqCst)
{
Ok(self.redis_conn.clone())
} else {
Err(redis_interface::errors::RedisError::RedisConnectionError.into())
}
}
}
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/redis.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_storage_impl_3276040950322020961
|
clm
|
file
|
// Repository: hyperswitch
// Crate: storage_impl
// File: crates/storage_impl/src/database/store.rs
// Contains: 3 structs, 0 enums
use async_bb8_diesel::{AsyncConnection, ConnectionError};
use bb8::CustomizeConnection;
use common_utils::{types::TenantConfig, DbConnectionParams};
use diesel::PgConnection;
use error_stack::ResultExt;
use crate::{
config::Database,
errors::{StorageError, StorageResult},
};
pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;
pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>;
#[async_trait::async_trait]
pub trait DatabaseStore: Clone + Send + Sync {
type Config: Send;
async fn new(
config: Self::Config,
tenant_config: &dyn TenantConfig,
test_transaction: bool,
) -> StorageResult<Self>;
fn get_master_pool(&self) -> &PgPool;
fn get_replica_pool(&self) -> &PgPool;
fn get_accounts_master_pool(&self) -> &PgPool;
fn get_accounts_replica_pool(&self) -> &PgPool;
}
#[derive(Debug, Clone)]
pub struct Store {
pub master_pool: PgPool,
pub accounts_pool: PgPool,
}
#[async_trait::async_trait]
impl DatabaseStore for Store {
type Config = Database;
async fn new(
config: Database,
tenant_config: &dyn TenantConfig,
test_transaction: bool,
) -> StorageResult<Self> {
Ok(Self {
master_pool: diesel_make_pg_pool(&config, tenant_config.get_schema(), test_transaction)
.await?,
accounts_pool: diesel_make_pg_pool(
&config,
tenant_config.get_accounts_schema(),
test_transaction,
)
.await?,
})
}
fn get_master_pool(&self) -> &PgPool {
&self.master_pool
}
fn get_replica_pool(&self) -> &PgPool {
&self.master_pool
}
fn get_accounts_master_pool(&self) -> &PgPool {
&self.accounts_pool
}
fn get_accounts_replica_pool(&self) -> &PgPool {
&self.accounts_pool
}
}
#[derive(Debug, Clone)]
pub struct ReplicaStore {
pub master_pool: PgPool,
pub replica_pool: PgPool,
pub accounts_master_pool: PgPool,
pub accounts_replica_pool: PgPool,
}
#[async_trait::async_trait]
impl DatabaseStore for ReplicaStore {
type Config = (Database, Database);
async fn new(
config: (Database, Database),
tenant_config: &dyn TenantConfig,
test_transaction: bool,
) -> StorageResult<Self> {
let (master_config, replica_config) = config;
let master_pool =
diesel_make_pg_pool(&master_config, tenant_config.get_schema(), test_transaction)
.await
.attach_printable("failed to create master pool")?;
let accounts_master_pool = diesel_make_pg_pool(
&master_config,
tenant_config.get_accounts_schema(),
test_transaction,
)
.await
.attach_printable("failed to create accounts master pool")?;
let replica_pool = diesel_make_pg_pool(
&replica_config,
tenant_config.get_schema(),
test_transaction,
)
.await
.attach_printable("failed to create replica pool")?;
let accounts_replica_pool = diesel_make_pg_pool(
&replica_config,
tenant_config.get_accounts_schema(),
test_transaction,
)
.await
.attach_printable("failed to create accounts pool")?;
Ok(Self {
master_pool,
replica_pool,
accounts_master_pool,
accounts_replica_pool,
})
}
fn get_master_pool(&self) -> &PgPool {
&self.master_pool
}
fn get_replica_pool(&self) -> &PgPool {
&self.replica_pool
}
fn get_accounts_master_pool(&self) -> &PgPool {
&self.accounts_master_pool
}
fn get_accounts_replica_pool(&self) -> &PgPool {
&self.accounts_replica_pool
}
}
pub async fn diesel_make_pg_pool(
database: &Database,
schema: &str,
test_transaction: bool,
) -> StorageResult<PgPool> {
let database_url = database.get_database_url(schema);
let manager = async_bb8_diesel::ConnectionManager::<PgConnection>::new(database_url);
let mut pool = bb8::Pool::builder()
.max_size(database.pool_size)
.min_idle(database.min_idle)
.queue_strategy(database.queue_strategy.into())
.connection_timeout(std::time::Duration::from_secs(database.connection_timeout))
.max_lifetime(database.max_lifetime.map(std::time::Duration::from_secs));
if test_transaction {
pool = pool.connection_customizer(Box::new(TestTransaction));
}
pool.build(manager)
.await
.change_context(StorageError::InitializationError)
.attach_printable("Failed to create PostgreSQL connection pool")
}
#[derive(Debug)]
struct TestTransaction;
#[async_trait::async_trait]
impl CustomizeConnection<PgPooledConn, ConnectionError> for TestTransaction {
#[allow(clippy::unwrap_used)]
async fn on_acquire(&self, conn: &mut PgPooledConn) -> Result<(), ConnectionError> {
use diesel::Connection;
conn.run(|conn| {
conn.begin_test_transaction().unwrap();
Ok(())
})
.await
}
}
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/database/store.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 3,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_storage_impl_-7646703352176012178
|
clm
|
file
|
// Repository: hyperswitch
// Crate: storage_impl
// File: crates/storage_impl/src/redis/cache.rs
// Contains: 2 structs, 1 enums
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
);
}
}
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/redis/cache.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_-6576528134363597775
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/request.rs
// Contains: 2 structs, 2 enums
use masking::{Maskable, Secret};
use reqwest::multipart::Form;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
pub type Headers = std::collections::HashSet<(String, Maskable<String>)>;
#[derive(
Clone,
Copy,
Debug,
Eq,
PartialEq,
Deserialize,
Serialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[serde(rename_all = "UPPERCASE")]
#[strum(serialize_all = "UPPERCASE")]
pub enum Method {
Get,
Post,
Put,
Delete,
Patch,
}
#[derive(Deserialize, Serialize, Debug)]
pub enum ContentType {
Json,
FormUrlEncoded,
FormData,
Xml,
}
fn default_request_headers() -> [(String, Maskable<String>); 1] {
use http::header;
[(header::VIA.to_string(), "HyperSwitch".to_string().into())]
}
#[derive(Debug)]
pub struct Request {
pub url: String,
pub headers: Headers,
pub method: Method,
pub certificate: Option<Secret<String>>,
pub certificate_key: Option<Secret<String>>,
pub body: Option<RequestContent>,
pub ca_certificate: Option<Secret<String>>,
}
impl std::fmt::Debug for RequestContent {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Json(_) => "JsonRequestBody",
Self::FormUrlEncoded(_) => "FormUrlEncodedRequestBody",
Self::FormData(_) => "FormDataRequestBody",
Self::Xml(_) => "XmlRequestBody",
Self::RawBytes(_) => "RawBytesRequestBody",
})
}
}
pub enum RequestContent {
Json(Box<dyn masking::ErasedMaskSerialize + Send>),
FormUrlEncoded(Box<dyn masking::ErasedMaskSerialize + Send>),
FormData((Form, Box<dyn masking::ErasedMaskSerialize + Send>)),
Xml(Box<dyn masking::ErasedMaskSerialize + Send>),
RawBytes(Vec<u8>),
}
impl RequestContent {
pub fn get_inner_value(&self) -> Secret<String> {
match self {
Self::Json(i) => serde_json::to_string(&i).unwrap_or_default().into(),
Self::FormUrlEncoded(i) => serde_urlencoded::to_string(i).unwrap_or_default().into(),
Self::Xml(i) => quick_xml::se::to_string(&i).unwrap_or_default().into(),
Self::FormData((_, i)) => serde_json::to_string(i).unwrap_or_default().into(),
Self::RawBytes(_) => String::new().into(),
}
}
}
impl Request {
pub fn new(method: Method, url: &str) -> Self {
Self {
method,
url: String::from(url),
headers: std::collections::HashSet::new(),
certificate: None,
certificate_key: None,
body: None,
ca_certificate: None,
}
}
pub fn set_body<T: Into<RequestContent>>(&mut self, body: T) {
self.body.replace(body.into());
}
pub fn add_default_headers(&mut self) {
self.headers.extend(default_request_headers());
}
pub fn add_header(&mut self, header: &str, value: Maskable<String>) {
self.headers.insert((String::from(header), value));
}
pub fn add_certificate(&mut self, certificate: Option<Secret<String>>) {
self.certificate = certificate;
}
pub fn add_certificate_key(&mut self, certificate_key: Option<Secret<String>>) {
self.certificate = certificate_key;
}
}
#[derive(Debug)]
pub struct RequestBuilder {
pub url: String,
pub headers: Headers,
pub method: Method,
pub certificate: Option<Secret<String>>,
pub certificate_key: Option<Secret<String>>,
pub body: Option<RequestContent>,
pub ca_certificate: Option<Secret<String>>,
}
impl RequestBuilder {
pub fn new() -> Self {
Self {
method: Method::Get,
url: String::with_capacity(1024),
headers: std::collections::HashSet::new(),
certificate: None,
certificate_key: None,
body: None,
ca_certificate: None,
}
}
pub fn url(mut self, url: &str) -> Self {
self.url = url.into();
self
}
pub fn method(mut self, method: Method) -> Self {
self.method = method;
self
}
pub fn attach_default_headers(mut self) -> Self {
self.headers.extend(default_request_headers());
self
}
pub fn header(mut self, header: &str, value: &str) -> Self {
self.headers.insert((header.into(), value.into()));
self
}
pub fn headers(mut self, headers: Vec<(String, Maskable<String>)>) -> Self {
self.headers.extend(headers);
self
}
pub fn set_optional_body<T: Into<RequestContent>>(mut self, body: Option<T>) -> Self {
body.map(|body| self.body.replace(body.into()));
self
}
pub fn set_body<T: Into<RequestContent>>(mut self, body: T) -> Self {
self.body.replace(body.into());
self
}
pub fn add_certificate(mut self, certificate: Option<Secret<String>>) -> Self {
self.certificate = certificate;
self
}
pub fn add_certificate_key(mut self, certificate_key: Option<Secret<String>>) -> Self {
self.certificate_key = certificate_key;
self
}
pub fn add_ca_certificate_pem(mut self, ca_certificate: Option<Secret<String>>) -> Self {
self.ca_certificate = ca_certificate;
self
}
pub fn build(self) -> Request {
Request {
method: self.method,
url: self.url,
headers: self.headers,
certificate: self.certificate,
certificate_key: self.certificate_key,
body: self.body,
ca_certificate: self.ca_certificate,
}
}
}
impl Default for RequestBuilder {
fn default() -> Self {
Self::new()
}
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/request.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_4097855999874423392
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/types.rs
// Contains: 19 structs, 3 enums
//! Types that can be used in other crates
pub mod keymanager;
/// Enum for Authentication Level
pub mod authentication;
/// User related types
pub mod user;
/// types that are wrappers around primitive types
pub mod primitive_wrappers;
use std::{
borrow::Cow,
fmt::Display,
iter::Sum,
num::NonZeroI64,
ops::{Add, Mul, Sub},
primitive::i64,
str::FromStr,
};
use common_enums::enums;
use diesel::{
backend::Backend,
deserialize,
deserialize::FromSql,
serialize::{Output, ToSql},
sql_types,
sql_types::Jsonb,
AsExpression, FromSqlRow, Queryable,
};
use error_stack::{report, ResultExt};
pub use primitive_wrappers::bool_wrappers::{
AlwaysRequestExtendedAuthorization, ExtendedAuthorizationAppliedBool,
RequestExtendedAuthorizationBool,
};
use rust_decimal::{
prelude::{FromPrimitive, ToPrimitive},
Decimal,
};
use semver::Version;
use serde::{de::Visitor, Deserialize, Deserializer, Serialize};
use thiserror::Error;
use time::PrimitiveDateTime;
use utoipa::ToSchema;
use crate::{
consts::{
self, MAX_DESCRIPTION_LENGTH, MAX_STATEMENT_DESCRIPTOR_LENGTH, PUBLISHABLE_KEY_LENGTH,
},
errors::{CustomResult, ParsingError, PercentageError, ValidationError},
fp_utils::when,
id_type, impl_enum_str,
};
/// Represents Percentage Value between 0 and 100 both inclusive
#[derive(Clone, Default, Debug, PartialEq, Serialize)]
pub struct Percentage<const PRECISION: u8> {
// this value will range from 0 to 100, decimal length defined by precision macro
/// Percentage value ranging between 0 and 100
percentage: f32,
}
fn get_invalid_percentage_error_message(precision: u8) -> String {
format!(
"value should be a float between 0 to 100 and precise to only upto {precision} decimal digits",
)
}
impl<const PRECISION: u8> Percentage<PRECISION> {
/// construct percentage using a string representation of float value
pub fn from_string(value: String) -> CustomResult<Self, PercentageError> {
if Self::is_valid_string_value(&value)? {
Ok(Self {
percentage: value
.parse::<f32>()
.change_context(PercentageError::InvalidPercentageValue)?,
})
} else {
Err(report!(PercentageError::InvalidPercentageValue))
.attach_printable(get_invalid_percentage_error_message(PRECISION))
}
}
/// function to get percentage value
pub fn get_percentage(&self) -> f32 {
self.percentage
}
/// apply the percentage to amount and ceil the result
#[allow(clippy::as_conversions)]
pub fn apply_and_ceil_result(
&self,
amount: MinorUnit,
) -> CustomResult<MinorUnit, PercentageError> {
let max_amount = i64::MAX / 10000;
let amount = amount.0;
if amount > max_amount {
// value gets rounded off after i64::MAX/10000
Err(report!(PercentageError::UnableToApplyPercentage {
percentage: self.percentage,
amount: MinorUnit::new(amount),
}))
.attach_printable(format!(
"Cannot calculate percentage for amount greater than {max_amount}",
))
} else {
let percentage_f64 = f64::from(self.percentage);
let result = (amount as f64 * (percentage_f64 / 100.0)).ceil() as i64;
Ok(MinorUnit::new(result))
}
}
fn is_valid_string_value(value: &str) -> CustomResult<bool, PercentageError> {
let float_value = Self::is_valid_float_string(value)?;
Ok(Self::is_valid_range(float_value) && Self::is_valid_precision_length(value))
}
fn is_valid_float_string(value: &str) -> CustomResult<f32, PercentageError> {
value
.parse::<f32>()
.change_context(PercentageError::InvalidPercentageValue)
}
fn is_valid_range(value: f32) -> bool {
(0.0..=100.0).contains(&value)
}
fn is_valid_precision_length(value: &str) -> bool {
if value.contains('.') {
// if string has '.' then take the decimal part and verify precision length
match value.split('.').next_back() {
Some(decimal_part) => {
decimal_part.trim_end_matches('0').len() <= <u8 as Into<usize>>::into(PRECISION)
}
// will never be None
None => false,
}
} else {
// if there is no '.' then it is a whole number with no decimal part. So return true
true
}
}
}
// custom serde deserialization function
struct PercentageVisitor<const PRECISION: u8> {}
impl<'de, const PRECISION: u8> Visitor<'de> for PercentageVisitor<PRECISION> {
type Value = Percentage<PRECISION>;
fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
formatter.write_str("Percentage object")
}
fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
where
A: serde::de::MapAccess<'de>,
{
let mut percentage_value = None;
while let Some(key) = map.next_key::<String>()? {
if key.eq("percentage") {
if percentage_value.is_some() {
return Err(serde::de::Error::duplicate_field("percentage"));
}
percentage_value = Some(map.next_value::<serde_json::Value>()?);
} else {
// Ignore unknown fields
let _: serde::de::IgnoredAny = map.next_value()?;
}
}
if let Some(value) = percentage_value {
let string_value = value.to_string();
Ok(Percentage::from_string(string_value.clone()).map_err(|_| {
serde::de::Error::invalid_value(
serde::de::Unexpected::Other(&format!("percentage value {string_value}")),
&&*get_invalid_percentage_error_message(PRECISION),
)
})?)
} else {
Err(serde::de::Error::missing_field("percentage"))
}
}
}
impl<'de, const PRECISION: u8> Deserialize<'de> for Percentage<PRECISION> {
fn deserialize<D>(data: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
data.deserialize_map(PercentageVisitor::<PRECISION> {})
}
}
/// represents surcharge type and value
#[derive(Clone, Debug, PartialEq, Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case", tag = "type", content = "value")]
pub enum Surcharge {
/// Fixed Surcharge value
Fixed(MinorUnit),
/// Surcharge percentage
Rate(Percentage<{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH }>),
}
/// This struct lets us represent a semantic version type
#[derive(Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, Ord, PartialOrd)]
#[diesel(sql_type = Jsonb)]
#[derive(Serialize, serde::Deserialize)]
pub struct SemanticVersion(#[serde(with = "Version")] Version);
impl SemanticVersion {
/// returns major version number
pub fn get_major(&self) -> u64 {
self.0.major
}
/// returns minor version number
pub fn get_minor(&self) -> u64 {
self.0.minor
}
/// Constructs new SemanticVersion instance
pub fn new(major: u64, minor: u64, patch: u64) -> Self {
Self(Version::new(major, minor, patch))
}
}
impl Display for SemanticVersion {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl FromStr for SemanticVersion {
type Err = error_stack::Report<ParsingError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Self(Version::from_str(s).change_context(
ParsingError::StructParseFailure("SemanticVersion"),
)?))
}
}
crate::impl_to_sql_from_sql_json!(SemanticVersion);
/// Amount convertor trait for connector
pub trait AmountConvertor: Send {
/// Output type for the connector
type Output;
/// helps in conversion of connector required amount type
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>>;
/// helps in converting back connector required amount type to core minor unit
fn convert_back(
&self,
amount: Self::Output,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>>;
}
/// Connector required amount type
#[derive(Default, Debug, Clone, Copy, PartialEq)]
pub struct StringMinorUnitForConnector;
impl AmountConvertor for StringMinorUnitForConnector {
type Output = StringMinorUnit;
fn convert(
&self,
amount: MinorUnit,
_currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_string()
}
fn convert_back(
&self,
amount: Self::Output,
_currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64()
}
}
/// Core required conversion type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct StringMajorUnitForCore;
impl AmountConvertor for StringMajorUnitForCore {
type Output = StringMajorUnit;
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_major_unit_as_string(currency)
}
fn convert_back(
&self,
amount: StringMajorUnit,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64(currency)
}
}
/// Connector required amount type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct StringMajorUnitForConnector;
impl AmountConvertor for StringMajorUnitForConnector {
type Output = StringMajorUnit;
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_major_unit_as_string(currency)
}
fn convert_back(
&self,
amount: StringMajorUnit,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64(currency)
}
}
/// Connector required amount type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct FloatMajorUnitForConnector;
impl AmountConvertor for FloatMajorUnitForConnector {
type Output = FloatMajorUnit;
fn convert(
&self,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
amount.to_major_unit_as_f64(currency)
}
fn convert_back(
&self,
amount: FloatMajorUnit,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
amount.to_minor_unit_as_i64(currency)
}
}
/// Connector required amount type
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct MinorUnitForConnector;
impl AmountConvertor for MinorUnitForConnector {
type Output = MinorUnit;
fn convert(
&self,
amount: MinorUnit,
_currency: enums::Currency,
) -> Result<Self::Output, error_stack::Report<ParsingError>> {
Ok(amount)
}
fn convert_back(
&self,
amount: MinorUnit,
_currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
Ok(amount)
}
}
/// This Unit struct represents MinorUnit in which core amount works
#[derive(
Default,
Debug,
serde::Deserialize,
AsExpression,
serde::Serialize,
Clone,
Copy,
PartialEq,
Eq,
Hash,
ToSchema,
PartialOrd,
)]
#[diesel(sql_type = sql_types::BigInt)]
pub struct MinorUnit(i64);
impl MinorUnit {
/// gets amount as i64 value will be removed in future
pub fn get_amount_as_i64(self) -> i64 {
self.0
}
/// forms a new minor default unit i.e zero
pub fn zero() -> Self {
Self(0)
}
/// forms a new minor unit from amount
pub fn new(value: i64) -> Self {
Self(value)
}
/// checks if the amount is greater than the given value
pub fn is_greater_than(&self, value: i64) -> bool {
self.get_amount_as_i64() > value
}
/// Convert the amount to its major denomination based on Currency and return String
/// Paypal Connector accepts Zero and Two decimal currency but not three decimal and it should be updated as required for 3 decimal currencies.
/// Paypal Ref - https://developer.paypal.com/docs/reports/reference/paypal-supported-currencies/
fn to_major_unit_as_string(
self,
currency: enums::Currency,
) -> Result<StringMajorUnit, error_stack::Report<ParsingError>> {
let amount_f64 = self.to_major_unit_as_f64(currency)?;
let amount_string = if currency.is_zero_decimal_currency() {
amount_f64.0.to_string()
} else if currency.is_three_decimal_currency() {
format!("{:.3}", amount_f64.0)
} else {
format!("{:.2}", amount_f64.0)
};
Ok(StringMajorUnit::new(amount_string))
}
/// Convert the amount to its major denomination based on Currency and return f64
fn to_major_unit_as_f64(
self,
currency: enums::Currency,
) -> Result<FloatMajorUnit, error_stack::Report<ParsingError>> {
let amount_decimal =
Decimal::from_i64(self.0).ok_or(ParsingError::I64ToDecimalConversionFailure)?;
let amount = if currency.is_zero_decimal_currency() {
amount_decimal
} else if currency.is_three_decimal_currency() {
amount_decimal / Decimal::from(1000)
} else {
amount_decimal / Decimal::from(100)
};
let amount_f64 = amount
.to_f64()
.ok_or(ParsingError::FloatToDecimalConversionFailure)?;
Ok(FloatMajorUnit::new(amount_f64))
}
///Convert minor unit to string minor unit
fn to_minor_unit_as_string(self) -> Result<StringMinorUnit, error_stack::Report<ParsingError>> {
Ok(StringMinorUnit::new(self.0.to_string()))
}
}
impl From<NonZeroI64> for MinorUnit {
fn from(val: NonZeroI64) -> Self {
Self::new(val.get())
}
}
impl Display for MinorUnit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl<DB> FromSql<sql_types::BigInt, DB> for MinorUnit
where
DB: Backend,
i64: FromSql<sql_types::BigInt, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = i64::from_sql(value)?;
Ok(Self(val))
}
}
impl<DB> ToSql<sql_types::BigInt, DB> for MinorUnit
where
DB: Backend,
i64: ToSql<sql_types::BigInt, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> Queryable<sql_types::BigInt, DB> for MinorUnit
where
DB: Backend,
Self: FromSql<sql_types::BigInt, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl Add for MinorUnit {
type Output = Self;
fn add(self, a2: Self) -> Self {
Self(self.0 + a2.0)
}
}
impl Sub for MinorUnit {
type Output = Self;
fn sub(self, a2: Self) -> Self {
Self(self.0 - a2.0)
}
}
impl Mul<u16> for MinorUnit {
type Output = Self;
fn mul(self, a2: u16) -> Self::Output {
Self(self.0 * i64::from(a2))
}
}
impl Sum for MinorUnit {
fn sum<I: Iterator<Item = Self>>(iter: I) -> Self {
iter.fold(Self(0), |a, b| a + b)
}
}
/// Connector specific types to send
#[derive(
Default,
Debug,
serde::Deserialize,
AsExpression,
serde::Serialize,
Clone,
PartialEq,
Eq,
Hash,
ToSchema,
PartialOrd,
)]
#[diesel(sql_type = sql_types::Text)]
pub struct StringMinorUnit(String);
impl StringMinorUnit {
/// forms a new minor unit in string from amount
fn new(value: String) -> Self {
Self(value)
}
/// converts to minor unit i64 from minor unit string value
fn to_minor_unit_as_i64(&self) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
let amount_string = &self.0;
let amount_decimal = Decimal::from_str(amount_string).map_err(|e| {
ParsingError::StringToDecimalConversionFailure {
error: e.to_string(),
}
})?;
let amount_i64 = amount_decimal
.to_i64()
.ok_or(ParsingError::DecimalToI64ConversionFailure)?;
Ok(MinorUnit::new(amount_i64))
}
}
impl Display for StringMinorUnit {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl<DB> FromSql<sql_types::Text, DB> for StringMinorUnit
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(value)?;
Ok(Self(val))
}
}
impl<DB> ToSql<sql_types::Text, DB> for StringMinorUnit
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> Queryable<sql_types::Text, DB> for StringMinorUnit
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
/// Connector specific types to send
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq)]
pub struct FloatMajorUnit(f64);
impl FloatMajorUnit {
/// forms a new major unit from amount
fn new(value: f64) -> Self {
Self(value)
}
/// forms a new major unit with zero amount
pub fn zero() -> Self {
Self(0.0)
}
/// converts to minor unit as i64 from FloatMajorUnit
fn to_minor_unit_as_i64(
self,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
let amount_decimal =
Decimal::from_f64(self.0).ok_or(ParsingError::FloatToDecimalConversionFailure)?;
let amount = if currency.is_zero_decimal_currency() {
amount_decimal
} else if currency.is_three_decimal_currency() {
amount_decimal * Decimal::from(1000)
} else {
amount_decimal * Decimal::from(100)
};
let amount_i64 = amount
.to_i64()
.ok_or(ParsingError::DecimalToI64ConversionFailure)?;
Ok(MinorUnit::new(amount_i64))
}
}
/// Connector specific types to send
#[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq)]
pub struct StringMajorUnit(String);
impl StringMajorUnit {
/// forms a new major unit from amount
fn new(value: String) -> Self {
Self(value)
}
/// Converts to minor unit as i64 from StringMajorUnit
fn to_minor_unit_as_i64(
&self,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<ParsingError>> {
let amount_decimal = Decimal::from_str(&self.0).map_err(|e| {
ParsingError::StringToDecimalConversionFailure {
error: e.to_string(),
}
})?;
let amount = if currency.is_zero_decimal_currency() {
amount_decimal
} else if currency.is_three_decimal_currency() {
amount_decimal * Decimal::from(1000)
} else {
amount_decimal * Decimal::from(100)
};
let amount_i64 = amount
.to_i64()
.ok_or(ParsingError::DecimalToI64ConversionFailure)?;
Ok(MinorUnit::new(amount_i64))
}
/// forms a new StringMajorUnit default unit i.e zero
pub fn zero() -> Self {
Self("0".to_string())
}
/// Get string amount from struct to be removed in future
pub fn get_amount_as_string(&self) -> String {
self.0.clone()
}
}
#[derive(
Debug,
serde::Deserialize,
AsExpression,
serde::Serialize,
Clone,
PartialEq,
Eq,
Hash,
ToSchema,
PartialOrd,
)]
#[diesel(sql_type = sql_types::Text)]
/// This domain type can be used for any url
pub struct Url(url::Url);
impl Url {
/// Get string representation of the url
pub fn get_string_repr(&self) -> &str {
self.0.as_str()
}
/// wrap the url::Url in Url type
pub fn wrap(url: url::Url) -> Self {
Self(url)
}
/// Get the inner url
pub fn into_inner(self) -> url::Url {
self.0
}
/// Add query params to the url
pub fn add_query_params(mut self, (key, value): (&str, &str)) -> Self {
let url = self
.0
.query_pairs_mut()
.append_pair(key, value)
.finish()
.clone();
Self(url)
}
}
impl<DB> ToSql<sql_types::Text, DB> for Url
where
DB: Backend,
str: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
let url_string = self.0.as_str();
url_string.to_sql(out)
}
}
impl<DB> FromSql<sql_types::Text, DB> for Url
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(value)?;
let url = url::Url::parse(&val)?;
Ok(Self(url))
}
}
/// A type representing a range of time for filtering, including a mandatory start time and an optional end time.
#[derive(
Debug, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, Hash, ToSchema,
)]
pub struct TimeRange {
/// The start time to filter payments list or to get list of filters. To get list of filters start time is needed to be passed
#[serde(with = "crate::custom_serde::iso8601")]
#[serde(alias = "startTime")]
pub start_time: PrimitiveDateTime,
/// The end time to filter payments list or to get list of filters. If not passed the default time is now
#[serde(default, with = "crate::custom_serde::iso8601::option")]
#[serde(alias = "endTime")]
pub end_time: Option<PrimitiveDateTime>,
}
#[cfg(test)]
mod amount_conversion_tests {
#![allow(clippy::unwrap_used)]
use super::*;
const TWO_DECIMAL_CURRENCY: enums::Currency = enums::Currency::USD;
const THREE_DECIMAL_CURRENCY: enums::Currency = enums::Currency::BHD;
const ZERO_DECIMAL_CURRENCY: enums::Currency = enums::Currency::JPY;
#[test]
fn amount_conversion_to_float_major_unit() {
let request_amount = MinorUnit::new(999999999);
let required_conversion = FloatMajorUnitForConnector;
// Two decimal currency conversions
let converted_amount = required_conversion
.convert(request_amount, TWO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_amount.0, 9999999.99);
let converted_back_amount = required_conversion
.convert_back(converted_amount, TWO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
// Three decimal currency conversions
let converted_amount = required_conversion
.convert(request_amount, THREE_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_amount.0, 999999.999);
let converted_back_amount = required_conversion
.convert_back(converted_amount, THREE_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
// Zero decimal currency conversions
let converted_amount = required_conversion
.convert(request_amount, ZERO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_amount.0, 999999999.0);
let converted_back_amount = required_conversion
.convert_back(converted_amount, ZERO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
}
#[test]
fn amount_conversion_to_string_major_unit() {
let request_amount = MinorUnit::new(999999999);
let required_conversion = StringMajorUnitForConnector;
// Two decimal currency conversions
let converted_amount_two_decimal_currency = required_conversion
.convert(request_amount, TWO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(
converted_amount_two_decimal_currency.0,
"9999999.99".to_string()
);
let converted_back_amount = required_conversion
.convert_back(converted_amount_two_decimal_currency, TWO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
// Three decimal currency conversions
let converted_amount_three_decimal_currency = required_conversion
.convert(request_amount, THREE_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(
converted_amount_three_decimal_currency.0,
"999999.999".to_string()
);
let converted_back_amount = required_conversion
.convert_back(
converted_amount_three_decimal_currency,
THREE_DECIMAL_CURRENCY,
)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
// Zero decimal currency conversions
let converted_amount = required_conversion
.convert(request_amount, ZERO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_amount.0, "999999999".to_string());
let converted_back_amount = required_conversion
.convert_back(converted_amount, ZERO_DECIMAL_CURRENCY)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
}
#[test]
fn amount_conversion_to_string_minor_unit() {
let request_amount = MinorUnit::new(999999999);
let currency = TWO_DECIMAL_CURRENCY;
let required_conversion = StringMinorUnitForConnector;
let converted_amount = required_conversion
.convert(request_amount, currency)
.unwrap();
assert_eq!(converted_amount.0, "999999999".to_string());
let converted_back_amount = required_conversion
.convert_back(converted_amount, currency)
.unwrap();
assert_eq!(converted_back_amount, request_amount);
}
}
// Charges structs
#[derive(
Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
/// Charge specific fields for controlling the revert of funds from either platform or connected account. Check sub-fields for more details.
pub struct ChargeRefunds {
/// Identifier for charge created for the payment
pub charge_id: String,
/// Toggle for reverting the application fee that was collected for the payment.
/// If set to false, the funds are pulled from the destination account.
pub revert_platform_fee: Option<bool>,
/// Toggle for reverting the transfer that was made during the charge.
/// If set to false, the funds are pulled from the main platform's account.
pub revert_transfer: Option<bool>,
}
crate::impl_to_sql_from_sql_json!(ChargeRefunds);
/// A common type of domain type that can be used for fields that contain a string with restriction of length
#[derive(Debug, Clone, Serialize, Hash, PartialEq, Eq, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub(crate) struct LengthString<const MAX_LENGTH: u16, const MIN_LENGTH: u16>(String);
/// Error generated from violation of constraints for MerchantReferenceId
#[derive(Debug, Error, PartialEq, Eq)]
pub(crate) enum LengthStringError {
#[error("the maximum allowed length for this field is {0}")]
/// Maximum length of string violated
MaxLengthViolated(u16),
#[error("the minimum required length for this field is {0}")]
/// Minimum length of string violated
MinLengthViolated(u16),
}
impl<const MAX_LENGTH: u16, const MIN_LENGTH: u16> LengthString<MAX_LENGTH, MIN_LENGTH> {
/// Generates new [MerchantReferenceId] from the given input string
pub fn from(input_string: Cow<'static, str>) -> Result<Self, LengthStringError> {
let trimmed_input_string = input_string.trim().to_string();
let length_of_input_string = u16::try_from(trimmed_input_string.len())
.map_err(|_| LengthStringError::MaxLengthViolated(MAX_LENGTH))?;
when(length_of_input_string > MAX_LENGTH, || {
Err(LengthStringError::MaxLengthViolated(MAX_LENGTH))
})?;
when(length_of_input_string < MIN_LENGTH, || {
Err(LengthStringError::MinLengthViolated(MIN_LENGTH))
})?;
Ok(Self(trimmed_input_string))
}
pub(crate) fn new_unchecked(input_string: String) -> Self {
Self(input_string)
}
}
impl<'de, const MAX_LENGTH: u16, const MIN_LENGTH: u16> Deserialize<'de>
for LengthString<MAX_LENGTH, MIN_LENGTH>
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
let deserialized_string = String::deserialize(deserializer)?;
Self::from(deserialized_string.into()).map_err(serde::de::Error::custom)
}
}
impl<DB, const MAX_LENGTH: u16, const MIN_LENGTH: u16> FromSql<sql_types::Text, DB>
for LengthString<MAX_LENGTH, MIN_LENGTH>
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(bytes)?;
Ok(Self(val))
}
}
impl<DB, const MAX_LENGTH: u16, const MIN_LENGTH: u16> ToSql<sql_types::Text, DB>
for LengthString<MAX_LENGTH, MIN_LENGTH>
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB, const MAX_LENGTH: u16, const MIN_LENGTH: u16> Queryable<sql_types::Text, DB>
for LengthString<MAX_LENGTH, MIN_LENGTH>
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
/// Domain type for description
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub struct Description(LengthString<MAX_DESCRIPTION_LENGTH, 1>);
impl Description {
/// Create a new Description Domain type without any length check from a static str
pub fn from_str_unchecked(input_str: &'static str) -> Self {
Self(LengthString::new_unchecked(input_str.to_owned()))
}
// TODO: Remove this function in future once description in router data is updated to domain type
/// Get the string representation of the description
pub fn get_string_repr(&self) -> &str {
&self.0 .0
}
}
/// Domain type for Statement Descriptor
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub struct StatementDescriptor(LengthString<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>);
impl<DB> Queryable<sql_types::Text, DB> for Description
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for Description
where
DB: Backend,
LengthString<MAX_DESCRIPTION_LENGTH, 1>: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = LengthString::<MAX_DESCRIPTION_LENGTH, 1>::from_sql(bytes)?;
Ok(Self(val))
}
}
impl<DB> ToSql<sql_types::Text, DB> for Description
where
DB: Backend,
LengthString<MAX_DESCRIPTION_LENGTH, 1>: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> Queryable<sql_types::Text, DB> for StatementDescriptor
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for StatementDescriptor
where
DB: Backend,
LengthString<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = LengthString::<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>::from_sql(bytes)?;
Ok(Self(val))
}
}
impl<DB> ToSql<sql_types::Text, DB> for StatementDescriptor
where
DB: Backend,
LengthString<MAX_STATEMENT_DESCRIPTOR_LENGTH, 1>: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
/// Domain type for unified code
#[derive(
Debug, Clone, PartialEq, Eq, Queryable, serde::Deserialize, serde::Serialize, AsExpression,
)]
#[diesel(sql_type = sql_types::Text)]
pub struct UnifiedCode(pub String);
impl TryFrom<String> for UnifiedCode {
type Error = error_stack::Report<ValidationError>;
fn try_from(src: String) -> Result<Self, Self::Error> {
if src.len() > 255 {
Err(report!(ValidationError::InvalidValue {
message: "unified_code's length should not exceed 255 characters".to_string()
}))
} else {
Ok(Self(src))
}
}
}
impl<DB> Queryable<sql_types::Text, DB> for UnifiedCode
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for UnifiedCode
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(bytes)?;
Ok(Self::try_from(val)?)
}
}
impl<DB> ToSql<sql_types::Text, DB> for UnifiedCode
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
/// Domain type for unified messages
#[derive(
Debug, Clone, PartialEq, Eq, Queryable, serde::Deserialize, serde::Serialize, AsExpression,
)]
#[diesel(sql_type = sql_types::Text)]
pub struct UnifiedMessage(pub String);
impl TryFrom<String> for UnifiedMessage {
type Error = error_stack::Report<ValidationError>;
fn try_from(src: String) -> Result<Self, Self::Error> {
if src.len() > 1024 {
Err(report!(ValidationError::InvalidValue {
message: "unified_message's length should not exceed 1024 characters".to_string()
}))
} else {
Ok(Self(src))
}
}
}
impl<DB> Queryable<sql_types::Text, DB> for UnifiedMessage
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for UnifiedMessage
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(bytes)?;
Ok(Self::try_from(val)?)
}
}
impl<DB> ToSql<sql_types::Text, DB> for UnifiedMessage
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
#[cfg(feature = "v2")]
/// Browser information to be used for 3DS 2.0
// If any of the field is PII, then we can make them as secret
#[derive(
ToSchema,
Debug,
Clone,
serde::Deserialize,
serde::Serialize,
Eq,
PartialEq,
diesel::AsExpression,
)]
#[diesel(sql_type = Jsonb)]
pub struct BrowserInformation {
/// Color depth supported by the browser
pub color_depth: Option<u8>,
/// Whether java is enabled in the browser
pub java_enabled: Option<bool>,
/// Whether javascript is enabled in the browser
pub java_script_enabled: Option<bool>,
/// Language supported
pub language: Option<String>,
/// The screen height in pixels
pub screen_height: Option<u32>,
/// The screen width in pixels
pub screen_width: Option<u32>,
/// Time zone of the client
pub time_zone: Option<i32>,
/// Ip address of the client
#[schema(value_type = Option<String>)]
pub ip_address: Option<std::net::IpAddr>,
/// List of headers that are accepted
#[schema(
example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8"
)]
pub accept_header: Option<String>,
/// User-agent of the browser
pub user_agent: Option<String>,
/// The os type of the client device
pub os_type: Option<String>,
/// The os version of the client device
pub os_version: Option<String>,
/// The device model of the client
pub device_model: Option<String>,
/// Accept-language of the browser
pub accept_language: Option<String>,
/// Identifier of the source that initiated the request.
pub referer: Option<String>,
}
#[cfg(feature = "v2")]
crate::impl_to_sql_from_sql_json!(BrowserInformation);
/// Domain type for connector_transaction_id
/// Maximum length for connector's transaction_id can be 128 characters in HS DB.
/// In case connector's use an identifier whose length exceeds 128 characters,
/// the hash value of such identifiers will be stored as connector_transaction_id.
/// The actual connector's identifier will be stored in a separate column -
/// processor_transaction_data or something with a similar name.
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub enum ConnectorTransactionId {
/// Actual transaction identifier
TxnId(String),
/// Hashed value of the transaction identifier
HashedData(String),
}
impl ConnectorTransactionId {
/// Implementation for retrieving the inner identifier
pub fn get_id(&self) -> &String {
match self {
Self::TxnId(id) | Self::HashedData(id) => id,
}
}
/// Implementation for forming ConnectorTransactionId and an optional string to be used for connector_transaction_id and processor_transaction_data
pub fn form_id_and_data(src: String) -> (Self, Option<String>) {
let txn_id = Self::from(src.clone());
match txn_id {
Self::TxnId(_) => (txn_id, None),
Self::HashedData(_) => (txn_id, Some(src)),
}
}
/// Implementation for extracting hashed data
pub fn extract_hashed_data(&self) -> Option<String> {
match self {
Self::TxnId(_) => None,
Self::HashedData(src) => Some(src.clone()),
}
}
/// Implementation for retrieving
pub fn get_txn_id<'a>(
&'a self,
txn_data: Option<&'a String>,
) -> Result<&'a String, error_stack::Report<ValidationError>> {
match (self, txn_data) {
(Self::TxnId(id), _) => Ok(id),
(Self::HashedData(_), Some(id)) => Ok(id),
(Self::HashedData(id), None) => Err(report!(ValidationError::InvalidValue {
message: "processor_transaction_data is empty for HashedData variant".to_string(),
})
.attach_printable(format!(
"processor_transaction_data is empty for connector_transaction_id {id}",
))),
}
}
}
impl From<String> for ConnectorTransactionId {
fn from(src: String) -> Self {
// ID already hashed
if src.starts_with("hs_hash_") {
Self::HashedData(src)
// Hash connector's transaction ID
} else if src.len() > 128 {
let mut hasher = blake3::Hasher::new();
let mut output = [0u8; consts::CONNECTOR_TRANSACTION_ID_HASH_BYTES];
hasher.update(src.as_bytes());
hasher.finalize_xof().fill(&mut output);
let hash = hex::encode(output);
Self::HashedData(format!("hs_hash_{hash}"))
// Default
} else {
Self::TxnId(src)
}
}
}
impl<DB> Queryable<sql_types::Text, DB> for ConnectorTransactionId
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for ConnectorTransactionId
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(bytes)?;
Ok(Self::from(val))
}
}
impl<DB> ToSql<sql_types::Text, DB> for ConnectorTransactionId
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
match self {
Self::HashedData(id) | Self::TxnId(id) => id.to_sql(out),
}
}
}
/// Trait for fetching actual or hashed transaction IDs
pub trait ConnectorTransactionIdTrait {
/// Returns an optional connector transaction ID
fn get_optional_connector_transaction_id(&self) -> Option<&String> {
None
}
/// Returns a connector transaction ID
fn get_connector_transaction_id(&self) -> &String {
self.get_optional_connector_transaction_id()
.unwrap_or_else(|| {
static EMPTY_STRING: String = String::new();
&EMPTY_STRING
})
}
/// Returns an optional connector refund ID
fn get_optional_connector_refund_id(&self) -> Option<&String> {
self.get_optional_connector_transaction_id()
}
}
/// Domain type for PublishableKey
#[derive(Debug, Clone, PartialEq, Eq, serde::Deserialize, serde::Serialize, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub struct PublishableKey(LengthString<PUBLISHABLE_KEY_LENGTH, PUBLISHABLE_KEY_LENGTH>);
impl PublishableKey {
/// Create a new PublishableKey Domain type without any length check from a static str
pub fn generate(env_prefix: &'static str) -> Self {
let publishable_key_string = format!("pk_{env_prefix}_{}", uuid::Uuid::now_v7().simple());
Self(LengthString::new_unchecked(publishable_key_string))
}
/// Get the string representation of the PublishableKey
pub fn get_string_repr(&self) -> &str {
&self.0 .0
}
}
impl<DB> Queryable<sql_types::Text, DB> for PublishableKey
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for PublishableKey
where
DB: Backend,
LengthString<PUBLISHABLE_KEY_LENGTH, PUBLISHABLE_KEY_LENGTH>: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = LengthString::<PUBLISHABLE_KEY_LENGTH, PUBLISHABLE_KEY_LENGTH>::from_sql(bytes)?;
Ok(Self(val))
}
}
impl<DB> ToSql<sql_types::Text, DB> for PublishableKey
where
DB: Backend,
LengthString<PUBLISHABLE_KEY_LENGTH, PUBLISHABLE_KEY_LENGTH>: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl_enum_str!(
tag_delimiter = ":",
/// CreatedBy conveys the information about the creator (identifier) as well as the origin or
/// trigger (Api, Jwt) of the record.
#[derive(Eq, PartialEq, Debug, Clone)]
pub enum CreatedBy {
/// Api variant
Api {
/// merchant id of creator.
merchant_id: String,
},
/// Jwt variant
Jwt {
/// user id of creator.
user_id: String,
},
}
);
#[allow(missing_docs)]
pub trait TenantConfig: Send + Sync {
fn get_tenant_id(&self) -> &id_type::TenantId;
fn get_schema(&self) -> &str;
fn get_accounts_schema(&self) -> &str;
fn get_redis_key_prefix(&self) -> &str;
fn get_clickhouse_database(&self) -> &str;
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/types.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 3,
"num_structs": 19,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_187077588499932904
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/encryption.rs
// Contains: 1 structs, 0 enums
use diesel::{
backend::Backend,
deserialize::{self, FromSql, Queryable},
expression::AsExpression,
serialize::ToSql,
sql_types,
};
use masking::Secret;
use crate::{crypto::Encryptable, pii::EncryptionStrategy};
impl<DB> FromSql<sql_types::Binary, DB> for Encryption
where
DB: Backend,
Secret<Vec<u8>, EncryptionStrategy>: FromSql<sql_types::Binary, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
<Secret<Vec<u8>, EncryptionStrategy>>::from_sql(bytes).map(Self::new)
}
}
impl<DB> ToSql<sql_types::Binary, DB> for Encryption
where
DB: Backend,
Secret<Vec<u8>, EncryptionStrategy>: ToSql<sql_types::Binary, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.get_inner().to_sql(out)
}
}
impl<DB> Queryable<sql_types::Binary, DB> for Encryption
where
DB: Backend,
Secret<Vec<u8>, EncryptionStrategy>: FromSql<sql_types::Binary, DB>,
{
type Row = Secret<Vec<u8>, EncryptionStrategy>;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(Self { inner: row })
}
}
#[derive(Debug, AsExpression, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
#[diesel(sql_type = sql_types::Binary)]
#[repr(transparent)]
pub struct Encryption {
inner: Secret<Vec<u8>, EncryptionStrategy>,
}
impl<T: Clone> From<Encryptable<T>> for Encryption {
fn from(value: Encryptable<T>) -> Self {
Self::new(value.into_encrypted())
}
}
impl Encryption {
pub fn new(item: Secret<Vec<u8>, EncryptionStrategy>) -> Self {
Self { inner: item }
}
#[inline]
pub fn into_inner(self) -> Secret<Vec<u8>, EncryptionStrategy> {
self.inner
}
#[inline]
pub fn get_inner(&self) -> &Secret<Vec<u8>, EncryptionStrategy> {
&self.inner
}
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/encryption.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_752039877199717807
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/lib.rs
// Contains: 4 structs, 1 enums
#![warn(missing_docs, missing_debug_implementations)]
#![doc = include_str!(concat!(env!("CARGO_MANIFEST_DIR" ), "/", "README.md"))]
use masking::{PeekInterface, Secret};
pub mod access_token;
pub mod consts;
pub mod crypto;
pub mod custom_serde;
#[allow(missing_docs)] // Todo: add docs
pub mod encryption;
pub mod errors;
#[allow(missing_docs)] // Todo: add docs
pub mod events;
pub mod ext_traits;
pub mod fp_utils;
/// Used for hashing
pub mod hashing;
pub mod id_type;
#[cfg(feature = "keymanager")]
pub mod keymanager;
pub mod link_utils;
pub mod macros;
#[cfg(feature = "metrics")]
pub mod metrics;
pub mod new_type;
pub mod payout_method_utils;
pub mod pii;
#[allow(missing_docs)] // Todo: add docs
pub mod request;
#[cfg(feature = "signals")]
pub mod signals;
pub mod transformers;
pub mod types;
/// Unified Connector Service (UCS) interface definitions.
///
/// This module defines types and traits for interacting with the Unified Connector Service.
/// It includes reference ID types for payments and refunds, and a trait for extracting
/// UCS reference information from requests.
pub mod ucs_types;
pub mod validation;
pub use base64_serializer::Base64Serializer;
/// Date-time utilities.
pub mod date_time {
#[cfg(feature = "async_ext")]
use std::time::Instant;
use std::{marker::PhantomData, num::NonZeroU8};
use masking::{Deserialize, Serialize};
use time::{
format_description::{
well_known::iso8601::{Config, EncodedConfig, Iso8601, TimePrecision},
BorrowedFormatItem,
},
OffsetDateTime, PrimitiveDateTime,
};
/// Enum to represent date formats
#[derive(Debug)]
pub enum DateFormat {
/// Format the date in 20191105081132 format
YYYYMMDDHHmmss,
/// Format the date in 20191105 format
YYYYMMDD,
/// Format the date in 201911050811 format
YYYYMMDDHHmm,
/// Format the date in 05112019081132 format
DDMMYYYYHHmmss,
}
/// Create a new [`PrimitiveDateTime`] with the current date and time in UTC.
pub fn now() -> PrimitiveDateTime {
let utc_date_time = OffsetDateTime::now_utc();
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
}
/// Convert from OffsetDateTime to PrimitiveDateTime
pub fn convert_to_pdt(offset_time: OffsetDateTime) -> PrimitiveDateTime {
PrimitiveDateTime::new(offset_time.date(), offset_time.time())
}
/// Return the UNIX timestamp of the current date and time in UTC
pub fn now_unix_timestamp() -> i64 {
OffsetDateTime::now_utc().unix_timestamp()
}
/// Calculate execution time for a async block in milliseconds
#[cfg(feature = "async_ext")]
pub async fn time_it<T, Fut: futures::Future<Output = T>, F: FnOnce() -> Fut>(
block: F,
) -> (T, f64) {
let start = Instant::now();
let result = block().await;
(result, start.elapsed().as_secs_f64() * 1000f64)
}
/// Return the given date and time in UTC with the given format Eg: format: YYYYMMDDHHmmss Eg: 20191105081132
pub fn format_date(
date: PrimitiveDateTime,
format: DateFormat,
) -> Result<String, time::error::Format> {
let format = <&[BorrowedFormatItem<'_>]>::from(format);
date.format(&format)
}
/// Return the current date and time in UTC with the format [year]-[month]-[day]T[hour]:[minute]:[second].mmmZ Eg: 2023-02-15T13:33:18.898Z
pub fn date_as_yyyymmddthhmmssmmmz() -> Result<String, time::error::Format> {
const ISO_CONFIG: EncodedConfig = Config::DEFAULT
.set_time_precision(TimePrecision::Second {
decimal_digits: NonZeroU8::new(3),
})
.encode();
now().assume_utc().format(&Iso8601::<ISO_CONFIG>)
}
/// Return the current date and time in UTC formatted as "ddd, DD MMM YYYY HH:mm:ss GMT".
pub fn now_rfc7231_http_date() -> Result<String, time::error::Format> {
let now_utc = OffsetDateTime::now_utc();
// Desired format: ddd, DD MMM YYYY HH:mm:ss GMT
// Example: Fri, 23 May 2025 06:19:35 GMT
let format = time::macros::format_description!(
"[weekday repr:short], [day padding:zero] [month repr:short] [year repr:full] [hour padding:zero repr:24]:[minute padding:zero]:[second padding:zero] GMT"
);
now_utc.format(&format)
}
impl From<DateFormat> for &[BorrowedFormatItem<'_>] {
fn from(format: DateFormat) -> Self {
match format {
DateFormat::YYYYMMDDHHmmss => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero][hour padding:zero repr:24][minute padding:zero][second padding:zero]"),
DateFormat::YYYYMMDD => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero]"),
DateFormat::YYYYMMDDHHmm => time::macros::format_description!("[year repr:full][month padding:zero repr:numerical][day padding:zero][hour padding:zero repr:24][minute padding:zero]"),
DateFormat::DDMMYYYYHHmmss => time::macros::format_description!("[day padding:zero][month padding:zero repr:numerical][year repr:full][hour padding:zero repr:24][minute padding:zero][second padding:zero]"),
}
}
}
/// Format the date in 05112019 format
#[derive(Debug, Clone)]
pub struct DDMMYYYY;
/// Format the date in 20191105 format
#[derive(Debug, Clone)]
pub struct YYYYMMDD;
/// Format the date in 20191105081132 format
#[derive(Debug, Clone)]
pub struct YYYYMMDDHHmmss;
/// To serialize the date in Dateformats like YYYYMMDDHHmmss, YYYYMMDD, DDMMYYYY
#[derive(Debug, Deserialize, Clone)]
pub struct DateTime<T: TimeStrategy> {
inner: PhantomData<T>,
value: PrimitiveDateTime,
}
impl<T: TimeStrategy> From<PrimitiveDateTime> for DateTime<T> {
fn from(value: PrimitiveDateTime) -> Self {
Self {
inner: PhantomData,
value,
}
}
}
/// Time strategy for the Date, Eg: YYYYMMDDHHmmss, YYYYMMDD, DDMMYYYY
pub trait TimeStrategy {
/// Stringify the date as per the Time strategy
fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result;
}
impl<T: TimeStrategy> Serialize for DateTime<T> {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
serializer.collect_str(self)
}
}
impl<T: TimeStrategy> std::fmt::Display for DateTime<T> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
T::fmt(&self.value, f)
}
}
impl TimeStrategy for DDMMYYYY {
fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let year = input.year();
#[allow(clippy::as_conversions)]
let month = input.month() as u8;
let day = input.day();
let output = format!("{day:02}{month:02}{year}");
f.write_str(&output)
}
}
impl TimeStrategy for YYYYMMDD {
fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let year = input.year();
#[allow(clippy::as_conversions)]
let month: u8 = input.month() as u8;
let day = input.day();
let output = format!("{year}{month:02}{day:02}");
f.write_str(&output)
}
}
impl TimeStrategy for YYYYMMDDHHmmss {
fn fmt(input: &PrimitiveDateTime, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let year = input.year();
#[allow(clippy::as_conversions)]
let month = input.month() as u8;
let day = input.day();
let hour = input.hour();
let minute = input.minute();
let second = input.second();
let output = format!("{year}{month:02}{day:02}{hour:02}{minute:02}{second:02}");
f.write_str(&output)
}
}
}
/// Generate a nanoid with the given prefix and length
#[inline]
pub fn generate_id(length: usize, prefix: &str) -> String {
format!("{}_{}", prefix, nanoid::nanoid!(length, &consts::ALPHABETS))
}
/// Generate a ReferenceId with the default length with the given prefix
fn generate_ref_id_with_default_length<const MAX_LENGTH: u8, const MIN_LENGTH: u8>(
prefix: &str,
) -> id_type::LengthId<MAX_LENGTH, MIN_LENGTH> {
id_type::LengthId::<MAX_LENGTH, MIN_LENGTH>::new(prefix)
}
/// Generate a customer id with default length, with prefix as `cus`
pub fn generate_customer_id_of_default_length() -> id_type::CustomerId {
use id_type::GenerateId;
id_type::CustomerId::generate()
}
/// Generate a organization id with default length, with prefix as `org`
pub fn generate_organization_id_of_default_length() -> id_type::OrganizationId {
use id_type::GenerateId;
id_type::OrganizationId::generate()
}
/// Generate a profile id with default length, with prefix as `pro`
pub fn generate_profile_id_of_default_length() -> id_type::ProfileId {
use id_type::GenerateId;
id_type::ProfileId::generate()
}
/// Generate a routing id with default length, with prefix as `routing`
pub fn generate_routing_id_of_default_length() -> id_type::RoutingId {
use id_type::GenerateId;
id_type::RoutingId::generate()
}
/// Generate a merchant_connector_account id with default length, with prefix as `mca`
pub fn generate_merchant_connector_account_id_of_default_length(
) -> id_type::MerchantConnectorAccountId {
use id_type::GenerateId;
id_type::MerchantConnectorAccountId::generate()
}
/// Generate a profile_acquirer id with default length, with prefix as `mer_acq`
pub fn generate_profile_acquirer_id_of_default_length() -> id_type::ProfileAcquirerId {
use id_type::GenerateId;
id_type::ProfileAcquirerId::generate()
}
/// Generate a nanoid with the given prefix and a default length
#[inline]
pub fn generate_id_with_default_len(prefix: &str) -> String {
let len: usize = consts::ID_LENGTH;
format!("{}_{}", prefix, nanoid::nanoid!(len, &consts::ALPHABETS))
}
/// Generate a time-ordered (time-sortable) unique identifier using the current time
#[inline]
pub fn generate_time_ordered_id(prefix: &str) -> String {
format!("{prefix}_{}", uuid::Uuid::now_v7().as_simple())
}
/// Generate a time-ordered (time-sortable) unique identifier using the current time without prefix
#[inline]
pub fn generate_time_ordered_id_without_prefix() -> String {
uuid::Uuid::now_v7().as_simple().to_string()
}
/// Generate a nanoid with the specified length
#[inline]
pub fn generate_id_with_len(length: usize) -> String {
nanoid::nanoid!(length, &consts::ALPHABETS)
}
#[allow(missing_docs)]
pub trait DbConnectionParams {
fn get_username(&self) -> &str;
fn get_password(&self) -> Secret<String>;
fn get_host(&self) -> &str;
fn get_port(&self) -> u16;
fn get_dbname(&self) -> &str;
fn get_database_url(&self, schema: &str) -> String {
format!(
"postgres://{}:{}@{}:{}/{}?application_name={}&options=-c%20search_path%3D{}",
self.get_username(),
self.get_password().peek(),
self.get_host(),
self.get_port(),
self.get_dbname(),
schema,
schema,
)
}
}
// Can't add doc comments for macro invocations, neither does the macro allow it.
#[allow(missing_docs)]
mod base64_serializer {
use base64_serde::base64_serde_type;
base64_serde_type!(pub Base64Serializer, crate::consts::BASE64_ENGINE);
}
#[cfg(test)]
mod nanoid_tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::{
consts::{
MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH, MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH,
},
id_type::AlphaNumericId,
};
#[test]
fn test_generate_id_with_alphanumeric_id() {
let alphanumeric_id = AlphaNumericId::from(generate_id(10, "def").into());
assert!(alphanumeric_id.is_ok())
}
#[test]
fn test_generate_merchant_ref_id_with_default_length() {
let ref_id = id_type::LengthId::<
MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH,
MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH,
>::from(generate_id_with_default_len("def").into());
assert!(ref_id.is_ok())
}
}
/// Module for tokenization-related functionality
///
/// This module provides types and functions for handling tokenized payment data,
/// including response structures and token generation utilities.
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
pub mod tokenization;
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/lib.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 4,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_-7622348567784450268
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/new_type.rs
// Contains: 8 structs, 0 enums
//! Contains new types with restrictions
use masking::{ExposeInterface, PeekInterface, Secret};
use crate::{
consts::MAX_ALLOWED_MERCHANT_NAME_LENGTH,
pii::{Email, UpiVpaMaskingStrategy},
transformers::ForeignFrom,
};
#[nutype::nutype(
derive(Clone, Serialize, Deserialize, Debug),
validate(len_char_min = 1, len_char_max = MAX_ALLOWED_MERCHANT_NAME_LENGTH)
)]
pub struct MerchantName(String);
impl masking::SerializableSecret for MerchantName {}
/// Function for masking alphanumeric characters in a string.
///
/// # Arguments
/// `val`
/// - holds reference to the string to be masked.
/// `unmasked_char_count`
/// - minimum character count to remain unmasked for identification
/// - this number is for keeping the characters unmasked from
/// both beginning (if feasible) and ending of the string.
/// `min_masked_char_count`
/// - this ensures the minimum number of characters to be masked
///
/// # Behaviour
/// - Returns the original string if its length is less than or equal to `unmasked_char_count`.
/// - If the string length allows, keeps `unmasked_char_count` characters unmasked at both start and end.
/// - Otherwise, keeps `unmasked_char_count` characters unmasked only at the end.
/// - Only alphanumeric characters are masked; other characters remain unchanged.
///
/// # Examples
/// Sort Code
/// (12-34-56, 2, 2) -> 12-**-56
/// Routing number
/// (026009593, 3, 3) -> 026***593
/// CNPJ
/// (12345678901, 4, 4) -> *******8901
/// CNPJ
/// (12345678901, 4, 3) -> 1234***8901
/// Pix key
/// (123e-a452-1243-1244-000, 4, 4) -> 123e-****-****-****-000
/// IBAN
/// (AL35202111090000000001234567, 5, 5) -> AL352******************34567
fn apply_mask(val: &str, unmasked_char_count: usize, min_masked_char_count: usize) -> String {
let len = val.len();
if len <= unmasked_char_count {
return val.to_string();
}
let mask_start_index =
// For showing only last `unmasked_char_count` characters
if len < (unmasked_char_count * 2 + min_masked_char_count) {
0
// For showing first and last `unmasked_char_count` characters
} else {
unmasked_char_count
};
let mask_end_index = len - unmasked_char_count - 1;
let range = mask_start_index..=mask_end_index;
val.chars()
.enumerate()
.fold(String::new(), |mut acc, (index, ch)| {
if ch.is_alphanumeric() && range.contains(&index) {
acc.push('*');
} else {
acc.push(ch);
}
acc
})
}
/// Masked sort code
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedSortCode(Secret<String>);
impl From<String> for MaskedSortCode {
fn from(src: String) -> Self {
let masked_value = apply_mask(src.as_ref(), 2, 2);
Self(Secret::from(masked_value))
}
}
impl From<Secret<String>> for MaskedSortCode {
fn from(secret: Secret<String>) -> Self {
Self::from(secret.expose())
}
}
/// Masked Routing number
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedRoutingNumber(Secret<String>);
impl From<String> for MaskedRoutingNumber {
fn from(src: String) -> Self {
let masked_value = apply_mask(src.as_ref(), 3, 3);
Self(Secret::from(masked_value))
}
}
impl From<Secret<String>> for MaskedRoutingNumber {
fn from(secret: Secret<String>) -> Self {
Self::from(secret.expose())
}
}
/// Masked bank account
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedBankAccount(Secret<String>);
impl From<String> for MaskedBankAccount {
fn from(src: String) -> Self {
let masked_value = apply_mask(src.as_ref(), 4, 4);
Self(Secret::from(masked_value))
}
}
impl From<Secret<String>> for MaskedBankAccount {
fn from(secret: Secret<String>) -> Self {
Self::from(secret.expose())
}
}
/// Masked IBAN
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedIban(Secret<String>);
impl From<String> for MaskedIban {
fn from(src: String) -> Self {
let masked_value = apply_mask(src.as_ref(), 5, 5);
Self(Secret::from(masked_value))
}
}
impl From<Secret<String>> for MaskedIban {
fn from(secret: Secret<String>) -> Self {
Self::from(secret.expose())
}
}
/// Masked IBAN
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedBic(Secret<String>);
impl From<String> for MaskedBic {
fn from(src: String) -> Self {
let masked_value = apply_mask(src.as_ref(), 3, 2);
Self(Secret::from(masked_value))
}
}
impl From<Secret<String>> for MaskedBic {
fn from(secret: Secret<String>) -> Self {
Self::from(secret.expose())
}
}
/// Masked UPI ID
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedUpiVpaId(Secret<String>);
impl From<String> for MaskedUpiVpaId {
fn from(src: String) -> Self {
let unmasked_char_count = 2;
let masked_value = if let Some((user_identifier, bank_or_psp)) = src.split_once('@') {
let masked_user_identifier = user_identifier
.to_string()
.chars()
.take(unmasked_char_count)
.collect::<String>()
+ &"*".repeat(user_identifier.len() - unmasked_char_count);
format!("{masked_user_identifier}@{bank_or_psp}")
} else {
let masked_value = apply_mask(src.as_ref(), unmasked_char_count, 8);
masked_value
};
Self(Secret::from(masked_value))
}
}
impl From<Secret<String, UpiVpaMaskingStrategy>> for MaskedUpiVpaId {
fn from(secret: Secret<String, UpiVpaMaskingStrategy>) -> Self {
Self::from(secret.expose())
}
}
/// Masked Email
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedEmail(Secret<String>);
impl From<String> for MaskedEmail {
fn from(src: String) -> Self {
let unmasked_char_count = 2;
let masked_value = if let Some((user_identifier, domain)) = src.split_once('@') {
let masked_user_identifier = user_identifier
.to_string()
.chars()
.take(unmasked_char_count)
.collect::<String>()
+ &"*".repeat(user_identifier.len() - unmasked_char_count);
format!("{masked_user_identifier}@{domain}")
} else {
let masked_value = apply_mask(src.as_ref(), unmasked_char_count, 8);
masked_value
};
Self(Secret::from(masked_value))
}
}
impl From<Secret<String>> for MaskedEmail {
fn from(secret: Secret<String>) -> Self {
Self::from(secret.expose())
}
}
impl ForeignFrom<Email> for MaskedEmail {
fn foreign_from(email: Email) -> Self {
let email_value: String = email.expose().peek().to_owned();
Self::from(email_value)
}
}
/// Masked Phone Number
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct MaskedPhoneNumber(Secret<String>);
impl From<String> for MaskedPhoneNumber {
fn from(src: String) -> Self {
let unmasked_char_count = 2;
let masked_value = if unmasked_char_count <= src.len() {
let len = src.len();
// mask every character except the last 2
"*".repeat(len - unmasked_char_count).to_string()
+ src
.get(len.saturating_sub(unmasked_char_count)..)
.unwrap_or("")
} else {
src
};
Self(Secret::from(masked_value))
}
}
impl From<Secret<String>> for MaskedPhoneNumber {
fn from(secret: Secret<String>) -> Self {
Self::from(secret.expose())
}
}
#[cfg(test)]
mod apply_mask_fn_test {
use masking::PeekInterface;
use crate::new_type::{
apply_mask, MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode,
MaskedUpiVpaId,
};
#[test]
fn test_masked_types() {
let sort_code = MaskedSortCode::from("110011".to_string());
let routing_number = MaskedRoutingNumber::from("056008849".to_string());
let bank_account = MaskedBankAccount::from("12345678901234".to_string());
let iban = MaskedIban::from("NL02ABNA0123456789".to_string());
let upi_vpa = MaskedUpiVpaId::from("someusername@okhdfcbank".to_string());
// Standard masked data tests
assert_eq!(sort_code.0.peek().to_owned(), "11**11".to_string());
assert_eq!(routing_number.0.peek().to_owned(), "056***849".to_string());
assert_eq!(
bank_account.0.peek().to_owned(),
"1234******1234".to_string()
);
assert_eq!(iban.0.peek().to_owned(), "NL02A********56789".to_string());
assert_eq!(
upi_vpa.0.peek().to_owned(),
"so**********@okhdfcbank".to_string()
);
}
#[test]
fn test_apply_mask_fn() {
let value = "12345678901".to_string();
// Generic masked tests
assert_eq!(apply_mask(&value, 2, 2), "12*******01".to_string());
assert_eq!(apply_mask(&value, 3, 2), "123*****901".to_string());
assert_eq!(apply_mask(&value, 3, 3), "123*****901".to_string());
assert_eq!(apply_mask(&value, 4, 3), "1234***8901".to_string());
assert_eq!(apply_mask(&value, 4, 4), "*******8901".to_string());
assert_eq!(apply_mask(&value, 5, 4), "******78901".to_string());
assert_eq!(apply_mask(&value, 5, 5), "******78901".to_string());
assert_eq!(apply_mask(&value, 6, 5), "*****678901".to_string());
assert_eq!(apply_mask(&value, 6, 6), "*****678901".to_string());
assert_eq!(apply_mask(&value, 7, 6), "****5678901".to_string());
assert_eq!(apply_mask(&value, 7, 7), "****5678901".to_string());
assert_eq!(apply_mask(&value, 8, 7), "***45678901".to_string());
assert_eq!(apply_mask(&value, 8, 8), "***45678901".to_string());
}
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/new_type.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 8,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_-2975949343650304862
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/signals.rs
// Contains: 1 structs, 0 enums
//! Provide Interface for worker services to handle signals
#[cfg(not(target_os = "windows"))]
use futures::StreamExt;
#[cfg(not(target_os = "windows"))]
use router_env::logger;
use tokio::sync::mpsc;
/// This functions is meant to run in parallel to the application.
/// It will send a signal to the receiver when a SIGTERM or SIGINT is received
#[cfg(not(target_os = "windows"))]
pub async fn signal_handler(mut sig: signal_hook_tokio::Signals, sender: mpsc::Sender<()>) {
if let Some(signal) = sig.next().await {
logger::info!(
"Received signal: {:?}",
signal_hook::low_level::signal_name(signal)
);
match signal {
signal_hook::consts::SIGTERM | signal_hook::consts::SIGINT => match sender.try_send(())
{
Ok(_) => {
logger::info!("Request for force shutdown received")
}
Err(_) => {
logger::error!(
"The receiver is closed, a termination call might already be sent"
)
}
},
_ => {}
}
}
}
/// This functions is meant to run in parallel to the application.
/// It will send a signal to the receiver when a SIGTERM or SIGINT is received
#[cfg(target_os = "windows")]
pub async fn signal_handler(_sig: DummySignal, _sender: mpsc::Sender<()>) {}
/// This function is used to generate a list of signals that the signal_handler should listen for
#[cfg(not(target_os = "windows"))]
pub fn get_allowed_signals() -> Result<signal_hook_tokio::SignalsInfo, std::io::Error> {
signal_hook_tokio::Signals::new([signal_hook::consts::SIGTERM, signal_hook::consts::SIGINT])
}
/// This function is used to generate a list of signals that the signal_handler should listen for
#[cfg(target_os = "windows")]
pub fn get_allowed_signals() -> Result<DummySignal, std::io::Error> {
Ok(DummySignal)
}
/// Dummy Signal Handler for windows
#[cfg(target_os = "windows")]
#[derive(Debug, Clone)]
pub struct DummySignal;
#[cfg(target_os = "windows")]
impl DummySignal {
/// Dummy handler for signals in windows (empty)
pub fn handle(&self) -> Self {
self.clone()
}
/// Hollow implementation, for windows compatibility
pub fn close(self) {}
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/signals.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_505334816538760746
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/validation.rs
// Contains: 1 structs, 0 enums
//! Custom validations for some shared types.
#![deny(clippy::invalid_regex)]
use std::{collections::HashSet, sync::LazyLock};
use error_stack::report;
use globset::Glob;
use regex::Regex;
#[cfg(feature = "logs")]
use router_env::logger;
use crate::errors::{CustomResult, ValidationError};
/// Validates a given phone number using the [phonenumber] crate
///
/// It returns a [ValidationError::InvalidValue] in case it could not parse the phone number
pub fn validate_phone_number(phone_number: &str) -> Result<(), ValidationError> {
let _ = phonenumber::parse(None, phone_number).map_err(|e| ValidationError::InvalidValue {
message: format!("Could not parse phone number: {phone_number}, because: {e:?}"),
})?;
Ok(())
}
/// Performs a simple validation against a provided email address.
pub fn validate_email(email: &str) -> CustomResult<(), ValidationError> {
#[deny(clippy::invalid_regex)]
static EMAIL_REGEX: LazyLock<Option<Regex>> = LazyLock::new(|| {
#[allow(unknown_lints)]
#[allow(clippy::manual_ok_err)]
match Regex::new(
r"^(?i)[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$",
) {
Ok(regex) => Some(regex),
Err(_error) => {
#[cfg(feature = "logs")]
logger::error!(?_error);
None
}
}
});
let email_regex = match EMAIL_REGEX.as_ref() {
Some(regex) => Ok(regex),
None => Err(report!(ValidationError::InvalidValue {
message: "Invalid regex expression".into()
})),
}?;
const EMAIL_MAX_LENGTH: usize = 319;
if email.is_empty() || email.chars().count() > EMAIL_MAX_LENGTH {
return Err(report!(ValidationError::InvalidValue {
message: "Email address is either empty or exceeds maximum allowed length".into()
}));
}
if !email_regex.is_match(email) {
return Err(report!(ValidationError::InvalidValue {
message: "Invalid email address format".into()
}));
}
Ok(())
}
/// Checks whether a given domain matches against a list of valid domain glob patterns
pub fn validate_domain_against_allowed_domains(
domain: &str,
allowed_domains: HashSet<String>,
) -> bool {
allowed_domains.iter().any(|allowed_domain| {
Glob::new(allowed_domain)
.map(|glob| glob.compile_matcher().is_match(domain))
.map_err(|err| {
let err_msg = format!(
"Invalid glob pattern for configured allowed_domain [{allowed_domain:?}]! - {err:?}",
);
#[cfg(feature = "logs")]
logger::error!(err_msg);
err_msg
})
.unwrap_or(false)
})
}
/// checks whether the input string contains potential XSS or SQL injection attack vectors
pub fn contains_potential_xss_or_sqli(input: &str) -> bool {
let decoded = urlencoding::decode(input).unwrap_or_else(|_| input.into());
// Check for suspicious percent-encoded patterns
static PERCENT_ENCODED: LazyLock<Option<Regex>> = LazyLock::new(|| {
Regex::new(r"%[0-9A-Fa-f]{2}")
.map_err(|_err| {
#[cfg(feature = "logs")]
logger::error!(?_err);
})
.ok()
});
if decoded.contains('%') {
match PERCENT_ENCODED.as_ref() {
Some(regex) => {
if regex.is_match(&decoded) {
return true;
}
}
None => return true,
}
}
if ammonia::is_html(&decoded) {
return true;
}
static XSS: LazyLock<Option<Regex>> = LazyLock::new(|| {
Regex::new(
r"(?is)\bon[a-z]+\s*=|\bjavascript\s*:|\bdata\s*:\s*text/html|\b(alert|prompt|confirm|eval)\s*\(",
)
.map_err(|_err| {
#[cfg(feature = "logs")]
logger::error!(?_err);
})
.ok()
});
static SQLI: LazyLock<Option<Regex>> = LazyLock::new(|| {
Regex::new(
r"(?is)(?:')\s*or\s*'?\d+'?=?\d*|union\s+select|insert\s+into|drop\s+table|information_schema|sleep\s*\(|--|;",
)
.map_err(|_err| {
#[cfg(feature = "logs")]
logger::error!(?_err);
})
.ok()
});
match XSS.as_ref() {
Some(regex) => {
if regex.is_match(&decoded) {
return true;
}
}
None => return true,
}
match SQLI.as_ref() {
Some(regex) => {
if regex.is_match(&decoded) {
return true;
}
}
None => return true,
}
false
}
#[cfg(test)]
mod tests {
use fake::{faker::internet::en::SafeEmail, Fake};
use proptest::{
prop_assert,
strategy::{Just, NewTree, Strategy},
test_runner::TestRunner,
};
use test_case::test_case;
use super::*;
#[derive(Debug)]
struct ValidEmail;
impl Strategy for ValidEmail {
type Tree = Just<String>;
type Value = String;
fn new_tree(&self, _runner: &mut TestRunner) -> NewTree<Self> {
Ok(Just(SafeEmail().fake()))
}
}
#[test]
fn test_validate_email() {
let result = validate_email("[email protected]");
assert!(result.is_ok());
let result = validate_email("[email protected]");
assert!(result.is_ok());
let result = validate_email("");
assert!(result.is_err());
}
#[test_case("+40745323456" ; "Romanian valid phone number")]
#[test_case("+34912345678" ; "Spanish valid phone number")]
#[test_case("+41 79 123 45 67" ; "Swiss valid phone number")]
#[test_case("+66 81 234 5678" ; "Thailand valid phone number")]
fn test_validate_phone_number(phone_number: &str) {
assert!(validate_phone_number(phone_number).is_ok());
}
#[test_case("9123456789" ; "Romanian invalid phone number")]
fn test_invalid_phone_number(phone_number: &str) {
let res = validate_phone_number(phone_number);
assert!(res.is_err());
}
proptest::proptest! {
/// Example of unit test
#[test]
fn proptest_valid_fake_email(email in ValidEmail) {
prop_assert!(validate_email(&email).is_ok());
}
/// Example of unit test
#[test]
fn proptest_invalid_data_email(email in "\\PC*") {
prop_assert!(validate_email(&email).is_err());
}
#[test]
fn proptest_invalid_email(email in "[.+]@(.+)") {
prop_assert!(validate_email(&email).is_err());
}
}
#[test]
fn detects_basic_script_tags() {
assert!(contains_potential_xss_or_sqli(
"<script>alert('xss')</script>"
));
}
#[test]
fn detects_event_handlers() {
assert!(contains_potential_xss_or_sqli(
"onload=alert('xss') onclick=alert('xss') onmouseover=alert('xss')",
));
}
#[test]
fn detects_data_url_payload() {
assert!(contains_potential_xss_or_sqli(
"data:text/html,<script>alert('xss')</script>",
));
}
#[test]
fn detects_iframe_javascript_src() {
assert!(contains_potential_xss_or_sqli(
"<iframe src=javascript:alert('xss')></iframe>",
));
}
#[test]
fn detects_svg_with_script() {
assert!(contains_potential_xss_or_sqli(
"<svg><script>alert('xss')</script></svg>",
));
}
#[test]
fn detects_object_with_js() {
assert!(contains_potential_xss_or_sqli(
"<object data=javascript:alert('xss')></object>",
));
}
#[test]
fn detects_mixed_case_tags() {
assert!(contains_potential_xss_or_sqli(
"<ScRiPt>alert('xss')</ScRiPt>"
));
}
#[test]
fn detects_embedded_script_in_text() {
assert!(contains_potential_xss_or_sqli(
"Test<script>alert('xss')</script>Company",
));
}
#[test]
fn detects_math_with_script() {
assert!(contains_potential_xss_or_sqli(
"<math><script>alert('xss')</script></math>",
));
}
#[test]
fn detects_basic_sql_tautology() {
assert!(contains_potential_xss_or_sqli("' OR '1'='1"));
}
#[test]
fn detects_time_based_sqli() {
assert!(contains_potential_xss_or_sqli("' OR SLEEP(5) --"));
}
#[test]
fn detects_percent_encoded_sqli() {
// %27 OR %271%27=%271 is a typical encoded variant
assert!(contains_potential_xss_or_sqli("%27%20OR%20%271%27%3D%271"));
}
#[test]
fn detects_benign_html_as_suspicious() {
assert!(contains_potential_xss_or_sqli("<b>Hello</b>"));
}
#[test]
fn allows_legitimate_plain_text() {
assert!(!contains_potential_xss_or_sqli("My Test Company Ltd."));
}
#[test]
fn allows_normal_url() {
assert!(!contains_potential_xss_or_sqli("https://example.com"));
}
#[test]
fn allows_percent_char_without_encoding() {
assert!(!contains_potential_xss_or_sqli("Get 50% off today"));
}
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/validation.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_-6115316558658704543
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/pii.rs
// Contains: 2 structs, 6 enums
//! Personal Identifiable Information protection.
use std::{convert::AsRef, fmt, ops, str::FromStr};
use diesel::{
backend::Backend,
deserialize,
deserialize::FromSql,
prelude::*,
serialize::{Output, ToSql},
sql_types, AsExpression,
};
use error_stack::ResultExt;
use masking::{ExposeInterface, Secret, Strategy, WithType};
#[cfg(feature = "logs")]
use router_env::logger;
use serde::Deserialize;
use crate::{
crypto::Encryptable,
errors::{self, ValidationError},
validation::{validate_email, validate_phone_number},
};
/// A string constant representing a redacted or masked value.
pub const REDACTED: &str = "Redacted";
/// Type alias for serde_json value which has Secret Information
pub type SecretSerdeValue = Secret<serde_json::Value>;
/// Strategy for masking a PhoneNumber
#[derive(Debug)]
pub enum PhoneNumberStrategy {}
/// Phone Number
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(try_from = "String")]
pub struct PhoneNumber(Secret<String, PhoneNumberStrategy>);
impl<T> Strategy<T> for PhoneNumberStrategy
where
T: AsRef<str> + fmt::Debug,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
if let Some(val_str) = val_str.get(val_str.len() - 4..) {
// masks everything but the last 4 digits
write!(f, "{}{}", "*".repeat(val_str.len() - 4), val_str)
} else {
#[cfg(feature = "logs")]
logger::error!("Invalid phone number: {val_str}");
WithType::fmt(val, f)
}
}
}
impl FromStr for PhoneNumber {
type Err = error_stack::Report<ValidationError>;
fn from_str(phone_number: &str) -> Result<Self, Self::Err> {
validate_phone_number(phone_number)?;
let secret = Secret::<String, PhoneNumberStrategy>::new(phone_number.to_string());
Ok(Self(secret))
}
}
impl TryFrom<String> for PhoneNumber {
type Error = error_stack::Report<errors::ParsingError>;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::from_str(&value).change_context(errors::ParsingError::PhoneNumberParsingError)
}
}
impl ops::Deref for PhoneNumber {
type Target = Secret<String, PhoneNumberStrategy>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ops::DerefMut for PhoneNumber {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<DB> Queryable<sql_types::Text, DB> for PhoneNumber
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for PhoneNumber
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(bytes)?;
Ok(Self::from_str(val.as_str())?)
}
}
impl<DB> ToSql<sql_types::Text, DB> for PhoneNumber
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
/*
/// Phone number
#[derive(Debug)]
pub struct PhoneNumber;
impl<T> Strategy<T> for PhoneNumber
where
T: AsRef<str>,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
if val_str.len() < 10 || val_str.len() > 12 {
return WithType::fmt(val, f);
}
write!(
f,
"{}{}{}",
&val_str[..2],
"*".repeat(val_str.len() - 5),
&val_str[(val_str.len() - 3)..]
)
}
}
*/
/// Strategy for Encryption
#[derive(Debug)]
pub enum EncryptionStrategy {}
impl<T> Strategy<T> for EncryptionStrategy
where
T: AsRef<[u8]>,
{
fn fmt(value: &T, fmt: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
fmt,
"*** Encrypted data of length {} bytes ***",
value.as_ref().len()
)
}
}
/// Client secret
#[derive(Debug)]
pub enum ClientSecret {}
impl<T> Strategy<T> for ClientSecret
where
T: AsRef<str>,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
let client_secret_segments: Vec<&str> = val_str.split('_').collect();
if client_secret_segments.len() != 4
|| !client_secret_segments.contains(&"pay")
|| !client_secret_segments.contains(&"secret")
{
return WithType::fmt(val, f);
}
if let Some((client_secret_segments_0, client_secret_segments_1)) = client_secret_segments
.first()
.zip(client_secret_segments.get(1))
{
write!(
f,
"{}_{}_{}",
client_secret_segments_0,
client_secret_segments_1,
"*".repeat(
val_str.len()
- (client_secret_segments_0.len() + client_secret_segments_1.len() + 2)
)
)
} else {
#[cfg(feature = "logs")]
logger::error!("Invalid client secret: {val_str}");
WithType::fmt(val, f)
}
}
}
/// Strategy for masking Email
#[derive(Debug, Copy, Clone, Deserialize)]
pub enum EmailStrategy {}
impl<T> Strategy<T> for EmailStrategy
where
T: AsRef<str> + fmt::Debug,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
match val_str.split_once('@') {
Some((a, b)) => write!(f, "{}@{}", "*".repeat(a.len()), b),
None => WithType::fmt(val, f),
}
}
}
/// Email address
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq, Default, AsExpression,
)]
#[diesel(sql_type = sql_types::Text)]
#[serde(try_from = "String")]
pub struct Email(Secret<String, EmailStrategy>);
impl From<Encryptable<Secret<String, EmailStrategy>>> for Email {
fn from(item: Encryptable<Secret<String, EmailStrategy>>) -> Self {
Self(item.into_inner())
}
}
impl ExposeInterface<Secret<String, EmailStrategy>> for Email {
fn expose(self) -> Secret<String, EmailStrategy> {
self.0
}
}
impl TryFrom<String> for Email {
type Error = error_stack::Report<errors::ParsingError>;
fn try_from(value: String) -> Result<Self, Self::Error> {
Self::from_str(&value).change_context(errors::ParsingError::EmailParsingError)
}
}
impl ops::Deref for Email {
type Target = Secret<String, EmailStrategy>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ops::DerefMut for Email {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl<DB> Queryable<sql_types::Text, DB> for Email
where
DB: Backend,
Self: FromSql<sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> FromSql<sql_types::Text, DB> for Email
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let val = String::from_sql(bytes)?;
Ok(Self::from_str(val.as_str())?)
}
}
impl<DB> ToSql<sql_types::Text, DB> for Email
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl FromStr for Email {
type Err = error_stack::Report<ValidationError>;
fn from_str(email: &str) -> Result<Self, Self::Err> {
if email.eq(REDACTED) {
return Ok(Self(Secret::new(email.to_string())));
}
match validate_email(email) {
Ok(_) => {
let secret = Secret::<String, EmailStrategy>::new(email.to_string());
Ok(Self(secret))
}
Err(_) => Err(ValidationError::InvalidValue {
message: "Invalid email address format".into(),
}
.into()),
}
}
}
/// IP address
#[derive(Debug)]
pub enum IpAddress {}
impl<T> Strategy<T> for IpAddress
where
T: AsRef<str>,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let val_str: &str = val.as_ref();
let segments: Vec<&str> = val_str.split('.').collect();
if segments.len() != 4 {
return WithType::fmt(val, f);
}
for seg in segments.iter() {
if seg.is_empty() || seg.len() > 3 {
return WithType::fmt(val, f);
}
}
if let Some(segments) = segments.first() {
write!(f, "{segments}.**.**.**")
} else {
#[cfg(feature = "logs")]
logger::error!("Invalid IP address: {val_str}");
WithType::fmt(val, f)
}
}
}
/// Strategy for masking UPI VPA's
#[derive(Debug)]
pub enum UpiVpaMaskingStrategy {}
impl<T> Strategy<T> for UpiVpaMaskingStrategy
where
T: AsRef<str> + fmt::Debug,
{
fn fmt(val: &T, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let vpa_str: &str = val.as_ref();
if let Some((user_identifier, bank_or_psp)) = vpa_str.split_once('@') {
let masked_user_identifier = "*".repeat(user_identifier.len());
write!(f, "{masked_user_identifier}@{bank_or_psp}")
} else {
WithType::fmt(val, f)
}
}
}
#[cfg(test)]
mod pii_masking_strategy_tests {
use std::str::FromStr;
use masking::{ExposeInterface, Secret};
use super::{ClientSecret, Email, IpAddress, UpiVpaMaskingStrategy};
use crate::pii::{EmailStrategy, REDACTED};
/*
#[test]
fn test_valid_phone_number_masking() {
let secret: Secret<String, PhoneNumber> = Secret::new("9123456789".to_string());
assert_eq!("99*****299", format!("{}", secret));
}
#[test]
fn test_invalid_phone_number_masking() {
let secret: Secret<String, PhoneNumber> = Secret::new("99229922".to_string());
assert_eq!("*** alloc::string::String ***", format!("{}", secret));
let secret: Secret<String, PhoneNumber> = Secret::new("9922992299229922".to_string());
assert_eq!("*** alloc::string::String ***", format!("{}", secret));
}
*/
#[test]
fn test_valid_email_masking() {
let secret: Secret<String, EmailStrategy> = Secret::new("[email protected]".to_string());
assert_eq!("*******@test.com", format!("{secret:?}"));
let secret: Secret<String, EmailStrategy> = Secret::new("[email protected]".to_string());
assert_eq!("********@gmail.com", format!("{secret:?}"));
}
#[test]
fn test_invalid_email_masking() {
let secret: Secret<String, EmailStrategy> = Secret::new("myemailgmail.com".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
let secret: Secret<String, EmailStrategy> = Secret::new("myemail$gmail.com".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
}
#[test]
fn test_valid_newtype_email() {
let email_check = Email::from_str("[email protected]");
assert!(email_check.is_ok());
}
#[test]
fn test_invalid_newtype_email() {
let email_check = Email::from_str("example@abc@com");
assert!(email_check.is_err());
}
#[test]
fn test_redacted_email() {
let email_result = Email::from_str(REDACTED);
assert!(email_result.is_ok());
if let Ok(email) = email_result {
let secret_value = email.0.expose();
assert_eq!(secret_value.as_str(), REDACTED);
}
}
#[test]
fn test_valid_ip_addr_masking() {
let secret: Secret<String, IpAddress> = Secret::new("123.23.1.78".to_string());
assert_eq!("123.**.**.**", format!("{secret:?}"));
}
#[test]
fn test_invalid_ip_addr_masking() {
let secret: Secret<String, IpAddress> = Secret::new("123.4.56".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
let secret: Secret<String, IpAddress> = Secret::new("123.4567.12.4".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
let secret: Secret<String, IpAddress> = Secret::new("123..4.56".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
}
#[test]
fn test_valid_client_secret_masking() {
let secret: Secret<String, ClientSecret> =
Secret::new("pay_uszFB2QGe9MmLY65ojhT_secret_tLjTz9tAQxUVEFqfmOIP".to_string());
assert_eq!(
"pay_uszFB2QGe9MmLY65ojhT_***************************",
format!("{secret:?}")
);
}
#[test]
fn test_invalid_client_secret_masking() {
let secret: Secret<String, IpAddress> =
Secret::new("pay_uszFB2QGe9MmLY65ojhT_secret".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
}
#[test]
fn test_valid_phone_number_default_masking() {
let secret: Secret<String> = Secret::new("+40712345678".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
}
#[test]
fn test_valid_upi_vpa_masking() {
let secret: Secret<String, UpiVpaMaskingStrategy> = Secret::new("my_name@upi".to_string());
assert_eq!("*******@upi", format!("{secret:?}"));
}
#[test]
fn test_invalid_upi_vpa_masking() {
let secret: Secret<String, UpiVpaMaskingStrategy> = Secret::new("my_name_upi".to_string());
assert_eq!("*** alloc::string::String ***", format!("{secret:?}"));
}
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/pii.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 6,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_4847919099944751473
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/errors.rs
// Contains: 1 structs, 7 enums
//! Errors and error specific types for universal use
use serde::Serialize;
use crate::types::MinorUnit;
/// Custom Result
/// A custom datatype that wraps the error variant <E> into a report, allowing
/// error_stack::Report<E> specific extendability
///
/// Effectively, equivalent to `Result<T, error_stack::Report<E>>`
pub type CustomResult<T, E> = error_stack::Result<T, E>;
/// Parsing Errors
#[allow(missing_docs)] // Only to prevent warnings about struct fields not being documented
#[derive(Debug, thiserror::Error)]
pub enum ParsingError {
///Failed to parse enum
#[error("Failed to parse enum: {0}")]
EnumParseFailure(&'static str),
///Failed to parse struct
#[error("Failed to parse struct: {0}")]
StructParseFailure(&'static str),
/// Failed to encode data to given format
#[error("Failed to serialize to {0} format")]
EncodeError(&'static str),
/// Failed to parse data
#[error("Unknown error while parsing")]
UnknownError,
/// Failed to parse datetime
#[error("Failed to parse datetime")]
DateTimeParsingError,
/// Failed to parse email
#[error("Failed to parse email")]
EmailParsingError,
/// Failed to parse phone number
#[error("Failed to parse phone number")]
PhoneNumberParsingError,
/// Failed to parse Float value for converting to decimal points
#[error("Failed to parse Float value for converting to decimal points")]
FloatToDecimalConversionFailure,
/// Failed to parse Decimal value for i64 value conversion
#[error("Failed to parse Decimal value for i64 value conversion")]
DecimalToI64ConversionFailure,
/// Failed to parse string value for f64 value conversion
#[error("Failed to parse string value for f64 value conversion")]
StringToFloatConversionFailure,
/// Failed to parse i64 value for f64 value conversion
#[error("Failed to parse i64 value for f64 value conversion")]
I64ToDecimalConversionFailure,
/// Failed to parse i64 value for String value conversion
#[error("Failed to parse i64 value for String value conversion")]
I64ToStringConversionFailure,
/// Failed to parse String value to Decimal value conversion because `error`
#[error("Failed to parse String value to Decimal value conversion because {error}")]
StringToDecimalConversionFailure { error: String },
/// Failed to convert the given integer because of integer overflow error
#[error("Integer Overflow error")]
IntegerOverflow,
/// Failed to parse url
#[error("Failed to parse url")]
UrlParsingError,
}
/// Validation errors.
#[allow(missing_docs)] // Only to prevent warnings about struct fields not being documented
#[derive(Debug, thiserror::Error, Clone, PartialEq)]
pub enum ValidationError {
/// The provided input is missing a required field.
#[error("Missing required field: {field_name}")]
MissingRequiredField { field_name: String },
/// An incorrect value was provided for the field specified by `field_name`.
#[error("Incorrect value provided for field: {field_name}")]
IncorrectValueProvided { field_name: &'static str },
/// An invalid input was provided.
#[error("{message}")]
InvalidValue { message: String },
}
/// Integrity check errors.
#[derive(Debug, Clone, PartialEq, Default, Serialize)]
pub struct IntegrityCheckError {
/// Field names for which integrity check failed!
pub field_names: String,
/// Connector transaction reference id
pub connector_transaction_id: Option<String>,
}
/// Cryptographic algorithm errors
#[derive(Debug, thiserror::Error)]
pub enum CryptoError {
/// The cryptographic algorithm was unable to encode the message
#[error("Failed to encode given message")]
EncodingFailed,
/// The cryptographic algorithm was unable to decode the message
#[error("Failed to decode given message")]
DecodingFailed,
/// The cryptographic algorithm was unable to sign the message
#[error("Failed to sign message")]
MessageSigningFailed,
/// The cryptographic algorithm was unable to verify the given signature
#[error("Failed to verify signature")]
SignatureVerificationFailed,
/// The provided key length is invalid for the cryptographic algorithm
#[error("Invalid key length")]
InvalidKeyLength,
/// The provided IV length is invalid for the cryptographic algorithm
#[error("Invalid IV length")]
InvalidIvLength,
/// The provided authentication tag length is invalid for the cryptographic algorithm
#[error("Invalid authentication tag length")]
InvalidTagLength,
}
/// Errors for Qr code handling
#[derive(Debug, thiserror::Error)]
pub enum QrCodeError {
/// Failed to encode data into Qr code
#[error("Failed to create Qr code")]
FailedToCreateQrCode,
/// Failed to parse hex color
#[error("Invalid hex color code supplied")]
InvalidHexColor,
}
/// Api Models construction error
#[derive(Debug, Clone, thiserror::Error, PartialEq)]
pub enum PercentageError {
/// Percentage Value provided was invalid
#[error("Invalid Percentage value")]
InvalidPercentageValue,
/// Error occurred while calculating percentage
#[error("Failed apply percentage of {percentage} on {amount}")]
UnableToApplyPercentage {
/// percentage value
percentage: f32,
/// amount value
amount: MinorUnit,
},
}
/// Allows [error_stack::Report] to change between error contexts
/// using the dependent [ErrorSwitch] trait to define relations & mappings between traits
pub trait ReportSwitchExt<T, U> {
/// Switch to the intended report by calling switch
/// requires error switch to be already implemented on the error type
fn switch(self) -> Result<T, error_stack::Report<U>>;
}
impl<T, U, V> ReportSwitchExt<T, U> for Result<T, error_stack::Report<V>>
where
V: ErrorSwitch<U> + error_stack::Context,
U: error_stack::Context,
{
#[track_caller]
fn switch(self) -> Result<T, error_stack::Report<U>> {
match self {
Ok(i) => Ok(i),
Err(er) => {
let new_c = er.current_context().switch();
Err(er.change_context(new_c))
}
}
}
}
#[allow(missing_docs)]
#[derive(Debug, thiserror::Error)]
pub enum KeyManagerClientError {
#[error("Failed to construct header from the given value")]
FailedtoConstructHeader,
#[error("Failed to send request to Keymanager")]
RequestNotSent(String),
#[error("URL encoding of request failed")]
UrlEncodingFailed,
#[error("Failed to build the reqwest client ")]
ClientConstructionFailed,
#[error("Failed to send the request to Keymanager")]
RequestSendFailed,
#[error("Internal Server Error Received {0:?}")]
InternalServerError(bytes::Bytes),
#[error("Bad request received {0:?}")]
BadRequest(bytes::Bytes),
#[error("Unexpected Error occurred while calling the KeyManager")]
Unexpected(bytes::Bytes),
#[error("Response Decoding failed")]
ResponseDecodingFailed,
}
#[allow(missing_docs)]
#[derive(Debug, thiserror::Error)]
pub enum KeyManagerError {
#[error("Failed to add key to the KeyManager")]
KeyAddFailed,
#[error("Failed to transfer the key to the KeyManager")]
KeyTransferFailed,
#[error("Failed to Encrypt the data in the KeyManager")]
EncryptionFailed,
#[error("Failed to Decrypt the data in the KeyManager")]
DecryptionFailed,
}
/// Allow [error_stack::Report] to convert between error types
/// This auto-implements [ReportSwitchExt] for the corresponding errors
pub trait ErrorSwitch<T> {
/// Get the next error type that the source error can be escalated into
/// This does not consume the source error since we need to keep it in context
fn switch(&self) -> T;
}
/// Allow [error_stack::Report] to convert between error types
/// This serves as an alternative to [ErrorSwitch]
pub trait ErrorSwitchFrom<T> {
/// Convert to an error type that the source can be escalated into
/// This does not consume the source error since we need to keep it in context
fn switch_from(error: &T) -> Self;
}
impl<T, S> ErrorSwitch<T> for S
where
T: ErrorSwitchFrom<Self>,
{
fn switch(&self) -> T {
T::switch_from(self)
}
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/errors.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 7,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_-2854996414682991080
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/id_type.rs
// Contains: 1 structs, 1 enums
//! Common ID types
//! The id type can be used to create specific id types with custom behaviour
mod api_key;
mod authentication;
mod client_secret;
mod customer;
#[cfg(feature = "v2")]
mod global_id;
mod invoice;
mod merchant;
mod merchant_connector_account;
mod organization;
mod payment;
mod payout;
mod profile;
mod profile_acquirer;
mod refunds;
mod relay;
mod routing;
mod subscription;
mod tenant;
mod webhook_endpoint;
use std::{borrow::Cow, fmt::Debug};
use diesel::{
backend::Backend,
deserialize::FromSql,
expression::AsExpression,
serialize::{Output, ToSql},
sql_types,
};
pub use payout::PayoutId;
use serde::{Deserialize, Serialize};
use thiserror::Error;
#[cfg(feature = "v2")]
pub use self::global_id::{
customer::GlobalCustomerId,
payment::{GlobalAttemptId, GlobalPaymentId},
payment_methods::{GlobalPaymentMethodId, GlobalPaymentMethodSessionId},
refunds::GlobalRefundId,
token::GlobalTokenId,
CellId,
};
pub use self::{
api_key::ApiKeyId,
authentication::AuthenticationId,
client_secret::ClientSecretId,
customer::CustomerId,
invoice::InvoiceId,
merchant::MerchantId,
merchant_connector_account::MerchantConnectorAccountId,
organization::OrganizationId,
payment::{PaymentId, PaymentReferenceId},
profile::ProfileId,
profile_acquirer::ProfileAcquirerId,
refunds::RefundReferenceId,
relay::RelayId,
routing::RoutingId,
subscription::SubscriptionId,
tenant::TenantId,
webhook_endpoint::WebhookEndpointId,
};
use crate::{fp_utils::when, generate_id_with_default_len};
#[inline]
fn is_valid_id_character(input_char: char) -> bool {
input_char.is_ascii_alphanumeric() || matches!(input_char, '_' | '-')
}
/// This functions checks for the input string to contain valid characters
/// Returns Some(char) if there are any invalid characters, else None
fn get_invalid_input_character(input_string: Cow<'static, str>) -> Option<char> {
input_string
.trim()
.chars()
.find(|&char| !is_valid_id_character(char))
}
#[derive(Debug, PartialEq, Hash, Serialize, Clone, Eq)]
/// A type for alphanumeric ids
pub(crate) struct AlphaNumericId(String);
#[derive(Debug, Deserialize, Hash, Serialize, Error, Eq, PartialEq)]
#[error("value `{0}` contains invalid character `{1}`")]
/// The error type for alphanumeric id
pub(crate) struct AlphaNumericIdError(String, char);
impl<'de> Deserialize<'de> for AlphaNumericId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let deserialized_string = String::deserialize(deserializer)?;
Self::from(deserialized_string.into()).map_err(serde::de::Error::custom)
}
}
impl AlphaNumericId {
/// Creates a new alphanumeric id from string by applying validation checks
pub fn from(input_string: Cow<'static, str>) -> Result<Self, AlphaNumericIdError> {
let invalid_character = get_invalid_input_character(input_string.clone());
if let Some(invalid_character) = invalid_character {
Err(AlphaNumericIdError(
input_string.to_string(),
invalid_character,
))?
}
Ok(Self(input_string.to_string()))
}
/// Create a new alphanumeric id without any validations
pub(crate) fn new_unchecked(input_string: String) -> Self {
Self(input_string)
}
/// Generate a new alphanumeric id of default length
pub(crate) fn new(prefix: &str) -> Self {
Self(generate_id_with_default_len(prefix))
}
}
/// A common type of id that can be used for reference ids with length constraint
#[derive(Debug, Clone, Serialize, Hash, PartialEq, Eq, AsExpression)]
#[diesel(sql_type = sql_types::Text)]
pub(crate) struct LengthId<const MAX_LENGTH: u8, const MIN_LENGTH: u8>(AlphaNumericId);
/// Error generated from violation of constraints for MerchantReferenceId
#[derive(Debug, Error, PartialEq, Eq)]
pub(crate) enum LengthIdError {
#[error("the maximum allowed length for this field is {0}")]
/// Maximum length of string violated
MaxLengthViolated(u8),
#[error("the minimum required length for this field is {0}")]
/// Minimum length of string violated
MinLengthViolated(u8),
#[error("{0}")]
/// Input contains invalid characters
AlphanumericIdError(AlphaNumericIdError),
}
impl From<AlphaNumericIdError> for LengthIdError {
fn from(alphanumeric_id_error: AlphaNumericIdError) -> Self {
Self::AlphanumericIdError(alphanumeric_id_error)
}
}
impl<const MAX_LENGTH: u8, const MIN_LENGTH: u8> LengthId<MAX_LENGTH, MIN_LENGTH> {
/// Generates new [MerchantReferenceId] from the given input string
pub fn from(input_string: Cow<'static, str>) -> Result<Self, LengthIdError> {
let trimmed_input_string = input_string.trim().to_string();
let length_of_input_string = u8::try_from(trimmed_input_string.len())
.map_err(|_| LengthIdError::MaxLengthViolated(MAX_LENGTH))?;
when(length_of_input_string > MAX_LENGTH, || {
Err(LengthIdError::MaxLengthViolated(MAX_LENGTH))
})?;
when(length_of_input_string < MIN_LENGTH, || {
Err(LengthIdError::MinLengthViolated(MIN_LENGTH))
})?;
let alphanumeric_id = match AlphaNumericId::from(trimmed_input_string.into()) {
Ok(valid_alphanumeric_id) => valid_alphanumeric_id,
Err(error) => Err(LengthIdError::AlphanumericIdError(error))?,
};
Ok(Self(alphanumeric_id))
}
/// Generate a new MerchantRefId of default length with the given prefix
pub fn new(prefix: &str) -> Self {
Self(AlphaNumericId::new(prefix))
}
/// Use this function only if you are sure that the length is within the range
pub(crate) fn new_unchecked(alphanumeric_id: AlphaNumericId) -> Self {
Self(alphanumeric_id)
}
#[cfg(feature = "v2")]
/// Create a new LengthId from aplhanumeric id
pub(crate) fn from_alphanumeric_id(
alphanumeric_id: AlphaNumericId,
) -> Result<Self, LengthIdError> {
let length_of_input_string = alphanumeric_id.0.len();
let length_of_input_string = u8::try_from(length_of_input_string)
.map_err(|_| LengthIdError::MaxLengthViolated(MAX_LENGTH))?;
when(length_of_input_string > MAX_LENGTH, || {
Err(LengthIdError::MaxLengthViolated(MAX_LENGTH))
})?;
when(length_of_input_string < MIN_LENGTH, || {
Err(LengthIdError::MinLengthViolated(MIN_LENGTH))
})?;
Ok(Self(alphanumeric_id))
}
}
impl<'de, const MAX_LENGTH: u8, const MIN_LENGTH: u8> Deserialize<'de>
for LengthId<MAX_LENGTH, MIN_LENGTH>
{
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let deserialized_string = String::deserialize(deserializer)?;
Self::from(deserialized_string.into()).map_err(serde::de::Error::custom)
}
}
impl<DB, const MAX_LENGTH: u8, const MIN_LENGTH: u8> ToSql<sql_types::Text, DB>
for LengthId<MAX_LENGTH, MIN_LENGTH>
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, DB>) -> diesel::serialize::Result {
self.0 .0.to_sql(out)
}
}
impl<DB, const MAX_LENGTH: u8, const MIN_LENGTH: u8> FromSql<sql_types::Text, DB>
for LengthId<MAX_LENGTH, MIN_LENGTH>
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
let string_val = String::from_sql(value)?;
Ok(Self(AlphaNumericId::new_unchecked(string_val)))
}
}
/// An interface to generate object identifiers.
pub trait GenerateId {
/// Generates a random object identifier.
fn generate() -> Self;
}
#[cfg(test)]
mod alphanumeric_id_tests {
#![allow(clippy::unwrap_used)]
use super::*;
const VALID_UNDERSCORE_ID_JSON: &str = r#""cus_abcdefghijklmnopqrstuv""#;
const EXPECTED_VALID_UNDERSCORE_ID: &str = "cus_abcdefghijklmnopqrstuv";
const VALID_HYPHEN_ID_JSON: &str = r#""cus-abcdefghijklmnopqrstuv""#;
const VALID_HYPHEN_ID_STRING: &str = "cus-abcdefghijklmnopqrstuv";
const INVALID_ID_WITH_SPACES: &str = r#""cus abcdefghijklmnopqrstuv""#;
const INVALID_ID_WITH_EMOJIS: &str = r#""cus_abc🦀""#;
#[test]
fn test_id_deserialize_underscore() {
let parsed_alphanumeric_id =
serde_json::from_str::<AlphaNumericId>(VALID_UNDERSCORE_ID_JSON);
let alphanumeric_id = AlphaNumericId::from(EXPECTED_VALID_UNDERSCORE_ID.into()).unwrap();
assert_eq!(parsed_alphanumeric_id.unwrap(), alphanumeric_id);
}
#[test]
fn test_id_deserialize_hyphen() {
let parsed_alphanumeric_id = serde_json::from_str::<AlphaNumericId>(VALID_HYPHEN_ID_JSON);
let alphanumeric_id = AlphaNumericId::from(VALID_HYPHEN_ID_STRING.into()).unwrap();
assert_eq!(parsed_alphanumeric_id.unwrap(), alphanumeric_id);
}
#[test]
fn test_id_deserialize_with_spaces() {
let parsed_alphanumeric_id = serde_json::from_str::<AlphaNumericId>(INVALID_ID_WITH_SPACES);
assert!(parsed_alphanumeric_id.is_err());
}
#[test]
fn test_id_deserialize_with_emojis() {
let parsed_alphanumeric_id = serde_json::from_str::<AlphaNumericId>(INVALID_ID_WITH_EMOJIS);
assert!(parsed_alphanumeric_id.is_err());
}
}
#[cfg(test)]
mod merchant_reference_id_tests {
use super::*;
const VALID_REF_ID_JSON: &str = r#""cus_abcdefghijklmnopqrstuv""#;
const MAX_LENGTH: u8 = 36;
const MIN_LENGTH: u8 = 6;
const INVALID_REF_ID_JSON: &str = r#""cus abcdefghijklmnopqrstuv""#;
const INVALID_REF_ID_LENGTH: &str = r#""cus_abcdefghijklmnopqrstuvwxyzabcdefghij""#;
#[test]
fn test_valid_reference_id() {
let parsed_merchant_reference_id =
serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(VALID_REF_ID_JSON);
dbg!(&parsed_merchant_reference_id);
assert!(parsed_merchant_reference_id.is_ok());
}
#[test]
fn test_invalid_ref_id() {
let parsed_merchant_reference_id =
serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(INVALID_REF_ID_JSON);
assert!(parsed_merchant_reference_id.is_err());
}
#[test]
fn test_invalid_ref_id_error_message() {
let parsed_merchant_reference_id =
serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(INVALID_REF_ID_JSON);
let expected_error_message =
r#"value `cus abcdefghijklmnopqrstuv` contains invalid character ` `"#.to_string();
let error_message = parsed_merchant_reference_id
.err()
.map(|error| error.to_string());
assert_eq!(error_message, Some(expected_error_message));
}
#[test]
fn test_invalid_ref_id_length() {
let parsed_merchant_reference_id =
serde_json::from_str::<LengthId<MAX_LENGTH, MIN_LENGTH>>(INVALID_REF_ID_LENGTH);
dbg!(&parsed_merchant_reference_id);
let expected_error_message =
format!("the maximum allowed length for this field is {MAX_LENGTH}");
assert!(parsed_merchant_reference_id
.is_err_and(|error_string| error_string.to_string().eq(&expected_error_message)));
}
#[test]
fn test_invalid_ref_id_length_error_type() {
let parsed_merchant_reference_id =
LengthId::<MAX_LENGTH, MIN_LENGTH>::from(INVALID_REF_ID_LENGTH.into());
dbg!(&parsed_merchant_reference_id);
assert!(
parsed_merchant_reference_id.is_err_and(|error_type| matches!(
error_type,
LengthIdError::MaxLengthViolated(MAX_LENGTH)
))
);
}
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/id_type.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_7737780994551179029
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/payout_method_utils.rs
// Contains: 9 structs, 4 enums
//! This module has common utilities for payout method data in HyperSwitch
use common_enums;
use diesel::{sql_types::Jsonb, AsExpression, FromSqlRow};
use masking::Secret;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::new_type::{
MaskedBankAccount, MaskedBic, MaskedEmail, MaskedIban, MaskedPhoneNumber, MaskedRoutingNumber,
MaskedSortCode,
};
/// Masked payout method details for storing in db
#[derive(
Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub enum AdditionalPayoutMethodData {
/// Additional data for card payout method
Card(Box<CardAdditionalData>),
/// Additional data for bank payout method
Bank(Box<BankAdditionalData>),
/// Additional data for wallet payout method
Wallet(Box<WalletAdditionalData>),
/// Additional data for Bank Redirect payout method
BankRedirect(Box<BankRedirectAdditionalData>),
}
crate::impl_to_sql_from_sql_json!(AdditionalPayoutMethodData);
/// Masked payout method details for card payout method
#[derive(
Eq, PartialEq, Clone, Debug, Serialize, Deserialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct CardAdditionalData {
/// Issuer of the card
pub card_issuer: Option<String>,
/// Card network of the card
#[schema(value_type = Option<CardNetwork>)]
pub card_network: Option<common_enums::CardNetwork>,
/// Card type, can be either `credit` or `debit`
pub card_type: Option<String>,
/// Card issuing country
pub card_issuing_country: Option<String>,
/// Code for Card issuing bank
pub bank_code: Option<String>,
/// Last 4 digits of the card number
pub last4: Option<String>,
/// The ISIN of the card
pub card_isin: Option<String>,
/// Extended bin of card, contains the first 8 digits of card number
pub card_extended_bin: Option<String>,
/// Card expiry month
#[schema(value_type = String, example = "01")]
pub card_exp_month: Option<Secret<String>>,
/// Card expiry year
#[schema(value_type = String, example = "2026")]
pub card_exp_year: Option<Secret<String>>,
/// Card holder name
#[schema(value_type = String, example = "John Doe")]
pub card_holder_name: Option<Secret<String>>,
}
/// Masked payout method details for bank payout method
#[derive(
Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(untagged)]
pub enum BankAdditionalData {
/// Additional data for ach bank transfer payout method
Ach(Box<AchBankTransferAdditionalData>),
/// Additional data for bacs bank transfer payout method
Bacs(Box<BacsBankTransferAdditionalData>),
/// Additional data for sepa bank transfer payout method
Sepa(Box<SepaBankTransferAdditionalData>),
/// Additional data for pix bank transfer payout method
Pix(Box<PixBankTransferAdditionalData>),
}
/// Masked payout method details for ach bank transfer payout method
#[derive(
Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct AchBankTransferAdditionalData {
/// Partially masked account number for ach bank debit payment
#[schema(value_type = String, example = "0001****3456")]
pub bank_account_number: MaskedBankAccount,
/// Partially masked routing number for ach bank debit payment
#[schema(value_type = String, example = "110***000")]
pub bank_routing_number: MaskedRoutingNumber,
/// Name of the bank
#[schema(value_type = Option<BankNames>, example = "Deutsche Bank")]
pub bank_name: Option<String>,
/// Bank country code
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub bank_country_code: Option<common_enums::CountryAlpha2>,
/// Bank city
#[schema(value_type = Option<String>, example = "California")]
pub bank_city: Option<String>,
}
/// Masked payout method details for bacs bank transfer payout method
#[derive(
Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct BacsBankTransferAdditionalData {
/// Partially masked sort code for Bacs payment method
#[schema(value_type = String, example = "108800")]
pub bank_sort_code: MaskedSortCode,
/// Bank account's owner name
#[schema(value_type = String, example = "0001****3456")]
pub bank_account_number: MaskedBankAccount,
/// Bank name
#[schema(value_type = Option<String>, example = "Deutsche Bank")]
pub bank_name: Option<String>,
/// Bank country code
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub bank_country_code: Option<common_enums::CountryAlpha2>,
/// Bank city
#[schema(value_type = Option<String>, example = "California")]
pub bank_city: Option<String>,
}
/// Masked payout method details for sepa bank transfer payout method
#[derive(
Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct SepaBankTransferAdditionalData {
/// Partially masked international bank account number (iban) for SEPA
#[schema(value_type = String, example = "DE8937******013000")]
pub iban: MaskedIban,
/// Bank name
#[schema(value_type = Option<String>, example = "Deutsche Bank")]
pub bank_name: Option<String>,
/// Bank country code
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub bank_country_code: Option<common_enums::CountryAlpha2>,
/// Bank city
#[schema(value_type = Option<String>, example = "California")]
pub bank_city: Option<String>,
/// [8 / 11 digits] Bank Identifier Code (bic) / Swift Code - used in many countries for identifying a bank and it's branches
#[schema(value_type = Option<String>, example = "HSBCGB2LXXX")]
pub bic: Option<MaskedBic>,
}
/// Masked payout method details for pix bank transfer payout method
#[derive(
Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct PixBankTransferAdditionalData {
/// Partially masked unique key for pix transfer
#[schema(value_type = String, example = "a1f4102e ****** 6fa48899c1d1")]
pub pix_key: MaskedBankAccount,
/// Partially masked CPF - CPF is a Brazilian tax identification number
#[schema(value_type = Option<String>, example = "**** 124689")]
pub tax_id: Option<MaskedBankAccount>,
/// Bank account number is an unique identifier assigned by a bank to a customer.
#[schema(value_type = String, example = "**** 23456")]
pub bank_account_number: MaskedBankAccount,
/// Bank name
#[schema(value_type = Option<String>, example = "Deutsche Bank")]
pub bank_name: Option<String>,
/// Bank branch
#[schema(value_type = Option<String>, example = "3707")]
pub bank_branch: Option<String>,
}
/// Masked payout method details for wallet payout method
#[derive(
Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(untagged)]
pub enum WalletAdditionalData {
/// Additional data for paypal wallet payout method
Paypal(Box<PaypalAdditionalData>),
/// Additional data for venmo wallet payout method
Venmo(Box<VenmoAdditionalData>),
/// Additional data for Apple pay decrypt wallet payout method
ApplePayDecrypt(Box<ApplePayDecryptAdditionalData>),
}
/// Masked payout method details for paypal wallet payout method
#[derive(
Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct PaypalAdditionalData {
/// Email linked with paypal account
#[schema(value_type = Option<String>, example = "[email protected]")]
pub email: Option<MaskedEmail>,
/// mobile number linked to paypal account
#[schema(value_type = Option<String>, example = "******* 3349")]
pub telephone_number: Option<MaskedPhoneNumber>,
/// id of the paypal account
#[schema(value_type = Option<String>, example = "G83K ***** HCQ2")]
pub paypal_id: Option<MaskedBankAccount>,
}
/// Masked payout method details for venmo wallet payout method
#[derive(
Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct VenmoAdditionalData {
/// mobile number linked to venmo account
#[schema(value_type = Option<String>, example = "******* 3349")]
pub telephone_number: Option<MaskedPhoneNumber>,
}
/// Masked payout method details for Apple pay decrypt wallet payout method
#[derive(
Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct ApplePayDecryptAdditionalData {
/// Card expiry month
#[schema(value_type = String, example = "01")]
pub card_exp_month: Secret<String>,
/// Card expiry year
#[schema(value_type = String, example = "2026")]
pub card_exp_year: Secret<String>,
/// Card holder name
#[schema(value_type = String, example = "John Doe")]
pub card_holder_name: Option<Secret<String>>,
}
/// Masked payout method details for wallet payout method
#[derive(
Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
#[serde(untagged)]
pub enum BankRedirectAdditionalData {
/// Additional data for interac bank redirect payout method
Interac(Box<InteracAdditionalData>),
}
/// Masked payout method details for interac bank redirect payout method
#[derive(
Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, FromSqlRow, AsExpression, ToSchema,
)]
#[diesel(sql_type = Jsonb)]
pub struct InteracAdditionalData {
/// Email linked with interac account
#[schema(value_type = Option<String>, example = "[email protected]")]
pub email: Option<MaskedEmail>,
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/payout_method_utils.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 4,
"num_structs": 9,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_-6151197792626982588
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/link_utils.rs
// Contains: 3 structs, 0 enums
//! This module has common utilities for links in HyperSwitch
use std::{collections::HashSet, primitive::i64};
use common_enums::{enums, UIWidgetFormLayout};
use diesel::{
backend::Backend,
deserialize,
deserialize::FromSql,
serialize::{Output, ToSql},
sql_types::Jsonb,
AsExpression, FromSqlRow,
};
use error_stack::{report, ResultExt};
use masking::Secret;
use regex::Regex;
#[cfg(feature = "logs")]
use router_env::logger;
use serde::Serialize;
use utoipa::ToSchema;
use crate::{consts, errors::ParsingError, id_type, types::MinorUnit};
#[derive(
Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq, FromSqlRow, AsExpression, ToSchema,
)]
#[serde(rename_all = "snake_case", tag = "type", content = "value")]
#[diesel(sql_type = Jsonb)]
/// Link status enum
pub enum GenericLinkStatus {
/// Status variants for payment method collect link
PaymentMethodCollect(PaymentMethodCollectStatus),
/// Status variants for payout link
PayoutLink(PayoutLinkStatus),
}
impl Default for GenericLinkStatus {
fn default() -> Self {
Self::PaymentMethodCollect(PaymentMethodCollectStatus::Initiated)
}
}
crate::impl_to_sql_from_sql_json!(GenericLinkStatus);
#[derive(
Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq, FromSqlRow, AsExpression, ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[diesel(sql_type = Jsonb)]
/// Status variants for payment method collect links
pub enum PaymentMethodCollectStatus {
/// Link was initialized
Initiated,
/// Link was expired or invalidated
Invalidated,
/// Payment method details were submitted
Submitted,
}
impl<DB: Backend> FromSql<Jsonb, DB> for PaymentMethodCollectStatus
where
serde_json::Value: FromSql<Jsonb, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let value = <serde_json::Value as FromSql<Jsonb, DB>>::from_sql(bytes)?;
let generic_status: GenericLinkStatus = serde_json::from_value(value)?;
match generic_status {
GenericLinkStatus::PaymentMethodCollect(status) => Ok(status),
GenericLinkStatus::PayoutLink(_) => Err(report!(ParsingError::EnumParseFailure(
"PaymentMethodCollectStatus"
)))
.attach_printable("Invalid status for PaymentMethodCollect")?,
}
}
}
impl ToSql<Jsonb, diesel::pg::Pg> for PaymentMethodCollectStatus
where
serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>,
{
// This wraps PaymentMethodCollectStatus with GenericLinkStatus
// Required for storing the status in required format in DB (GenericLinkStatus)
// This type is used in PaymentMethodCollectLink (a variant of GenericLink, used in the application for avoiding conversion of data and status)
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, diesel::pg::Pg>) -> diesel::serialize::Result {
let value = serde_json::to_value(GenericLinkStatus::PaymentMethodCollect(self.clone()))?;
// the function `reborrow` only works in case of `Pg` backend. But, in case of other backends
// please refer to the diesel migration blog:
// https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations
<serde_json::Value as ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow())
}
}
#[derive(
Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq, FromSqlRow, AsExpression, ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[diesel(sql_type = Jsonb)]
/// Status variants for payout links
pub enum PayoutLinkStatus {
/// Link was initialized
Initiated,
/// Link was expired or invalidated
Invalidated,
/// Payout details were submitted
Submitted,
}
impl<DB: Backend> FromSql<Jsonb, DB> for PayoutLinkStatus
where
serde_json::Value: FromSql<Jsonb, DB>,
{
fn from_sql(bytes: DB::RawValue<'_>) -> deserialize::Result<Self> {
let value = <serde_json::Value as FromSql<Jsonb, DB>>::from_sql(bytes)?;
let generic_status: GenericLinkStatus = serde_json::from_value(value)?;
match generic_status {
GenericLinkStatus::PayoutLink(status) => Ok(status),
GenericLinkStatus::PaymentMethodCollect(_) => {
Err(report!(ParsingError::EnumParseFailure("PayoutLinkStatus")))
.attach_printable("Invalid status for PayoutLink")?
}
}
}
}
impl ToSql<Jsonb, diesel::pg::Pg> for PayoutLinkStatus
where
serde_json::Value: ToSql<Jsonb, diesel::pg::Pg>,
{
// This wraps PayoutLinkStatus with GenericLinkStatus
// Required for storing the status in required format in DB (GenericLinkStatus)
// This type is used in PayoutLink (a variant of GenericLink, used in the application for avoiding conversion of data and status)
fn to_sql<'b>(&'b self, out: &mut Output<'b, '_, diesel::pg::Pg>) -> diesel::serialize::Result {
let value = serde_json::to_value(GenericLinkStatus::PayoutLink(self.clone()))?;
// the function `reborrow` only works in case of `Pg` backend. But, in case of other backends
// please refer to the diesel migration blog:
// https://github.com/Diesel-rs/Diesel/blob/master/guide_drafts/migration_guide.md#changed-tosql-implementations
<serde_json::Value as ToSql<Jsonb, diesel::pg::Pg>>::to_sql(&value, &mut out.reborrow())
}
}
#[derive(Serialize, serde::Deserialize, Debug, Clone, FromSqlRow, AsExpression, ToSchema)]
#[diesel(sql_type = Jsonb)]
/// Payout link object
pub struct PayoutLinkData {
/// Identifier for the payout link
pub payout_link_id: String,
/// Identifier for the customer
pub customer_id: id_type::CustomerId,
/// Identifier for the payouts resource
pub payout_id: id_type::PayoutId,
/// Link to render the payout link
pub link: url::Url,
/// Client secret generated for authenticating frontend APIs
pub client_secret: Secret<String>,
/// Expiry in seconds from the time it was created
pub session_expiry: u32,
#[serde(flatten)]
/// Payout link's UI configurations
pub ui_config: GenericLinkUiConfig,
/// List of enabled payment methods
pub enabled_payment_methods: Option<Vec<EnabledPaymentMethod>>,
/// Payout amount
pub amount: MinorUnit,
/// Payout currency
pub currency: enums::Currency,
/// A list of allowed domains (glob patterns) where this link can be embedded / opened from
pub allowed_domains: HashSet<String>,
/// Form layout of the payout link
pub form_layout: Option<UIWidgetFormLayout>,
/// `test_mode` can be used for testing payout links without any restrictions
pub test_mode: Option<bool>,
}
crate::impl_to_sql_from_sql_json!(PayoutLinkData);
/// Object for GenericLinkUiConfig
#[derive(Clone, Debug, serde::Deserialize, Serialize, ToSchema)]
pub struct GenericLinkUiConfig {
/// Merchant's display logo
#[schema(value_type = Option<String>, max_length = 255, example = "https://hyperswitch.io/favicon.ico")]
pub logo: Option<url::Url>,
/// Custom merchant name for the link
#[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch")]
pub merchant_name: Option<Secret<String>>,
/// Primary color to be used in the form represented in hex format
#[schema(value_type = Option<String>, max_length = 255, example = "#4285F4")]
pub theme: Option<String>,
}
/// Object for GenericLinkUiConfigFormData
#[derive(Clone, Debug, serde::Deserialize, Serialize, ToSchema)]
pub struct GenericLinkUiConfigFormData {
/// Merchant's display logo
#[schema(value_type = String, max_length = 255, example = "https://hyperswitch.io/favicon.ico")]
pub logo: url::Url,
/// Custom merchant name for the link
#[schema(value_type = String, max_length = 255, example = "Hyperswitch")]
pub merchant_name: Secret<String>,
/// Primary color to be used in the form represented in hex format
#[schema(value_type = String, max_length = 255, example = "#4285F4")]
pub theme: String,
}
/// Object for EnabledPaymentMethod
#[derive(Clone, Debug, Serialize, serde::Deserialize, ToSchema)]
pub struct EnabledPaymentMethod {
/// Payment method (banks, cards, wallets) enabled for the operation
#[schema(value_type = PaymentMethod)]
pub payment_method: enums::PaymentMethod,
/// An array of associated payment method types
#[schema(value_type = HashSet<PaymentMethodType>)]
pub payment_method_types: HashSet<enums::PaymentMethodType>,
}
/// Util function for validating a domain without any wildcard characters.
pub fn validate_strict_domain(domain: &str) -> bool {
Regex::new(consts::STRICT_DOMAIN_REGEX)
.map(|regex| regex.is_match(domain))
.map_err(|err| {
let err_msg = format!("Invalid strict domain regex: {err:?}");
#[cfg(feature = "logs")]
logger::error!(err_msg);
err_msg
})
.unwrap_or(false)
}
/// Util function for validating a domain with "*" wildcard characters.
pub fn validate_wildcard_domain(domain: &str) -> bool {
Regex::new(consts::WILDCARD_DOMAIN_REGEX)
.map(|regex| regex.is_match(domain))
.map_err(|err| {
let err_msg = format!("Invalid strict domain regex: {err:?}");
#[cfg(feature = "logs")]
logger::error!(err_msg);
err_msg
})
.unwrap_or(false)
}
#[cfg(test)]
mod domain_tests {
use regex::Regex;
use super::*;
#[test]
fn test_validate_strict_domain_regex() {
assert!(
Regex::new(consts::STRICT_DOMAIN_REGEX).is_ok(),
"Strict domain regex is invalid"
);
}
#[test]
fn test_validate_wildcard_domain_regex() {
assert!(
Regex::new(consts::WILDCARD_DOMAIN_REGEX).is_ok(),
"Wildcard domain regex is invalid"
);
}
#[test]
fn test_validate_strict_domain() {
let valid_domains = vec![
"example.com",
"example.subdomain.com",
"https://example.com:8080",
"http://example.com",
"example.com:8080",
"example.com:443",
"localhost:443",
"127.0.0.1:443",
];
for domain in valid_domains {
assert!(
validate_strict_domain(domain),
"Could not validate strict domain: {domain}",
);
}
let invalid_domains = vec![
"",
"invalid.domain.",
"not_a_domain",
"http://example.com/path?query=1#fragment",
"127.0.0.1.2:443",
];
for domain in invalid_domains {
assert!(
!validate_strict_domain(domain),
"Could not validate invalid strict domain: {domain}",
);
}
}
#[test]
fn test_validate_wildcard_domain() {
let valid_domains = vec![
"example.com",
"example.subdomain.com",
"https://example.com:8080",
"http://example.com",
"example.com:8080",
"example.com:443",
"localhost:443",
"127.0.0.1:443",
"*.com",
"example.*.com",
"example.com:*",
"*:443",
"localhost:*",
"127.0.0.*:*",
"*:*",
];
for domain in valid_domains {
assert!(
validate_wildcard_domain(domain),
"Could not validate wildcard domain: {domain}",
);
}
let invalid_domains = vec![
"",
"invalid.domain.",
"not_a_domain",
"http://example.com/path?query=1#fragment",
"*.",
".*",
"example.com:*:",
"*:443:",
":localhost:*",
"127.00.*:*",
];
for domain in invalid_domains {
assert!(
!validate_wildcard_domain(domain),
"Could not validate invalid wildcard domain: {domain}",
);
}
}
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/link_utils.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 3,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_1551422774306890675
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/crypto.rs
// Contains: 15 structs, 0 enums
//! Utilities for cryptographic algorithms
use std::ops::Deref;
use base64::Engine;
use error_stack::ResultExt;
use masking::{ExposeInterface, Secret};
use md5;
use pem;
use ring::{
aead::{self, BoundKey, OpeningKey, SealingKey, UnboundKey},
hmac, rand as ring_rand,
signature::{RsaKeyPair, RSA_PSS_SHA256},
};
#[cfg(feature = "logs")]
use router_env::logger;
use rsa::{pkcs8::DecodePublicKey, signature::Verifier};
use crate::{
consts::BASE64_ENGINE,
errors::{self, CustomResult},
pii::{self, EncryptionStrategy},
};
#[derive(Clone, Debug)]
struct NonceSequence(u128);
impl NonceSequence {
/// Byte index at which sequence number starts in a 16-byte (128-bit) sequence.
/// This byte index considers the big endian order used while encoding and decoding the nonce
/// to/from a 128-bit unsigned integer.
const SEQUENCE_NUMBER_START_INDEX: usize = 4;
/// Generate a random nonce sequence.
fn new() -> Result<Self, ring::error::Unspecified> {
use ring::rand::{SecureRandom, SystemRandom};
let rng = SystemRandom::new();
// 96-bit sequence number, stored in a 128-bit unsigned integer in big-endian order
let mut sequence_number = [0_u8; 128 / 8];
rng.fill(&mut sequence_number[Self::SEQUENCE_NUMBER_START_INDEX..])?;
let sequence_number = u128::from_be_bytes(sequence_number);
Ok(Self(sequence_number))
}
/// Returns the current nonce value as bytes.
fn current(&self) -> [u8; aead::NONCE_LEN] {
let mut nonce = [0_u8; aead::NONCE_LEN];
nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]);
nonce
}
/// Constructs a nonce sequence from bytes
fn from_bytes(bytes: [u8; aead::NONCE_LEN]) -> Self {
let mut sequence_number = [0_u8; 128 / 8];
sequence_number[Self::SEQUENCE_NUMBER_START_INDEX..].copy_from_slice(&bytes);
let sequence_number = u128::from_be_bytes(sequence_number);
Self(sequence_number)
}
}
impl aead::NonceSequence for NonceSequence {
fn advance(&mut self) -> Result<aead::Nonce, ring::error::Unspecified> {
let mut nonce = [0_u8; aead::NONCE_LEN];
nonce.copy_from_slice(&self.0.to_be_bytes()[Self::SEQUENCE_NUMBER_START_INDEX..]);
// Increment sequence number
self.0 = self.0.wrapping_add(1);
// Return previous sequence number as bytes
Ok(aead::Nonce::assume_unique_for_key(nonce))
}
}
/// Trait for cryptographically signing messages
pub trait SignMessage {
/// Takes in a secret and a message and returns the calculated signature as bytes
fn sign_message(
&self,
_secret: &[u8],
_msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError>;
}
/// Trait for cryptographically verifying a message against a signature
pub trait VerifySignature {
/// Takes in a secret, the signature and the message and verifies the message
/// against the signature
fn verify_signature(
&self,
_secret: &[u8],
_signature: &[u8],
_msg: &[u8],
) -> CustomResult<bool, errors::CryptoError>;
}
/// Trait for cryptographically encoding a message
pub trait EncodeMessage {
/// Takes in a secret and the message and encodes it, returning bytes
fn encode_message(
&self,
_secret: &[u8],
_msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError>;
}
/// Trait for cryptographically decoding a message
pub trait DecodeMessage {
/// Takes in a secret, an encoded messages and attempts to decode it, returning bytes
fn decode_message(
&self,
_secret: &[u8],
_msg: Secret<Vec<u8>, EncryptionStrategy>,
) -> CustomResult<Vec<u8>, errors::CryptoError>;
}
/// Represents no cryptographic algorithm.
/// Implements all crypto traits and acts like a Nop
#[derive(Debug)]
pub struct NoAlgorithm;
impl SignMessage for NoAlgorithm {
fn sign_message(
&self,
_secret: &[u8],
_msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
Ok(Vec::new())
}
}
impl VerifySignature for NoAlgorithm {
fn verify_signature(
&self,
_secret: &[u8],
_signature: &[u8],
_msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
Ok(true)
}
}
impl EncodeMessage for NoAlgorithm {
fn encode_message(
&self,
_secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
Ok(msg.to_vec())
}
}
impl DecodeMessage for NoAlgorithm {
fn decode_message(
&self,
_secret: &[u8],
msg: Secret<Vec<u8>, EncryptionStrategy>,
) -> CustomResult<Vec<u8>, errors::CryptoError> {
Ok(msg.expose())
}
}
/// Represents the HMAC-SHA-1 algorithm
#[derive(Debug)]
pub struct HmacSha1;
impl SignMessage for HmacSha1 {
fn sign_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, secret);
Ok(hmac::sign(&key, msg).as_ref().to_vec())
}
}
impl VerifySignature for HmacSha1 {
fn verify_signature(
&self,
secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY, secret);
Ok(hmac::verify(&key, msg, signature).is_ok())
}
}
/// Represents the HMAC-SHA-256 algorithm
#[derive(Debug)]
pub struct HmacSha256;
impl SignMessage for HmacSha256 {
fn sign_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA256, secret);
Ok(hmac::sign(&key, msg).as_ref().to_vec())
}
}
impl VerifySignature for HmacSha256 {
fn verify_signature(
&self,
secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA256, secret);
Ok(hmac::verify(&key, msg, signature).is_ok())
}
}
/// Represents the HMAC-SHA-512 algorithm
#[derive(Debug)]
pub struct HmacSha512;
impl SignMessage for HmacSha512 {
fn sign_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA512, secret);
Ok(hmac::sign(&key, msg).as_ref().to_vec())
}
}
impl VerifySignature for HmacSha512 {
fn verify_signature(
&self,
secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let key = hmac::Key::new(hmac::HMAC_SHA512, secret);
Ok(hmac::verify(&key, msg, signature).is_ok())
}
}
/// Blake3
#[derive(Debug)]
pub struct Blake3(String);
impl Blake3 {
/// Create a new instance of Blake3 with a key
pub fn new(key: impl Into<String>) -> Self {
Self(key.into())
}
}
impl SignMessage for Blake3 {
fn sign_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let key = blake3::derive_key(&self.0, secret);
let output = blake3::keyed_hash(&key, msg).as_bytes().to_vec();
Ok(output)
}
}
impl VerifySignature for Blake3 {
fn verify_signature(
&self,
secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let key = blake3::derive_key(&self.0, secret);
let output = blake3::keyed_hash(&key, msg);
Ok(output.as_bytes() == signature)
}
}
/// Represents the GCM-AES-256 algorithm
#[derive(Debug)]
pub struct GcmAes256;
impl EncodeMessage for GcmAes256 {
fn encode_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let nonce_sequence =
NonceSequence::new().change_context(errors::CryptoError::EncodingFailed)?;
let current_nonce = nonce_sequence.current();
let key = UnboundKey::new(&aead::AES_256_GCM, secret)
.change_context(errors::CryptoError::EncodingFailed)?;
let mut key = SealingKey::new(key, nonce_sequence);
let mut in_out = msg.to_vec();
key.seal_in_place_append_tag(aead::Aad::empty(), &mut in_out)
.change_context(errors::CryptoError::EncodingFailed)?;
in_out.splice(0..0, current_nonce);
Ok(in_out)
}
}
impl DecodeMessage for GcmAes256 {
fn decode_message(
&self,
secret: &[u8],
msg: Secret<Vec<u8>, EncryptionStrategy>,
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let msg = msg.expose();
let key = UnboundKey::new(&aead::AES_256_GCM, secret)
.change_context(errors::CryptoError::DecodingFailed)?;
let nonce_sequence = NonceSequence::from_bytes(
<[u8; aead::NONCE_LEN]>::try_from(
msg.get(..aead::NONCE_LEN)
.ok_or(errors::CryptoError::DecodingFailed)
.attach_printable("Failed to read the nonce form the encrypted ciphertext")?,
)
.change_context(errors::CryptoError::DecodingFailed)?,
);
let mut key = OpeningKey::new(key, nonce_sequence);
let mut binding = msg;
let output = binding.as_mut_slice();
let result = key
.open_within(aead::Aad::empty(), output, aead::NONCE_LEN..)
.change_context(errors::CryptoError::DecodingFailed)?;
Ok(result.to_vec())
}
}
/// Represents the ED25519 signature verification algorithm
#[derive(Debug)]
pub struct Ed25519;
impl Ed25519 {
/// ED25519 algorithm constants
const ED25519_PUBLIC_KEY_LEN: usize = 32;
const ED25519_SIGNATURE_LEN: usize = 64;
/// Validates ED25519 inputs (public key and signature lengths)
fn validate_inputs(
public_key: &[u8],
signature: &[u8],
) -> CustomResult<(), errors::CryptoError> {
// Validate public key length
if public_key.len() != Self::ED25519_PUBLIC_KEY_LEN {
return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!(
"Invalid ED25519 public key length: expected {} bytes, got {}",
Self::ED25519_PUBLIC_KEY_LEN,
public_key.len()
));
}
// Validate signature length
if signature.len() != Self::ED25519_SIGNATURE_LEN {
return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!(
"Invalid ED25519 signature length: expected {} bytes, got {}",
Self::ED25519_SIGNATURE_LEN,
signature.len()
));
}
Ok(())
}
}
impl VerifySignature for Ed25519 {
fn verify_signature(
&self,
public_key: &[u8],
signature: &[u8], // ED25519 signature bytes (must be 64 bytes)
msg: &[u8], // Message that was signed
) -> CustomResult<bool, errors::CryptoError> {
// Validate inputs first
Self::validate_inputs(public_key, signature)?;
// Create unparsed public key
let ring_public_key =
ring::signature::UnparsedPublicKey::new(&ring::signature::ED25519, public_key);
// Perform verification
match ring_public_key.verify(msg, signature) {
Ok(()) => Ok(true),
Err(_err) => {
#[cfg(feature = "logs")]
logger::error!("ED25519 signature verification failed: {:?}", _err);
Err(errors::CryptoError::SignatureVerificationFailed)
.attach_printable("ED25519 signature verification failed")
}
}
}
}
impl SignMessage for Ed25519 {
fn sign_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
if secret.len() != 32 {
return Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!(
"Invalid ED25519 private key length: expected 32 bytes, got {}",
secret.len()
));
}
let key_pair = ring::signature::Ed25519KeyPair::from_seed_unchecked(secret)
.change_context(errors::CryptoError::MessageSigningFailed)
.attach_printable("Failed to create ED25519 key pair from seed")?;
let signature = key_pair.sign(msg);
Ok(signature.as_ref().to_vec())
}
}
/// Secure Hash Algorithm 512
#[derive(Debug)]
pub struct Sha512;
/// Secure Hash Algorithm 256
#[derive(Debug)]
pub struct Sha256;
/// Trait for generating a digest for SHA
pub trait GenerateDigest {
/// takes a message and creates a digest for it
fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError>;
}
impl GenerateDigest for Sha512 {
fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> {
let digest = ring::digest::digest(&ring::digest::SHA512, message);
Ok(digest.as_ref().to_vec())
}
}
impl VerifySignature for Sha512 {
fn verify_signature(
&self,
_secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let msg_str = std::str::from_utf8(msg)
.change_context(errors::CryptoError::EncodingFailed)?
.to_owned();
let hashed_digest = hex::encode(
Self.generate_digest(msg_str.as_bytes())
.change_context(errors::CryptoError::SignatureVerificationFailed)?,
);
let hashed_digest_into_bytes = hashed_digest.into_bytes();
Ok(hashed_digest_into_bytes == signature)
}
}
/// MD5 hash function
#[derive(Debug)]
pub struct Md5;
impl GenerateDigest for Md5 {
fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> {
let digest = md5::compute(message);
Ok(digest.as_ref().to_vec())
}
}
impl VerifySignature for Md5 {
fn verify_signature(
&self,
_secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let hashed_digest = Self
.generate_digest(msg)
.change_context(errors::CryptoError::SignatureVerificationFailed)?;
Ok(hashed_digest == signature)
}
}
impl GenerateDigest for Sha256 {
fn generate_digest(&self, message: &[u8]) -> CustomResult<Vec<u8>, errors::CryptoError> {
let digest = ring::digest::digest(&ring::digest::SHA256, message);
Ok(digest.as_ref().to_vec())
}
}
impl VerifySignature for Sha256 {
fn verify_signature(
&self,
_secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
let hashed_digest = Self
.generate_digest(msg)
.change_context(errors::CryptoError::SignatureVerificationFailed)?;
let hashed_digest_into_bytes = hashed_digest.as_slice();
Ok(hashed_digest_into_bytes == signature)
}
}
/// Secure Hash Algorithm 256 with RSA public-key cryptosystem
#[derive(Debug)]
pub struct RsaSha256;
impl VerifySignature for RsaSha256 {
fn verify_signature(
&self,
secret: &[u8],
signature: &[u8],
msg: &[u8],
) -> CustomResult<bool, errors::CryptoError> {
// create verifying key
let decoded_public_key = BASE64_ENGINE
.decode(secret)
.change_context(errors::CryptoError::SignatureVerificationFailed)
.attach_printable("base64 decoding failed")?;
let string_public_key = String::from_utf8(decoded_public_key)
.change_context(errors::CryptoError::SignatureVerificationFailed)
.attach_printable("utf8 to string parsing failed")?;
let rsa_public_key = rsa::RsaPublicKey::from_public_key_pem(&string_public_key)
.change_context(errors::CryptoError::SignatureVerificationFailed)
.attach_printable("rsa public key transformation failed")?;
let verifying_key = rsa::pkcs1v15::VerifyingKey::<rsa::sha2::Sha256>::new(rsa_public_key);
// transfrom the signature
let decoded_signature = BASE64_ENGINE
.decode(signature)
.change_context(errors::CryptoError::SignatureVerificationFailed)
.attach_printable("base64 decoding failed")?;
let rsa_signature = rsa::pkcs1v15::Signature::try_from(&decoded_signature[..])
.change_context(errors::CryptoError::SignatureVerificationFailed)
.attach_printable("rsa signature transformation failed")?;
// signature verification
verifying_key
.verify(msg, &rsa_signature)
.map(|_| true)
.change_context(errors::CryptoError::SignatureVerificationFailed)
.attach_printable("signature verification step failed")
}
}
/// TripleDesEde3 hash function
#[derive(Debug)]
#[cfg(feature = "crypto_openssl")]
pub struct TripleDesEde3CBC {
padding: common_enums::CryptoPadding,
iv: Vec<u8>,
}
#[cfg(feature = "crypto_openssl")]
impl TripleDesEde3CBC {
const TRIPLE_DES_KEY_LENGTH: usize = 24;
/// Initialization Vector (IV) length for TripleDesEde3
pub const TRIPLE_DES_IV_LENGTH: usize = 8;
/// Constructor function to be used by the encryptor and decryptor to generate the data type
pub fn new(
padding: Option<common_enums::CryptoPadding>,
iv: Vec<u8>,
) -> Result<Self, errors::CryptoError> {
if iv.len() != Self::TRIPLE_DES_IV_LENGTH {
Err(errors::CryptoError::InvalidIvLength)?
};
let padding = padding.unwrap_or(common_enums::CryptoPadding::PKCS7);
Ok(Self { iv, padding })
}
}
#[cfg(feature = "crypto_openssl")]
impl EncodeMessage for TripleDesEde3CBC {
fn encode_message(
&self,
secret: &[u8],
msg: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
if secret.len() != Self::TRIPLE_DES_KEY_LENGTH {
Err(errors::CryptoError::InvalidKeyLength)?
}
let mut buffer = msg.to_vec();
if let common_enums::CryptoPadding::ZeroPadding = self.padding {
let pad_len = Self::TRIPLE_DES_IV_LENGTH - (buffer.len() % Self::TRIPLE_DES_IV_LENGTH);
if pad_len != Self::TRIPLE_DES_IV_LENGTH {
buffer.extend(vec![0u8; pad_len]);
}
};
let cipher = openssl::symm::Cipher::des_ede3_cbc();
openssl::symm::encrypt(cipher, secret, Some(&self.iv), &buffer)
.change_context(errors::CryptoError::EncodingFailed)
}
}
/// Generate a random string using a cryptographically secure pseudo-random number generator
/// (CSPRNG). Typically used for generating (readable) keys and passwords.
#[inline]
pub fn generate_cryptographically_secure_random_string(length: usize) -> String {
use rand::distributions::DistString;
rand::distributions::Alphanumeric.sample_string(&mut rand::rngs::OsRng, length)
}
/// Generate an array of random bytes using a cryptographically secure pseudo-random number
/// generator (CSPRNG). Typically used for generating keys.
#[inline]
pub fn generate_cryptographically_secure_random_bytes<const N: usize>() -> [u8; N] {
use rand::RngCore;
let mut bytes = [0; N];
rand::rngs::OsRng.fill_bytes(&mut bytes);
bytes
}
/// A wrapper type to store the encrypted data for sensitive pii domain data types
#[derive(Debug, Clone)]
pub struct Encryptable<T: Clone> {
inner: T,
encrypted: Secret<Vec<u8>, EncryptionStrategy>,
}
impl<T: Clone, S: masking::Strategy<T>> Encryptable<Secret<T, S>> {
/// constructor function to be used by the encryptor and decryptor to generate the data type
pub fn new(
masked_data: Secret<T, S>,
encrypted_data: Secret<Vec<u8>, EncryptionStrategy>,
) -> Self {
Self {
inner: masked_data,
encrypted: encrypted_data,
}
}
}
impl<T: Clone> Encryptable<T> {
/// Get the inner data while consuming self
#[inline]
pub fn into_inner(self) -> T {
self.inner
}
/// Get the reference to inner value
#[inline]
pub fn get_inner(&self) -> &T {
&self.inner
}
/// Get the inner encrypted data while consuming self
#[inline]
pub fn into_encrypted(self) -> Secret<Vec<u8>, EncryptionStrategy> {
self.encrypted
}
/// Deserialize inner value and return new Encryptable object
pub fn deserialize_inner_value<U, F>(
self,
f: F,
) -> CustomResult<Encryptable<U>, errors::ParsingError>
where
F: FnOnce(T) -> CustomResult<U, errors::ParsingError>,
U: Clone,
{
let inner = self.inner;
let encrypted = self.encrypted;
let inner = f(inner)?;
Ok(Encryptable { inner, encrypted })
}
/// consume self and modify the inner value
pub fn map<U: Clone>(self, f: impl FnOnce(T) -> U) -> Encryptable<U> {
let encrypted_data = self.encrypted;
let masked_data = f(self.inner);
Encryptable {
inner: masked_data,
encrypted: encrypted_data,
}
}
}
impl<T: Clone> Deref for Encryptable<Secret<T>> {
type Target = Secret<T>;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl<T: Clone> masking::Serialize for Encryptable<T>
where
T: masking::Serialize,
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
self.inner.serialize(serializer)
}
}
impl<T: Clone> PartialEq for Encryptable<T>
where
T: PartialEq,
{
fn eq(&self, other: &Self) -> bool {
self.inner.eq(&other.inner)
}
}
/// Type alias for `Option<Encryptable<Secret<String>>>`
pub type OptionalEncryptableSecretString = Option<Encryptable<Secret<String>>>;
/// Type alias for `Option<Encryptable<Secret<String>>>` used for `name` field
pub type OptionalEncryptableName = Option<Encryptable<Secret<String>>>;
/// Type alias for `Option<Encryptable<Secret<String>>>` used for `email` field
pub type OptionalEncryptableEmail = Option<Encryptable<Secret<String, pii::EmailStrategy>>>;
/// Type alias for `Option<Encryptable<Secret<String>>>` used for `phone` field
pub type OptionalEncryptablePhone = Option<Encryptable<Secret<String>>>;
/// Type alias for `Option<Encryptable<Secret<serde_json::Value>>>`
pub type OptionalEncryptableValue = Option<Encryptable<Secret<serde_json::Value>>>;
/// Type alias for `Option<Secret<serde_json::Value>>`
pub type OptionalSecretValue = Option<Secret<serde_json::Value>>;
/// Type alias for `Encryptable<Secret<String>>` used for `name` field
pub type EncryptableName = Encryptable<Secret<String>>;
/// Type alias for `Encryptable<Secret<String>>` used for `email` field
pub type EncryptableEmail = Encryptable<Secret<String, pii::EmailStrategy>>;
/// Represents the RSA-PSS-SHA256 signing algorithm
#[derive(Debug)]
pub struct RsaPssSha256;
impl SignMessage for RsaPssSha256 {
fn sign_message(
&self,
private_key_pem_bytes: &[u8],
msg_to_sign: &[u8],
) -> CustomResult<Vec<u8>, errors::CryptoError> {
let parsed_pem = pem::parse(private_key_pem_bytes)
.change_context(errors::CryptoError::EncodingFailed)
.attach_printable("Failed to parse PEM string")?;
let key_pair = match parsed_pem.tag() {
"PRIVATE KEY" => RsaKeyPair::from_pkcs8(parsed_pem.contents())
.change_context(errors::CryptoError::InvalidKeyLength)
.attach_printable("Failed to parse PKCS#8 DER with ring"),
"RSA PRIVATE KEY" => RsaKeyPair::from_der(parsed_pem.contents())
.change_context(errors::CryptoError::InvalidKeyLength)
.attach_printable("Failed to parse PKCS#1 DER (using from_der) with ring"),
tag => Err(errors::CryptoError::InvalidKeyLength).attach_printable(format!(
"Unexpected PEM tag: {tag}. Expected 'PRIVATE KEY' or 'RSA PRIVATE KEY'",
)),
}?;
let rng = ring_rand::SystemRandom::new();
let signature_len = key_pair.public().modulus_len();
let mut signature_bytes = vec![0; signature_len];
key_pair
.sign(&RSA_PSS_SHA256, &rng, msg_to_sign, &mut signature_bytes)
.change_context(errors::CryptoError::EncodingFailed)
.attach_printable("Failed to sign data with ring")?;
Ok(signature_bytes)
}
}
#[cfg(test)]
mod crypto_tests {
#![allow(clippy::expect_used)]
use super::{DecodeMessage, EncodeMessage, SignMessage, VerifySignature};
use crate::crypto::GenerateDigest;
#[test]
fn test_hmac_sha256_sign_message() {
let message = r#"{"type":"payment_intent"}"#.as_bytes();
let secret = "hmac_secret_1234".as_bytes();
let right_signature =
hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823e")
.expect("Right signature decoding");
let signature = super::HmacSha256
.sign_message(secret, message)
.expect("Signature");
assert_eq!(signature, right_signature);
}
#[test]
fn test_hmac_sha256_verify_signature() {
let right_signature =
hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823e")
.expect("Right signature decoding");
let wrong_signature =
hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f")
.expect("Wrong signature decoding");
let secret = "hmac_secret_1234".as_bytes();
let data = r#"{"type":"payment_intent"}"#.as_bytes();
let right_verified = super::HmacSha256
.verify_signature(secret, &right_signature, data)
.expect("Right signature verification result");
assert!(right_verified);
let wrong_verified = super::HmacSha256
.verify_signature(secret, &wrong_signature, data)
.expect("Wrong signature verification result");
assert!(!wrong_verified);
}
#[test]
fn test_sha256_verify_signature() {
let right_signature =
hex::decode("123250a72f4e961f31661dbcee0fec0f4714715dc5ae1b573f908a0a5381ddba")
.expect("Right signature decoding");
let wrong_signature =
hex::decode("123250a72f4e961f31661dbcee0fec0f4714715dc5ae1b573f908a0a5381ddbb")
.expect("Wrong signature decoding");
let secret = "".as_bytes();
let data = r#"AJHFH9349JASFJHADJ9834115USD2020-11-13.13:22:34711000000021406655APPROVED12345product_id"#.as_bytes();
let right_verified = super::Sha256
.verify_signature(secret, &right_signature, data)
.expect("Right signature verification result");
assert!(right_verified);
let wrong_verified = super::Sha256
.verify_signature(secret, &wrong_signature, data)
.expect("Wrong signature verification result");
assert!(!wrong_verified);
}
#[test]
fn test_hmac_sha512_sign_message() {
let message = r#"{"type":"payment_intent"}"#.as_bytes();
let secret = "hmac_secret_1234".as_bytes();
let right_signature = hex::decode("38b0bc1ea66b14793e39cd58e93d37b799a507442d0dd8d37443fa95dec58e57da6db4742636fea31201c48e57a66e73a308a2e5a5c6bb831e4e39fe2227c00f")
.expect("signature decoding");
let signature = super::HmacSha512
.sign_message(secret, message)
.expect("Signature");
assert_eq!(signature, right_signature);
}
#[test]
fn test_hmac_sha512_verify_signature() {
let right_signature = hex::decode("38b0bc1ea66b14793e39cd58e93d37b799a507442d0dd8d37443fa95dec58e57da6db4742636fea31201c48e57a66e73a308a2e5a5c6bb831e4e39fe2227c00f")
.expect("signature decoding");
let wrong_signature =
hex::decode("d5550730377011948f12cc28889bee590d2a5434d6f54b87562f2dbc2657823f")
.expect("Wrong signature decoding");
let secret = "hmac_secret_1234".as_bytes();
let data = r#"{"type":"payment_intent"}"#.as_bytes();
let right_verified = super::HmacSha512
.verify_signature(secret, &right_signature, data)
.expect("Right signature verification result");
assert!(right_verified);
let wrong_verified = super::HmacSha256
.verify_signature(secret, &wrong_signature, data)
.expect("Wrong signature verification result");
assert!(!wrong_verified);
}
#[test]
fn test_gcm_aes_256_encode_message() {
let message = r#"{"type":"PAYMENT"}"#.as_bytes();
let secret =
hex::decode("000102030405060708090a0b0c0d0e0f000102030405060708090a0b0c0d0e0f")
.expect("Secret decoding");
let algorithm = super::GcmAes256;
let encoded_message = algorithm
.encode_message(&secret, message)
.expect("Encoded message and tag");
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);
}
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/crypto.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 15,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_653998211949762902
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/custom_serde.rs
// Contains: 1 structs, 0 enums
//! Custom serialization/deserialization implementations.
/// Use the well-known ISO 8601 format when serializing and deserializing an
/// [`PrimitiveDateTime`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod iso8601 {
use std::num::NonZeroU8;
use serde::{ser::Error as _, Deserializer, Serialize, Serializer};
use time::{
format_description::well_known::{
iso8601::{Config, EncodedConfig, TimePrecision},
Iso8601,
},
serde::iso8601,
PrimitiveDateTime, UtcOffset,
};
const FORMAT_CONFIG: EncodedConfig = Config::DEFAULT
.set_time_precision(TimePrecision::Second {
decimal_digits: NonZeroU8::new(3),
})
.encode();
/// Serialize a [`PrimitiveDateTime`] using the well-known ISO 8601 format.
pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.assume_utc()
.format(&Iso8601::<FORMAT_CONFIG>)
.map_err(S::Error::custom)?
.serialize(serializer)
}
/// Deserialize an [`PrimitiveDateTime`] from its ISO 8601 representation.
pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error>
where
D: Deserializer<'a>,
{
iso8601::deserialize(deserializer).map(|offset_date_time| {
let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC);
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
})
}
/// Use the well-known ISO 8601 format when serializing and deserializing an
/// [`Option<PrimitiveDateTime>`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod option {
use serde::Serialize;
use time::format_description::well_known::Iso8601;
use super::*;
/// Serialize an [`Option<PrimitiveDateTime>`] using the well-known ISO 8601 format.
pub fn serialize<S>(
date_time: &Option<PrimitiveDateTime>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.map(|date_time| date_time.assume_utc().format(&Iso8601::<FORMAT_CONFIG>))
.transpose()
.map_err(S::Error::custom)?
.serialize(serializer)
}
/// Deserialize an [`Option<PrimitiveDateTime>`] from its ISO 8601 representation.
pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error>
where
D: Deserializer<'a>,
{
iso8601::option::deserialize(deserializer).map(|option_offset_date_time| {
option_offset_date_time.map(|offset_date_time| {
let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC);
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
})
})
}
}
/// Use the well-known ISO 8601 format which is without timezone when serializing and deserializing an
/// [`Option<PrimitiveDateTime>`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod option_without_timezone {
use serde::{de, Deserialize, Serialize};
use time::macros::format_description;
use super::*;
/// Serialize an [`Option<PrimitiveDateTime>`] using the well-known ISO 8601 format which is without timezone.
pub fn serialize<S>(
date_time: &Option<PrimitiveDateTime>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.map(|date_time| {
let format =
format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]");
date_time.assume_utc().format(format)
})
.transpose()
.map_err(S::Error::custom)?
.serialize(serializer)
}
/// Deserialize an [`Option<PrimitiveDateTime>`] from its ISO 8601 representation.
pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error>
where
D: Deserializer<'a>,
{
Option::deserialize(deserializer)?
.map(|time_string| {
let format =
format_description!("[year]-[month]-[day]T[hour]:[minute]:[second]");
PrimitiveDateTime::parse(time_string, format).map_err(|_| {
de::Error::custom(format!(
"Failed to parse PrimitiveDateTime from {time_string}"
))
})
})
.transpose()
}
}
}
/// Use the UNIX timestamp when serializing and deserializing an
/// [`PrimitiveDateTime`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod timestamp {
use serde::{Deserializer, Serialize, Serializer};
use time::{serde::timestamp, PrimitiveDateTime, UtcOffset};
/// Serialize a [`PrimitiveDateTime`] using UNIX timestamp.
pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.assume_utc()
.unix_timestamp()
.serialize(serializer)
}
/// Deserialize an [`PrimitiveDateTime`] from UNIX timestamp.
pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error>
where
D: Deserializer<'a>,
{
timestamp::deserialize(deserializer).map(|offset_date_time| {
let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC);
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
})
}
/// Use the UNIX timestamp when serializing and deserializing an
/// [`Option<PrimitiveDateTime>`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod option {
use serde::Serialize;
use super::*;
/// Serialize an [`Option<PrimitiveDateTime>`] from UNIX timestamp.
pub fn serialize<S>(
date_time: &Option<PrimitiveDateTime>,
serializer: S,
) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.map(|date_time| date_time.assume_utc().unix_timestamp())
.serialize(serializer)
}
/// Deserialize an [`Option<PrimitiveDateTime>`] from UNIX timestamp.
pub fn deserialize<'a, D>(deserializer: D) -> Result<Option<PrimitiveDateTime>, D::Error>
where
D: Deserializer<'a>,
{
timestamp::option::deserialize(deserializer).map(|option_offset_date_time| {
option_offset_date_time.map(|offset_date_time| {
let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC);
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
})
})
}
}
}
/// <https://github.com/serde-rs/serde/issues/994#issuecomment-316895860>
pub mod json_string {
use serde::{
de::{self, Deserialize, DeserializeOwned, Deserializer},
ser::{self, Serialize, Serializer},
};
/// Serialize a type to json_string format
pub fn serialize<T, S>(value: &T, serializer: S) -> Result<S::Ok, S::Error>
where
T: Serialize,
S: Serializer,
{
let j = serde_json::to_string(value).map_err(ser::Error::custom)?;
j.serialize(serializer)
}
/// Deserialize a string which is in json format
pub fn deserialize<'de, T, D>(deserializer: D) -> Result<T, D::Error>
where
T: DeserializeOwned,
D: Deserializer<'de>,
{
let j = String::deserialize(deserializer)?;
serde_json::from_str(&j).map_err(de::Error::custom)
}
}
/// Use a custom ISO 8601 format when serializing and deserializing
/// [`PrimitiveDateTime`][PrimitiveDateTime].
///
/// [PrimitiveDateTime]: ::time::PrimitiveDateTime
pub mod iso8601custom {
use serde::{ser::Error as _, Deserializer, Serialize, Serializer};
use time::{
format_description::well_known::{
iso8601::{Config, EncodedConfig, TimePrecision},
Iso8601,
},
serde::iso8601,
PrimitiveDateTime, UtcOffset,
};
const FORMAT_CONFIG: EncodedConfig = Config::DEFAULT
.set_time_precision(TimePrecision::Second {
decimal_digits: None,
})
.encode();
/// Serialize a [`PrimitiveDateTime`] using the well-known ISO 8601 format.
pub fn serialize<S>(date_time: &PrimitiveDateTime, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
date_time
.assume_utc()
.format(&Iso8601::<FORMAT_CONFIG>)
.map_err(S::Error::custom)?
.replace('T', " ")
.replace('Z', "")
.serialize(serializer)
}
/// Deserialize an [`PrimitiveDateTime`] from its ISO 8601 representation.
pub fn deserialize<'a, D>(deserializer: D) -> Result<PrimitiveDateTime, D::Error>
where
D: Deserializer<'a>,
{
iso8601::deserialize(deserializer).map(|offset_date_time| {
let utc_date_time = offset_date_time.to_offset(UtcOffset::UTC);
PrimitiveDateTime::new(utc_date_time.date(), utc_date_time.time())
})
}
}
#[cfg(test)]
mod tests {
use serde::{Deserialize, Serialize};
use serde_json::json;
#[test]
fn test_leap_second_parse() {
#[derive(Serialize, Deserialize)]
struct Try {
#[serde(with = "crate::custom_serde::iso8601")]
f: time::PrimitiveDateTime,
}
let leap_second_date_time = json!({"f": "2023-12-31T23:59:60.000Z"});
let deser = serde_json::from_value::<Try>(leap_second_date_time);
assert!(deser.is_ok())
}
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/custom_serde.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_3399729733404434167
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/types/primitive_wrappers.rs
// Contains: 3 structs, 0 enums
pub(crate) mod bool_wrappers {
use serde::{Deserialize, Serialize};
/// Bool that represents if Extended Authorization is Applied or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct ExtendedAuthorizationAppliedBool(bool);
impl From<bool> for ExtendedAuthorizationAppliedBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for ExtendedAuthorizationAppliedBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for ExtendedAuthorizationAppliedBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Extended Authorization is Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, Serialize, Deserialize, diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct RequestExtendedAuthorizationBool(bool);
impl From<bool> for RequestExtendedAuthorizationBool {
fn from(value: bool) -> Self {
Self(value)
}
}
impl RequestExtendedAuthorizationBool {
/// returns the inner bool value
pub fn is_true(&self) -> bool {
self.0
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB> for RequestExtendedAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for RequestExtendedAuthorizationBool
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
/// Bool that represents if Extended Authorization is always Requested or not
#[derive(
Clone, Copy, Debug, Eq, PartialEq, diesel::expression::AsExpression, Serialize, Deserialize,
)]
#[diesel(sql_type = diesel::sql_types::Bool)]
pub struct AlwaysRequestExtendedAuthorization(bool);
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Bool, DB>
for AlwaysRequestExtendedAuthorization
where
DB: diesel::backend::Backend,
bool: diesel::serialize::ToSql<diesel::sql_types::Bool, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>
for AlwaysRequestExtendedAuthorization
where
DB: diesel::backend::Backend,
bool: diesel::deserialize::FromSql<diesel::sql_types::Bool, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
bool::from_sql(value).map(Self)
}
}
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/types/primitive_wrappers.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 3,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_4432511803214784143
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/types/keymanager.rs
// Contains: 18 structs, 1 enums
#![allow(missing_docs)]
use core::fmt;
use base64::Engine;
use masking::{ExposeInterface, PeekInterface, Secret, Strategy, StrongSecret};
#[cfg(feature = "encryption_service")]
use router_env::logger;
#[cfg(feature = "km_forward_x_request_id")]
use router_env::tracing_actix_web::RequestId;
use rustc_hash::FxHashMap;
use serde::{
de::{self, Unexpected, Visitor},
ser, Deserialize, Deserializer, Serialize,
};
use crate::{
consts::BASE64_ENGINE,
crypto::Encryptable,
encryption::Encryption,
errors::{self, CustomResult},
id_type,
transformers::{ForeignFrom, ForeignTryFrom},
};
macro_rules! impl_get_tenant_for_request {
($ty:ident) => {
impl GetKeymanagerTenant for $ty {
fn get_tenant_id(&self, state: &KeyManagerState) -> id_type::TenantId {
match self.identifier {
Identifier::User(_) | Identifier::UserAuth(_) => state.global_tenant_id.clone(),
Identifier::Merchant(_) => state.tenant_id.clone(),
}
}
}
};
}
#[derive(Debug, Clone)]
pub struct KeyManagerState {
pub tenant_id: id_type::TenantId,
pub global_tenant_id: id_type::TenantId,
pub enabled: bool,
pub url: String,
pub client_idle_timeout: Option<u64>,
#[cfg(feature = "km_forward_x_request_id")]
pub request_id: Option<RequestId>,
#[cfg(feature = "keymanager_mtls")]
pub ca: Secret<String>,
#[cfg(feature = "keymanager_mtls")]
pub cert: Secret<String>,
pub infra_values: Option<serde_json::Value>,
}
impl KeyManagerState {
pub fn add_confirm_value_in_infra_values(
&self,
is_confirm_operation: bool,
) -> Option<serde_json::Value> {
self.infra_values.clone().map(|mut infra_values| {
if is_confirm_operation {
infra_values.as_object_mut().map(|obj| {
obj.insert(
"is_confirm_operation".to_string(),
serde_json::Value::Bool(true),
)
});
}
infra_values
})
}
}
pub trait GetKeymanagerTenant {
fn get_tenant_id(&self, state: &KeyManagerState) -> id_type::TenantId;
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
#[serde(tag = "data_identifier", content = "key_identifier")]
pub enum Identifier {
User(String),
Merchant(id_type::MerchantId),
UserAuth(String),
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
pub struct EncryptionCreateRequest {
#[serde(flatten)]
pub identifier: Identifier,
}
#[derive(Serialize, Deserialize, Debug, Eq, PartialEq, Clone)]
pub struct EncryptionTransferRequest {
#[serde(flatten)]
pub identifier: Identifier,
pub key: String,
}
#[derive(Debug, Deserialize, Serialize)]
pub struct DataKeyCreateResponse {
#[serde(flatten)]
pub identifier: Identifier,
pub key_version: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct BatchEncryptDataRequest {
#[serde(flatten)]
pub identifier: Identifier,
pub data: DecryptedDataGroup,
}
impl_get_tenant_for_request!(EncryptionCreateRequest);
impl_get_tenant_for_request!(EncryptionTransferRequest);
impl_get_tenant_for_request!(BatchEncryptDataRequest);
impl<S> From<(Secret<Vec<u8>, S>, Identifier)> for EncryptDataRequest
where
S: Strategy<Vec<u8>>,
{
fn from((secret, identifier): (Secret<Vec<u8>, S>, Identifier)) -> Self {
Self {
identifier,
data: DecryptedData(StrongSecret::new(secret.expose())),
}
}
}
impl<S> From<(FxHashMap<String, Secret<Vec<u8>, S>>, Identifier)> for BatchEncryptDataRequest
where
S: Strategy<Vec<u8>>,
{
fn from((map, identifier): (FxHashMap<String, Secret<Vec<u8>, S>>, Identifier)) -> Self {
let group = map
.into_iter()
.map(|(key, value)| (key, DecryptedData(StrongSecret::new(value.expose()))))
.collect();
Self {
identifier,
data: DecryptedDataGroup(group),
}
}
}
impl<S> From<(Secret<String, S>, Identifier)> for EncryptDataRequest
where
S: Strategy<String>,
{
fn from((secret, identifier): (Secret<String, S>, Identifier)) -> Self {
Self {
data: DecryptedData(StrongSecret::new(secret.expose().as_bytes().to_vec())),
identifier,
}
}
}
impl<S> From<(Secret<serde_json::Value, S>, Identifier)> for EncryptDataRequest
where
S: Strategy<serde_json::Value>,
{
fn from((secret, identifier): (Secret<serde_json::Value, S>, Identifier)) -> Self {
Self {
data: DecryptedData(StrongSecret::new(
secret.expose().to_string().as_bytes().to_vec(),
)),
identifier,
}
}
}
impl<S> From<(FxHashMap<String, Secret<serde_json::Value, S>>, Identifier)>
for BatchEncryptDataRequest
where
S: Strategy<serde_json::Value>,
{
fn from(
(map, identifier): (FxHashMap<String, Secret<serde_json::Value, S>>, Identifier),
) -> Self {
let group = map
.into_iter()
.map(|(key, value)| {
(
key,
DecryptedData(StrongSecret::new(
value.expose().to_string().as_bytes().to_vec(),
)),
)
})
.collect();
Self {
data: DecryptedDataGroup(group),
identifier,
}
}
}
impl<S> From<(FxHashMap<String, Secret<String, S>>, Identifier)> for BatchEncryptDataRequest
where
S: Strategy<String>,
{
fn from((map, identifier): (FxHashMap<String, Secret<String, S>>, Identifier)) -> Self {
let group = map
.into_iter()
.map(|(key, value)| {
(
key,
DecryptedData(StrongSecret::new(value.expose().as_bytes().to_vec())),
)
})
.collect();
Self {
data: DecryptedDataGroup(group),
identifier,
}
}
}
#[derive(Serialize, Deserialize, Debug)]
pub struct EncryptDataRequest {
#[serde(flatten)]
pub identifier: Identifier,
pub data: DecryptedData,
}
#[derive(Debug, Serialize, serde::Deserialize)]
pub struct DecryptedDataGroup(pub FxHashMap<String, DecryptedData>);
#[derive(Debug, Serialize, Deserialize)]
pub struct BatchEncryptDataResponse {
pub data: EncryptedDataGroup,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct EncryptDataResponse {
pub data: EncryptedData,
}
#[derive(Debug, Serialize, serde::Deserialize)]
pub struct EncryptedDataGroup(pub FxHashMap<String, EncryptedData>);
#[derive(Debug)]
pub struct TransientBatchDecryptDataRequest {
pub identifier: Identifier,
pub data: FxHashMap<String, StrongSecret<Vec<u8>>>,
}
#[derive(Debug)]
pub struct TransientDecryptDataRequest {
pub identifier: Identifier,
pub data: StrongSecret<Vec<u8>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BatchDecryptDataRequest {
#[serde(flatten)]
pub identifier: Identifier,
pub data: FxHashMap<String, StrongSecret<String>>,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DecryptDataRequest {
#[serde(flatten)]
pub identifier: Identifier,
pub data: StrongSecret<String>,
}
impl_get_tenant_for_request!(EncryptDataRequest);
impl_get_tenant_for_request!(TransientBatchDecryptDataRequest);
impl_get_tenant_for_request!(TransientDecryptDataRequest);
impl_get_tenant_for_request!(BatchDecryptDataRequest);
impl_get_tenant_for_request!(DecryptDataRequest);
impl<T, S> ForeignFrom<(FxHashMap<String, Secret<T, S>>, BatchEncryptDataResponse)>
for FxHashMap<String, Encryptable<Secret<T, S>>>
where
T: Clone,
S: Strategy<T> + Send,
{
fn foreign_from(
(mut masked_data, response): (FxHashMap<String, Secret<T, S>>, BatchEncryptDataResponse),
) -> Self {
response
.data
.0
.into_iter()
.flat_map(|(k, v)| {
masked_data.remove(&k).map(|inner| {
(
k,
Encryptable::new(inner.clone(), v.data.peek().clone().into()),
)
})
})
.collect()
}
}
impl<T, S> ForeignFrom<(Secret<T, S>, EncryptDataResponse)> for Encryptable<Secret<T, S>>
where
T: Clone,
S: Strategy<T> + Send,
{
fn foreign_from((masked_data, response): (Secret<T, S>, EncryptDataResponse)) -> Self {
Self::new(masked_data, response.data.data.peek().clone().into())
}
}
pub trait DecryptedDataConversion<T: Clone, S: Strategy<T> + Send>: Sized {
fn convert(
value: &DecryptedData,
encryption: Encryption,
) -> CustomResult<Self, errors::CryptoError>;
}
impl<S: Strategy<String> + Send> DecryptedDataConversion<String, S>
for Encryptable<Secret<String, S>>
{
fn convert(
value: &DecryptedData,
encryption: Encryption,
) -> CustomResult<Self, errors::CryptoError> {
let string = String::from_utf8(value.clone().inner().peek().clone()).map_err(|_err| {
#[cfg(feature = "encryption_service")]
logger::error!("Decryption error {:?}", _err);
errors::CryptoError::DecodingFailed
})?;
Ok(Self::new(Secret::new(string), encryption.into_inner()))
}
}
impl<S: Strategy<serde_json::Value> + Send> DecryptedDataConversion<serde_json::Value, S>
for Encryptable<Secret<serde_json::Value, S>>
{
fn convert(
value: &DecryptedData,
encryption: Encryption,
) -> CustomResult<Self, errors::CryptoError> {
let val = serde_json::from_slice(value.clone().inner().peek()).map_err(|_err| {
#[cfg(feature = "encryption_service")]
logger::error!("Decryption error {:?}", _err);
errors::CryptoError::DecodingFailed
})?;
Ok(Self::new(Secret::new(val), encryption.clone().into_inner()))
}
}
impl<S: Strategy<Vec<u8>> + Send> DecryptedDataConversion<Vec<u8>, S>
for Encryptable<Secret<Vec<u8>, S>>
{
fn convert(
value: &DecryptedData,
encryption: Encryption,
) -> CustomResult<Self, errors::CryptoError> {
Ok(Self::new(
Secret::new(value.clone().inner().peek().clone()),
encryption.clone().into_inner(),
))
}
}
impl<T, S> ForeignTryFrom<(Encryption, DecryptDataResponse)> for Encryptable<Secret<T, S>>
where
T: Clone,
S: Strategy<T> + Send,
Self: DecryptedDataConversion<T, S>,
{
type Error = error_stack::Report<errors::CryptoError>;
fn foreign_try_from(
(encrypted_data, response): (Encryption, DecryptDataResponse),
) -> Result<Self, Self::Error> {
Self::convert(&response.data, encrypted_data)
}
}
impl<T, S> ForeignTryFrom<(FxHashMap<String, Encryption>, BatchDecryptDataResponse)>
for FxHashMap<String, Encryptable<Secret<T, S>>>
where
T: Clone,
S: Strategy<T> + Send,
Encryptable<Secret<T, S>>: DecryptedDataConversion<T, S>,
{
type Error = error_stack::Report<errors::CryptoError>;
fn foreign_try_from(
(mut encrypted_data, response): (FxHashMap<String, Encryption>, BatchDecryptDataResponse),
) -> Result<Self, Self::Error> {
response
.data
.0
.into_iter()
.map(|(k, v)| match encrypted_data.remove(&k) {
Some(encrypted) => Ok((k.clone(), Encryptable::convert(&v, encrypted.clone())?)),
None => Err(errors::CryptoError::DecodingFailed)?,
})
.collect()
}
}
impl From<(Encryption, Identifier)> for TransientDecryptDataRequest {
fn from((encryption, identifier): (Encryption, Identifier)) -> Self {
Self {
data: StrongSecret::new(encryption.clone().into_inner().expose()),
identifier,
}
}
}
impl From<(FxHashMap<String, Encryption>, Identifier)> for TransientBatchDecryptDataRequest {
fn from((map, identifier): (FxHashMap<String, Encryption>, Identifier)) -> Self {
let data = map
.into_iter()
.map(|(k, v)| (k, StrongSecret::new(v.clone().into_inner().expose())))
.collect();
Self { data, identifier }
}
}
#[derive(Debug, Serialize, Deserialize)]
pub struct BatchDecryptDataResponse {
pub data: DecryptedDataGroup,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct DecryptDataResponse {
pub data: DecryptedData,
}
#[derive(Clone, Debug)]
pub struct DecryptedData(StrongSecret<Vec<u8>>);
impl Serialize for DecryptedData {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let data = BASE64_ENGINE.encode(self.0.peek());
serializer.serialize_str(&data)
}
}
impl<'de> Deserialize<'de> for DecryptedData {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct DecryptedDataVisitor;
impl Visitor<'_> for DecryptedDataVisitor {
type Value = DecryptedData;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("string of the format {version}:{base64_encoded_data}'")
}
fn visit_str<E>(self, value: &str) -> Result<DecryptedData, E>
where
E: de::Error,
{
let dec_data = BASE64_ENGINE.decode(value).map_err(|err| {
let err = err.to_string();
E::invalid_value(Unexpected::Str(value), &err.as_str())
})?;
Ok(DecryptedData(dec_data.into()))
}
}
deserializer.deserialize_str(DecryptedDataVisitor)
}
}
impl DecryptedData {
pub fn from_data(data: StrongSecret<Vec<u8>>) -> Self {
Self(data)
}
pub fn inner(self) -> StrongSecret<Vec<u8>> {
self.0
}
}
#[derive(Debug)]
pub struct EncryptedData {
pub data: StrongSecret<Vec<u8>>,
}
impl Serialize for EncryptedData {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let data = String::from_utf8(self.data.peek().clone()).map_err(ser::Error::custom)?;
serializer.serialize_str(data.as_str())
}
}
impl<'de> Deserialize<'de> for EncryptedData {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct EncryptedDataVisitor;
impl Visitor<'_> for EncryptedDataVisitor {
type Value = EncryptedData;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("string of the format {version}:{base64_encoded_data}'")
}
fn visit_str<E>(self, value: &str) -> Result<EncryptedData, E>
where
E: de::Error,
{
Ok(EncryptedData {
data: StrongSecret::new(value.as_bytes().to_vec()),
})
}
}
deserializer.deserialize_str(EncryptedDataVisitor)
}
}
/// A trait which converts the struct to Hashmap required for encryption and back to struct
pub trait ToEncryptable<T, S: Clone, E>: Sized {
/// Serializes the type to a hashmap
fn to_encryptable(self) -> FxHashMap<String, E>;
/// Deserializes the hashmap back to the type
fn from_encryptable(
hashmap: FxHashMap<String, Encryptable<S>>,
) -> CustomResult<T, errors::ParsingError>;
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/types/keymanager.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 18,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_8607023723694094507
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/types/user/core.rs
// Contains: 1 structs, 0 enums
use diesel::{deserialize::FromSqlRow, expression::AsExpression};
use crate::id_type;
/// Struct for lineageContext
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, AsExpression, FromSqlRow)]
#[diesel(sql_type = diesel::sql_types::Jsonb)]
pub struct LineageContext {
/// user_id: String
pub user_id: String,
/// merchant_id: MerchantId
pub merchant_id: id_type::MerchantId,
/// role_id: String
pub role_id: String,
/// org_id: OrganizationId
pub org_id: id_type::OrganizationId,
/// profile_id: ProfileId
pub profile_id: id_type::ProfileId,
/// tenant_id: TenantId
pub tenant_id: id_type::TenantId,
}
crate::impl_to_sql_from_sql_json!(LineageContext);
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/types/user/core.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_7892931939774120745
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/types/user/theme.rs
// Contains: 1 structs, 1 enums
use common_enums::EntityType;
use serde::{Deserialize, Serialize};
use crate::{
events::{ApiEventMetric, ApiEventsType},
id_type, impl_api_event_type,
};
/// Enum for having all the required lineage for every level.
/// Currently being used for theme related APIs and queries.
#[derive(Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(tag = "entity_type", rename_all = "snake_case")]
pub enum ThemeLineage {
/// Tenant lineage variant
Tenant {
/// tenant_id: TenantId
tenant_id: id_type::TenantId,
},
/// Org lineage variant
Organization {
/// tenant_id: TenantId
tenant_id: id_type::TenantId,
/// org_id: OrganizationId
org_id: id_type::OrganizationId,
},
/// Merchant lineage variant
Merchant {
/// tenant_id: TenantId
tenant_id: id_type::TenantId,
/// org_id: OrganizationId
org_id: id_type::OrganizationId,
/// merchant_id: MerchantId
merchant_id: id_type::MerchantId,
},
/// Profile lineage variant
Profile {
/// tenant_id: TenantId
tenant_id: id_type::TenantId,
/// org_id: OrganizationId
org_id: id_type::OrganizationId,
/// merchant_id: MerchantId
merchant_id: id_type::MerchantId,
/// profile_id: ProfileId
profile_id: id_type::ProfileId,
},
}
impl_api_event_type!(Miscellaneous, (ThemeLineage));
impl ThemeLineage {
/// Constructor for ThemeLineage
pub fn new(
entity_type: EntityType,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
merchant_id: id_type::MerchantId,
profile_id: id_type::ProfileId,
) -> Self {
match entity_type {
EntityType::Tenant => Self::Tenant { tenant_id },
EntityType::Organization => Self::Organization { tenant_id, org_id },
EntityType::Merchant => Self::Merchant {
tenant_id,
org_id,
merchant_id,
},
EntityType::Profile => Self::Profile {
tenant_id,
org_id,
merchant_id,
profile_id,
},
}
}
/// Get the entity_type from the lineage
pub fn entity_type(&self) -> EntityType {
match self {
Self::Tenant { .. } => EntityType::Tenant,
Self::Organization { .. } => EntityType::Organization,
Self::Merchant { .. } => EntityType::Merchant,
Self::Profile { .. } => EntityType::Profile,
}
}
/// Get the tenant_id from the lineage
pub fn tenant_id(&self) -> &id_type::TenantId {
match self {
Self::Tenant { tenant_id }
| Self::Organization { tenant_id, .. }
| Self::Merchant { tenant_id, .. }
| Self::Profile { tenant_id, .. } => tenant_id,
}
}
/// Get the org_id from the lineage
pub fn org_id(&self) -> Option<&id_type::OrganizationId> {
match self {
Self::Tenant { .. } => None,
Self::Organization { org_id, .. }
| Self::Merchant { org_id, .. }
| Self::Profile { org_id, .. } => Some(org_id),
}
}
/// Get the merchant_id from the lineage
pub fn merchant_id(&self) -> Option<&id_type::MerchantId> {
match self {
Self::Tenant { .. } | Self::Organization { .. } => None,
Self::Merchant { merchant_id, .. } | Self::Profile { merchant_id, .. } => {
Some(merchant_id)
}
}
}
/// Get the profile_id from the lineage
pub fn profile_id(&self) -> Option<&id_type::ProfileId> {
match self {
Self::Tenant { .. } | Self::Organization { .. } | Self::Merchant { .. } => None,
Self::Profile { profile_id, .. } => Some(profile_id),
}
}
/// Get higher lineages from the current lineage
pub fn get_same_and_higher_lineages(self) -> Vec<Self> {
match &self {
Self::Tenant { .. } => vec![self],
Self::Organization { tenant_id, .. } => vec![
Self::Tenant {
tenant_id: tenant_id.clone(),
},
self,
],
Self::Merchant {
tenant_id, org_id, ..
} => vec![
Self::Tenant {
tenant_id: tenant_id.clone(),
},
Self::Organization {
tenant_id: tenant_id.clone(),
org_id: org_id.clone(),
},
self,
],
Self::Profile {
tenant_id,
org_id,
merchant_id,
..
} => vec![
Self::Tenant {
tenant_id: tenant_id.clone(),
},
Self::Organization {
tenant_id: tenant_id.clone(),
org_id: org_id.clone(),
},
Self::Merchant {
tenant_id: tenant_id.clone(),
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
},
self,
],
}
}
}
/// Struct for holding the theme settings for email
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
pub struct EmailThemeConfig {
/// The entity name to be used in the email
pub entity_name: String,
/// The URL of the entity logo to be used in the email
pub entity_logo_url: String,
/// The primary color to be used in the email
pub primary_color: String,
/// The foreground color to be used in the email
pub foreground_color: String,
/// The background color to be used in the email
pub background_color: String,
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/types/user/theme.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_7560330797755923019
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/id_type/global_id.rs
// Contains: 1 structs, 2 enums
pub(super) mod customer;
pub(super) mod payment;
pub(super) mod payment_methods;
pub(super) mod refunds;
pub(super) mod token;
use diesel::{backend::Backend, deserialize::FromSql, serialize::ToSql, sql_types};
use error_stack::ResultExt;
use thiserror::Error;
use crate::{
consts::{CELL_IDENTIFIER_LENGTH, MAX_GLOBAL_ID_LENGTH, MIN_GLOBAL_ID_LENGTH},
errors, generate_time_ordered_id,
id_type::{AlphaNumericId, AlphaNumericIdError, LengthId, LengthIdError},
};
#[derive(Debug, Clone, Hash, PartialEq, Eq, serde::Serialize)]
/// A global id that can be used to identify any entity
/// This id will have information about the entity and cell in a distributed system architecture
pub(crate) struct GlobalId(LengthId<MAX_GLOBAL_ID_LENGTH, MIN_GLOBAL_ID_LENGTH>);
#[derive(Clone, Copy)]
/// Entities that can be identified by a global id
pub(crate) enum GlobalEntity {
Customer,
Payment,
Attempt,
PaymentMethod,
Refund,
PaymentMethodSession,
Token,
}
impl GlobalEntity {
fn prefix(self) -> &'static str {
match self {
Self::Customer => "cus",
Self::Payment => "pay",
Self::PaymentMethod => "pm",
Self::Attempt => "att",
Self::Refund => "ref",
Self::PaymentMethodSession => "pms",
Self::Token => "tok",
}
}
}
/// Cell identifier for an instance / deployment of application
#[derive(Debug, Clone, Hash, PartialEq, Eq)]
pub struct CellId(LengthId<CELL_IDENTIFIER_LENGTH, CELL_IDENTIFIER_LENGTH>);
#[derive(Debug, Error, PartialEq, Eq)]
pub enum CellIdError {
#[error("cell id error: {0}")]
InvalidCellLength(LengthIdError),
#[error("{0}")]
InvalidCellIdFormat(AlphaNumericIdError),
}
impl From<LengthIdError> for CellIdError {
fn from(error: LengthIdError) -> Self {
Self::InvalidCellLength(error)
}
}
impl From<AlphaNumericIdError> for CellIdError {
fn from(error: AlphaNumericIdError) -> Self {
Self::InvalidCellIdFormat(error)
}
}
impl CellId {
/// Create a new cell id from a string
fn from_str(cell_id_string: impl AsRef<str>) -> Result<Self, CellIdError> {
let trimmed_input_string = cell_id_string.as_ref().trim().to_string();
let alphanumeric_id = AlphaNumericId::from(trimmed_input_string.into())?;
let length_id = LengthId::from_alphanumeric_id(alphanumeric_id)?;
Ok(Self(length_id))
}
/// Create a new cell id from a string
pub fn from_string(
input_string: impl AsRef<str>,
) -> error_stack::Result<Self, errors::ValidationError> {
Self::from_str(input_string).change_context(
errors::ValidationError::IncorrectValueProvided {
field_name: "cell_id",
},
)
}
/// Get the string representation of the cell id
fn get_string_repr(&self) -> &str {
&self.0 .0 .0
}
}
impl<'de> serde::Deserialize<'de> for CellId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let deserialized_string = String::deserialize(deserializer)?;
Self::from_str(deserialized_string.as_str()).map_err(serde::de::Error::custom)
}
}
/// Error generated from violation of constraints for MerchantReferenceId
#[derive(Debug, Error, PartialEq, Eq)]
pub(crate) enum GlobalIdError {
/// The format for the global id is invalid
#[error("The id format is invalid, expected format is {{cell_id:5}}_{{entity_prefix:3}}_{{uuid:32}}_{{random:24}}")]
InvalidIdFormat,
/// LengthIdError and AlphanumericIdError
#[error("{0}")]
LengthIdError(#[from] LengthIdError),
/// CellIdError because of invalid cell id format
#[error("{0}")]
CellIdError(#[from] CellIdError),
}
impl GlobalId {
/// Create a new global id from entity and cell information
/// The entity prefix is used to identify the entity, `cus` for customers, `pay`` for payments etc.
pub fn generate(cell_id: &CellId, entity: GlobalEntity) -> Self {
let prefix = format!("{}_{}", cell_id.get_string_repr(), entity.prefix());
let id = generate_time_ordered_id(&prefix);
let alphanumeric_id = AlphaNumericId::new_unchecked(id);
Self(LengthId::new_unchecked(alphanumeric_id))
}
pub(crate) fn from_string(
input_string: std::borrow::Cow<'static, str>,
) -> Result<Self, GlobalIdError> {
let length_id = LengthId::from(input_string)?;
let input_string = &length_id.0 .0;
let (cell_id, _remaining) = input_string
.split_once("_")
.ok_or(GlobalIdError::InvalidIdFormat)?;
CellId::from_str(cell_id)?;
Ok(Self(length_id))
}
pub(crate) fn get_string_repr(&self) -> &str {
&self.0 .0 .0
}
}
impl<DB> ToSql<sql_types::Text, DB> for GlobalId
where
DB: Backend,
String: ToSql<sql_types::Text, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0 .0 .0.to_sql(out)
}
}
impl<DB> FromSql<sql_types::Text, DB> for GlobalId
where
DB: Backend,
String: FromSql<sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
let string_val = String::from_sql(value)?;
let alphanumeric_id = AlphaNumericId::from(string_val.into())?;
let length_id = LengthId::from_alphanumeric_id(alphanumeric_id)?;
Ok(Self(length_id))
}
}
/// Deserialize the global id from string
/// The format should match {cell_id:5}_{entity_prefix:3}_{time_ordered_id:32}_{.*:24}
impl<'de> serde::Deserialize<'de> for GlobalId {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: serde::Deserializer<'de>,
{
let deserialized_string = String::deserialize(deserializer)?;
Self::from_string(deserialized_string.into()).map_err(serde::de::Error::custom)
}
}
#[cfg(test)]
mod global_id_tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn test_cell_id_from_str() {
let cell_id_string = "12345";
let cell_id = CellId::from_str(cell_id_string).unwrap();
assert_eq!(cell_id.get_string_repr(), cell_id_string);
}
#[test]
fn test_global_id_generate() {
let cell_id_string = "12345";
let entity = GlobalEntity::Customer;
let cell_id = CellId::from_str(cell_id_string).unwrap();
let global_id = GlobalId::generate(&cell_id, entity);
// Generate a regex for globalid
// Eg - 12abc_cus_abcdefghijklmnopqrstuvwxyz1234567890
let regex = regex::Regex::new(r"[a-z0-9]{5}_cus_[a-z0-9]{32}").unwrap();
assert!(regex.is_match(&global_id.0 .0 .0));
}
#[test]
fn test_global_id_from_string() {
let input_string = "12345_cus_abcdefghijklmnopqrstuvwxyz1234567890";
let global_id = GlobalId::from_string(input_string.into()).unwrap();
assert_eq!(global_id.0 .0 .0, input_string);
}
#[test]
fn test_global_id_deser() {
let input_string_for_serde_json_conversion =
r#""12345_cus_abcdefghijklmnopqrstuvwxyz1234567890""#;
let input_string = "12345_cus_abcdefghijklmnopqrstuvwxyz1234567890";
let global_id =
serde_json::from_str::<GlobalId>(input_string_for_serde_json_conversion).unwrap();
assert_eq!(global_id.0 .0 .0, input_string);
}
#[test]
fn test_global_id_deser_error() {
let input_string_for_serde_json_conversion =
r#""123_45_cus_abcdefghijklmnopqrstuvwxyz1234567890""#;
let global_id = serde_json::from_str::<GlobalId>(input_string_for_serde_json_conversion);
assert!(global_id.is_err());
let expected_error_message = format!(
"cell id error: the minimum required length for this field is {CELL_IDENTIFIER_LENGTH}"
);
let error_message = global_id.unwrap_err().to_string();
assert_eq!(error_message, expected_error_message);
}
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/id_type/global_id.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_-5097360531389682442
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/id_type/global_id/payment_methods.rs
// Contains: 2 structs, 2 enums
use error_stack::ResultExt;
use crate::{
errors::CustomResult,
id_type::global_id::{CellId, GlobalEntity, GlobalId},
};
/// A global id that can be used to identify a payment method
#[derive(
Debug,
Clone,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Text)]
pub struct GlobalPaymentMethodId(GlobalId);
/// A global id that can be used to identify a payment method session
#[derive(
Debug,
Clone,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Text)]
pub struct GlobalPaymentMethodSessionId(GlobalId);
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
pub enum GlobalPaymentMethodIdError {
#[error("Failed to construct GlobalPaymentMethodId")]
ConstructionError,
}
#[derive(Debug, thiserror::Error, Clone, PartialEq, Eq)]
pub enum GlobalPaymentMethodSessionIdError {
#[error("Failed to construct GlobalPaymentMethodSessionId")]
ConstructionError,
}
impl GlobalPaymentMethodSessionId {
/// Create a new GlobalPaymentMethodSessionId from cell id information
pub fn generate(
cell_id: &CellId,
) -> error_stack::Result<Self, GlobalPaymentMethodSessionIdError> {
let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethodSession);
Ok(Self(global_id))
}
/// Get the string representation of the id
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Construct a redis key from the id to be stored in redis
pub fn get_redis_key(&self) -> String {
format!("payment_method_session:{}", self.get_string_repr())
}
}
#[cfg(feature = "v2")]
impl crate::events::ApiEventMetric for GlobalPaymentMethodSessionId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::PaymentMethodSession {
payment_method_session_id: self.clone(),
})
}
}
impl crate::events::ApiEventMetric for GlobalPaymentMethodId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(
crate::events::ApiEventsType::PaymentMethodListForPaymentMethods {
payment_method_id: self.clone(),
},
)
}
}
impl GlobalPaymentMethodId {
/// Create a new GlobalPaymentMethodId from cell id information
pub fn generate(cell_id: &CellId) -> error_stack::Result<Self, GlobalPaymentMethodIdError> {
let global_id = GlobalId::generate(cell_id, GlobalEntity::PaymentMethod);
Ok(Self(global_id))
}
/// Get string representation of the id
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Construct a new GlobalPaymentMethodId from a string
pub fn generate_from_string(value: String) -> CustomResult<Self, GlobalPaymentMethodIdError> {
let id = GlobalId::from_string(value.into())
.change_context(GlobalPaymentMethodIdError::ConstructionError)?;
Ok(Self(id))
}
}
impl<DB> diesel::Queryable<diesel::sql_types::Text, DB> for GlobalPaymentMethodId
where
DB: diesel::backend::Backend,
Self: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodId
where
DB: diesel::backend::Backend,
GlobalId: diesel::serialize::ToSql<diesel::sql_types::Text, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodId
where
DB: diesel::backend::Backend,
GlobalId: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
let global_id = GlobalId::from_sql(value)?;
Ok(Self(global_id))
}
}
impl<DB> diesel::Queryable<diesel::sql_types::Text, DB> for GlobalPaymentMethodSessionId
where
DB: diesel::backend::Backend,
Self: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
Ok(row)
}
}
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodSessionId
where
DB: diesel::backend::Backend,
GlobalId: diesel::serialize::ToSql<diesel::sql_types::Text, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Text, DB> for GlobalPaymentMethodSessionId
where
DB: diesel::backend::Backend,
GlobalId: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
let global_id = GlobalId::from_sql(value)?;
Ok(Self(global_id))
}
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/id_type/global_id/payment_methods.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_common_utils_8467217108537756594
|
clm
|
file
|
// Repository: hyperswitch
// Crate: common_utils
// File: crates/common_utils/src/id_type/global_id/refunds.rs
// Contains: 1 structs, 0 enums
use error_stack::ResultExt;
use crate::errors;
/// A global id that can be used to identify a refund
#[derive(
Debug,
Clone,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Text)]
pub struct GlobalRefundId(super::GlobalId);
// Database related implementations so that this field can be used directly in the database tables
crate::impl_queryable_id_type!(GlobalRefundId);
impl GlobalRefundId {
/// Get string representation of the id
pub fn get_string_repr(&self) -> &str {
self.0.get_string_repr()
}
/// Generate a new GlobalRefundId from a cell id
pub fn generate(cell_id: &crate::id_type::CellId) -> Self {
let global_id = super::GlobalId::generate(cell_id, super::GlobalEntity::Refund);
Self(global_id)
}
}
// TODO: refactor the macro to include this id use case as well
impl TryFrom<std::borrow::Cow<'static, str>> for GlobalRefundId {
type Error = error_stack::Report<errors::ValidationError>;
fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> {
let merchant_ref_id = super::GlobalId::from_string(value).change_context(
errors::ValidationError::IncorrectValueProvided {
field_name: "refund_id",
},
)?;
Ok(Self(merchant_ref_id))
}
}
// TODO: refactor the macro to include this id use case as well
impl<DB> diesel::serialize::ToSql<diesel::sql_types::Text, DB> for GlobalRefundId
where
DB: diesel::backend::Backend,
super::GlobalId: diesel::serialize::ToSql<diesel::sql_types::Text, DB>,
{
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, DB>,
) -> diesel::serialize::Result {
self.0.to_sql(out)
}
}
impl<DB> diesel::deserialize::FromSql<diesel::sql_types::Text, DB> for GlobalRefundId
where
DB: diesel::backend::Backend,
super::GlobalId: diesel::deserialize::FromSql<diesel::sql_types::Text, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
super::GlobalId::from_sql(value).map(Self)
}
}
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/id_type/global_id/refunds.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_8023859856720245509
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/tokenization.rs
// Contains: 3 structs, 1 enums
use common_enums;
use common_utils::{
self, date_time,
errors::{CustomResult, ValidationError},
types::keymanager,
};
use masking::Secret;
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct Tokenization {
pub id: common_utils::id_type::GlobalTokenId,
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: common_utils::id_type::GlobalCustomerId,
pub locker_id: String,
pub created_at: PrimitiveDateTime,
pub updated_at: PrimitiveDateTime,
pub flag: common_enums::TokenizationFlag,
pub version: common_enums::ApiVersion,
}
impl Tokenization {
pub fn is_disabled(&self) -> bool {
self.flag == common_enums::TokenizationFlag::Disabled
}
}
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TokenizationNew {
pub id: common_utils::id_type::GlobalTokenId,
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: common_utils::id_type::GlobalCustomerId,
pub locker_id: String,
pub flag: common_enums::TokenizationFlag,
pub version: common_enums::ApiVersion,
}
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct TokenizationResponse {
pub token: String,
pub created_at: PrimitiveDateTime,
pub flag: common_enums::TokenizationFlag,
}
impl From<Tokenization> for TokenizationResponse {
fn from(value: Tokenization) -> Self {
Self {
token: value.id.get_string_repr().to_string(),
created_at: value.created_at,
flag: value.flag,
}
}
}
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum TokenizationUpdate {
DeleteTokenizationRecordUpdate {
flag: Option<common_enums::enums::TokenizationFlag>,
},
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for Tokenization {
type DstType = diesel_models::tokenization::Tokenization;
type NewDstType = diesel_models::tokenization::Tokenization;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::tokenization::Tokenization {
id: self.id,
merchant_id: self.merchant_id,
customer_id: self.customer_id,
locker_id: self.locker_id,
created_at: self.created_at,
updated_at: self.updated_at,
version: self.version,
flag: self.flag,
})
}
async fn convert_back(
_state: &keymanager::KeyManagerState,
item: Self::DstType,
_key: &Secret<Vec<u8>>,
_key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError> {
Ok(Self {
id: item.id,
merchant_id: item.merchant_id,
customer_id: item.customer_id,
locker_id: item.locker_id,
created_at: item.created_at,
updated_at: item.updated_at,
flag: item.flag,
version: item.version,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::tokenization::Tokenization {
id: self.id,
merchant_id: self.merchant_id,
customer_id: self.customer_id,
locker_id: self.locker_id,
created_at: self.created_at,
updated_at: self.updated_at,
version: self.version,
flag: self.flag,
})
}
}
impl From<TokenizationUpdate> for diesel_models::tokenization::TokenizationUpdateInternal {
fn from(value: TokenizationUpdate) -> Self {
let now = date_time::now();
match value {
TokenizationUpdate::DeleteTokenizationRecordUpdate { flag } => Self {
updated_at: now,
flag,
},
}
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/tokenization.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 3,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-8338838494061444050
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_request_types.rs
// Contains: 55 structs, 4 enums
pub mod authentication;
pub mod fraud_check;
pub mod revenue_recovery;
pub mod subscriptions;
pub mod unified_authentication_service;
use api_models::payments::{AdditionalPaymentData, AddressDetails, RequestSurchargeDetails};
use common_types::payments as common_payments_types;
use common_utils::{consts, errors, ext_traits::OptionExt, id_type, pii, types::MinorUnit};
use diesel_models::{enums as storage_enums, types::OrderDetailsWithAmount};
use error_stack::ResultExt;
use masking::Secret;
use serde::Serialize;
use serde_with::serde_as;
use super::payment_method_data::PaymentMethodData;
use crate::{
address,
errors::api_error_response::{ApiErrorResponse, NotImplementedMessage},
mandates,
payment_method_data::ExternalVaultPaymentMethodData,
payments,
router_data::{self, AccessTokenAuthenticationResponse, RouterData},
router_flow_types as flows, router_response_types as response_types,
vault::PaymentMethodVaultingData,
};
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsAuthorizeData {
pub payment_method_data: PaymentMethodData,
/// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount)
/// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately
/// ```text
/// get_original_amount()
/// get_surcharge_amount()
/// get_tax_on_surcharge_amount()
/// get_total_surcharge_amount() // returns surcharge_amount + tax_on_surcharge_amount
/// ```
pub amount: i64,
pub order_tax_amount: Option<MinorUnit>,
pub email: Option<pii::Email>,
pub customer_name: Option<Secret<String>>,
pub currency: storage_enums::Currency,
pub confirm: bool,
pub statement_descriptor_suffix: Option<String>,
pub statement_descriptor: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub router_return_url: Option<String>,
pub webhook_url: Option<String>,
pub complete_authorize_url: Option<String>,
// Mandates
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub off_session: Option<bool>,
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub browser_info: Option<BrowserInformation>,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub order_category: Option<String>,
pub session_token: Option<String>,
pub enrolled_for_3ds: bool,
pub related_transaction_id: Option<String>,
pub payment_experience: Option<storage_enums::PaymentExperience>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub surcharge_details: Option<SurchargeDetails>,
pub customer_id: Option<id_type::CustomerId>,
pub request_incremental_authorization: bool,
pub metadata: Option<serde_json::Value>,
pub authentication_data: Option<AuthenticationData>,
pub request_extended_authorization:
Option<common_types::primitive_wrappers::RequestExtendedAuthorizationBool>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
// New amount for amount frame work
pub minor_amount: MinorUnit,
/// Merchant's identifier for the payment/invoice. This will be sent to the connector
/// if the connector provides support to accept multiple reference ids.
/// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference.
pub merchant_order_reference_id: Option<String>,
pub integrity_object: Option<AuthoriseIntegrityObject>,
pub shipping_cost: Option<MinorUnit>,
pub additional_payment_method_data: Option<AdditionalPaymentData>,
pub merchant_account_id: Option<Secret<String>>,
pub merchant_config_currency: Option<storage_enums::Currency>,
pub connector_testing_data: Option<pii::SecretSerdeValue>,
pub order_id: Option<String>,
pub locale: Option<String>,
pub payment_channel: Option<common_enums::PaymentChannel>,
pub enable_partial_authorization:
Option<common_types::primitive_wrappers::EnablePartialAuthorizationBool>,
pub enable_overcapture: Option<common_types::primitive_wrappers::EnableOvercaptureBool>,
pub is_stored_credential: Option<bool>,
pub mit_category: Option<common_enums::MitCategory>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ExternalVaultProxyPaymentsData {
pub payment_method_data: ExternalVaultPaymentMethodData,
/// total amount (original_amount + surcharge_amount + tax_on_surcharge_amount)
/// If connector supports separate field for surcharge amount, consider using below functions defined on `PaymentsAuthorizeData` to fetch original amount and surcharge amount separately
/// ```text
/// get_original_amount()
/// get_surcharge_amount()
/// get_tax_on_surcharge_amount()
/// get_total_surcharge_amount() // returns surcharge_amount + tax_on_surcharge_amount
/// ```
pub amount: i64,
pub order_tax_amount: Option<MinorUnit>,
pub email: Option<pii::Email>,
pub customer_name: Option<Secret<String>>,
pub currency: storage_enums::Currency,
pub confirm: bool,
pub statement_descriptor_suffix: Option<String>,
pub statement_descriptor: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub router_return_url: Option<String>,
pub webhook_url: Option<String>,
pub complete_authorize_url: Option<String>,
// Mandates
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub off_session: Option<bool>,
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub browser_info: Option<BrowserInformation>,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub order_category: Option<String>,
pub session_token: Option<String>,
pub enrolled_for_3ds: bool,
pub related_transaction_id: Option<String>,
pub payment_experience: Option<storage_enums::PaymentExperience>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub surcharge_details: Option<SurchargeDetails>,
pub customer_id: Option<id_type::CustomerId>,
pub request_incremental_authorization: bool,
pub metadata: Option<serde_json::Value>,
pub authentication_data: Option<AuthenticationData>,
pub request_extended_authorization:
Option<common_types::primitive_wrappers::RequestExtendedAuthorizationBool>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
// New amount for amount frame work
pub minor_amount: MinorUnit,
/// Merchant's identifier for the payment/invoice. This will be sent to the connector
/// if the connector provides support to accept multiple reference ids.
/// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference.
pub merchant_order_reference_id: Option<id_type::PaymentReferenceId>,
pub integrity_object: Option<AuthoriseIntegrityObject>,
pub shipping_cost: Option<MinorUnit>,
pub additional_payment_method_data: Option<AdditionalPaymentData>,
pub merchant_account_id: Option<Secret<String>>,
pub merchant_config_currency: Option<storage_enums::Currency>,
pub connector_testing_data: Option<pii::SecretSerdeValue>,
pub order_id: Option<String>,
}
// Note: Integrity traits for ExternalVaultProxyPaymentsData are not implemented
// as they are not mandatory for this flow. The integrity_check field in RouterData
// will use Ok(()) as default, similar to other flows.
// Implement ConnectorCustomerData conversion for ExternalVaultProxy RouterData
impl
TryFrom<
&RouterData<
flows::ExternalVaultProxy,
ExternalVaultProxyPaymentsData,
response_types::PaymentsResponseData,
>,
> for ConnectorCustomerData
{
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(
data: &RouterData<
flows::ExternalVaultProxy,
ExternalVaultProxyPaymentsData,
response_types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
email: data.request.email.clone(),
payment_method_data: None, // External vault proxy doesn't use regular payment method data
description: None,
phone: None,
name: data.request.customer_name.clone(),
preprocessing_id: data.preprocessing_id.clone(),
split_payments: data.request.split_payments.clone(),
setup_future_usage: data.request.setup_future_usage,
customer_acceptance: data.request.customer_acceptance.clone(),
customer_id: None,
billing_address: None,
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsPostSessionTokensData {
// amount here would include amount, surcharge_amount and shipping_cost
pub amount: MinorUnit,
/// original amount sent by the merchant
pub order_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub capture_method: Option<storage_enums::CaptureMethod>,
/// Merchant's identifier for the payment/invoice. This will be sent to the connector
/// if the connector provides support to accept multiple reference ids.
/// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference.
pub merchant_order_reference_id: Option<String>,
pub shipping_cost: Option<MinorUnit>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub router_return_url: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsUpdateMetadataData {
pub metadata: pii::SecretSerdeValue,
pub connector_transaction_id: String,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct AuthoriseIntegrityObject {
/// Authorise amount
pub amount: MinorUnit,
/// Authorise currency
pub currency: storage_enums::Currency,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct SyncIntegrityObject {
/// Sync amount
pub amount: Option<MinorUnit>,
/// Sync currency
pub currency: Option<storage_enums::Currency>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct PaymentsCaptureData {
pub amount_to_capture: i64,
pub currency: storage_enums::Currency,
pub connector_transaction_id: String,
pub payment_amount: i64,
pub multiple_capture_data: Option<MultipleCaptureRequestData>,
pub connector_meta: Option<serde_json::Value>,
pub browser_info: Option<BrowserInformation>,
pub metadata: Option<serde_json::Value>,
// This metadata is used to store the metadata shared during the payment intent request.
pub capture_method: Option<storage_enums::CaptureMethod>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
// New amount for amount frame work
pub minor_payment_amount: MinorUnit,
pub minor_amount_to_capture: MinorUnit,
pub integrity_object: Option<CaptureIntegrityObject>,
pub webhook_url: Option<String>,
}
#[derive(Debug, Clone, PartialEq, Serialize)]
pub struct CaptureIntegrityObject {
/// capture amount
pub capture_amount: Option<MinorUnit>,
/// capture currency
pub currency: storage_enums::Currency,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct PaymentsIncrementalAuthorizationData {
pub total_amount: i64,
pub additional_amount: i64,
pub currency: storage_enums::Currency,
pub reason: Option<String>,
pub connector_transaction_id: String,
pub connector_meta: Option<serde_json::Value>,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct MultipleCaptureRequestData {
pub capture_sequence: i16,
pub capture_reference: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct AuthorizeSessionTokenData {
pub amount_to_capture: Option<i64>,
pub currency: storage_enums::Currency,
pub connector_transaction_id: String,
pub amount: Option<i64>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ConnectorCustomerData {
pub description: Option<String>,
pub email: Option<pii::Email>,
pub phone: Option<Secret<String>>,
pub name: Option<Secret<String>>,
pub preprocessing_id: Option<String>,
pub payment_method_data: Option<PaymentMethodData>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
// Mandates
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
pub customer_id: Option<id_type::CustomerId>,
pub billing_address: Option<AddressDetails>,
}
impl TryFrom<SetupMandateRequestData> for ConnectorCustomerData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: SetupMandateRequestData) -> Result<Self, Self::Error> {
Ok(Self {
email: data.email,
payment_method_data: Some(data.payment_method_data),
description: None,
phone: None,
name: None,
preprocessing_id: None,
split_payments: None,
setup_future_usage: data.setup_future_usage,
customer_acceptance: data.customer_acceptance,
customer_id: None,
billing_address: None,
})
}
}
impl TryFrom<SetupMandateRequestData> for PaymentsPreProcessingData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: SetupMandateRequestData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: Some(data.payment_method_data),
amount: data.amount,
minor_amount: data.minor_amount,
email: data.email,
currency: Some(data.currency),
payment_method_type: data.payment_method_type,
setup_mandate_details: data.setup_mandate_details,
capture_method: data.capture_method,
order_details: None,
router_return_url: data.router_return_url,
webhook_url: data.webhook_url,
complete_authorize_url: data.complete_authorize_url,
browser_info: data.browser_info,
surcharge_details: None,
connector_transaction_id: None,
mandate_id: data.mandate_id,
related_transaction_id: None,
redirect_response: None,
enrolled_for_3ds: false,
split_payments: None,
metadata: data.metadata,
customer_acceptance: data.customer_acceptance,
setup_future_usage: data.setup_future_usage,
is_stored_credential: data.is_stored_credential,
})
}
}
impl
TryFrom<
&RouterData<flows::Authorize, PaymentsAuthorizeData, response_types::PaymentsResponseData>,
> for ConnectorCustomerData
{
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(
data: &RouterData<
flows::Authorize,
PaymentsAuthorizeData,
response_types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
email: data.request.email.clone(),
payment_method_data: Some(data.request.payment_method_data.clone()),
description: None,
phone: None,
name: data.request.customer_name.clone(),
preprocessing_id: data.preprocessing_id.clone(),
split_payments: data.request.split_payments.clone(),
setup_future_usage: data.request.setup_future_usage,
customer_acceptance: data.request.customer_acceptance.clone(),
customer_id: None,
billing_address: None,
})
}
}
impl TryFrom<&RouterData<flows::Session, PaymentsSessionData, response_types::PaymentsResponseData>>
for ConnectorCustomerData
{
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(
data: &RouterData<
flows::Session,
PaymentsSessionData,
response_types::PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
Ok(Self {
email: data.request.email.clone(),
payment_method_data: None,
description: None,
phone: None,
name: data.request.customer_name.clone(),
preprocessing_id: data.preprocessing_id.clone(),
split_payments: None,
setup_future_usage: None,
customer_acceptance: None,
customer_id: None,
billing_address: None,
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentMethodTokenizationData {
pub payment_method_data: PaymentMethodData,
pub browser_info: Option<BrowserInformation>,
pub currency: storage_enums::Currency,
pub amount: Option<i64>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub mandate_id: Option<api_models::payments::MandateIds>,
}
impl TryFrom<SetupMandateRequestData> for PaymentMethodTokenizationData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: SetupMandateRequestData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data.payment_method_data,
browser_info: None,
currency: data.currency,
amount: data.amount,
split_payments: None,
customer_acceptance: data.customer_acceptance,
setup_future_usage: data.setup_future_usage,
setup_mandate_details: data.setup_mandate_details,
mandate_id: data.mandate_id,
})
}
}
impl<F> From<&RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>>
for PaymentMethodTokenizationData
{
fn from(
data: &RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>,
) -> Self {
Self {
payment_method_data: data.request.payment_method_data.clone(),
browser_info: None,
currency: data.request.currency,
amount: Some(data.request.amount),
split_payments: data.request.split_payments.clone(),
customer_acceptance: data.request.customer_acceptance.clone(),
setup_future_usage: data.request.setup_future_usage,
setup_mandate_details: data.request.setup_mandate_details.clone(),
mandate_id: data.request.mandate_id.clone(),
}
}
}
impl TryFrom<PaymentsAuthorizeData> for PaymentMethodTokenizationData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data.payment_method_data,
browser_info: data.browser_info,
currency: data.currency,
amount: Some(data.amount),
split_payments: data.split_payments.clone(),
customer_acceptance: data.customer_acceptance,
setup_future_usage: data.setup_future_usage,
setup_mandate_details: data.setup_mandate_details,
mandate_id: data.mandate_id,
})
}
}
impl TryFrom<CompleteAuthorizeData> for PaymentMethodTokenizationData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: CompleteAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data
.payment_method_data
.get_required_value("payment_method_data")
.change_context(ApiErrorResponse::MissingRequiredField {
field_name: "payment_method_data",
})?,
browser_info: data.browser_info,
currency: data.currency,
amount: Some(data.amount),
split_payments: None,
customer_acceptance: data.customer_acceptance,
setup_future_usage: data.setup_future_usage,
setup_mandate_details: data.setup_mandate_details,
mandate_id: data.mandate_id,
})
}
}
impl TryFrom<ExternalVaultProxyPaymentsData> for PaymentMethodTokenizationData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(_data: ExternalVaultProxyPaymentsData) -> Result<Self, Self::Error> {
// TODO: External vault proxy payments should not use regular payment method tokenization
// This needs to be implemented separately for external vault flows
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason(
"External vault proxy tokenization not implemented".to_string(),
),
}
.into())
}
}
#[derive(Debug, Clone, Serialize)]
pub struct CreateOrderRequestData {
pub minor_amount: MinorUnit,
pub currency: storage_enums::Currency,
}
impl TryFrom<PaymentsAuthorizeData> for CreateOrderRequestData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
minor_amount: data.minor_amount,
currency: data.currency,
})
}
}
impl TryFrom<ExternalVaultProxyPaymentsData> for CreateOrderRequestData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: ExternalVaultProxyPaymentsData) -> Result<Self, Self::Error> {
Ok(Self {
minor_amount: data.minor_amount,
currency: data.currency,
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsPreProcessingData {
pub payment_method_data: Option<PaymentMethodData>,
pub amount: Option<i64>,
pub email: Option<pii::Email>,
pub currency: Option<storage_enums::Currency>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub router_return_url: Option<String>,
pub webhook_url: Option<String>,
pub complete_authorize_url: Option<String>,
pub surcharge_details: Option<SurchargeDetails>,
pub browser_info: Option<BrowserInformation>,
pub connector_transaction_id: Option<String>,
pub enrolled_for_3ds: bool,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub related_transaction_id: Option<String>,
pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
pub metadata: Option<Secret<serde_json::Value>>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
// New amount for amount frame work
pub minor_amount: Option<MinorUnit>,
pub is_stored_credential: Option<bool>,
}
#[derive(Debug, Clone, Serialize)]
pub struct GiftCardBalanceCheckRequestData {
pub payment_method_data: PaymentMethodData,
pub currency: Option<storage_enums::Currency>,
pub minor_amount: Option<MinorUnit>,
}
impl TryFrom<PaymentsAuthorizeData> for PaymentsPreProcessingData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: Some(data.payment_method_data),
amount: Some(data.amount),
minor_amount: Some(data.minor_amount),
email: data.email,
currency: Some(data.currency),
payment_method_type: data.payment_method_type,
setup_mandate_details: data.setup_mandate_details,
capture_method: data.capture_method,
order_details: data.order_details,
router_return_url: data.router_return_url,
webhook_url: data.webhook_url,
complete_authorize_url: data.complete_authorize_url,
browser_info: data.browser_info,
surcharge_details: data.surcharge_details,
connector_transaction_id: None,
mandate_id: data.mandate_id,
related_transaction_id: data.related_transaction_id,
redirect_response: None,
enrolled_for_3ds: data.enrolled_for_3ds,
split_payments: data.split_payments,
metadata: data.metadata.map(Secret::new),
customer_acceptance: data.customer_acceptance,
setup_future_usage: data.setup_future_usage,
is_stored_credential: data.is_stored_credential,
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsPreAuthenticateData {
pub payment_method_data: Option<PaymentMethodData>,
pub amount: Option<i64>,
pub email: Option<pii::Email>,
pub currency: Option<storage_enums::Currency>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub router_return_url: Option<String>,
pub complete_authorize_url: Option<String>,
pub browser_info: Option<BrowserInformation>,
pub connector_transaction_id: Option<String>,
pub enrolled_for_3ds: bool,
pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
// New amount for amount frame work
pub minor_amount: Option<MinorUnit>,
}
impl TryFrom<PaymentsAuthorizeData> for PaymentsPreAuthenticateData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: Some(data.payment_method_data),
amount: Some(data.amount),
minor_amount: Some(data.minor_amount),
email: data.email,
currency: Some(data.currency),
payment_method_type: data.payment_method_type,
router_return_url: data.router_return_url,
complete_authorize_url: data.complete_authorize_url,
browser_info: data.browser_info,
connector_transaction_id: None,
redirect_response: None,
enrolled_for_3ds: data.enrolled_for_3ds,
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsAuthenticateData {
pub payment_method_data: Option<PaymentMethodData>,
pub amount: Option<i64>,
pub email: Option<pii::Email>,
pub currency: Option<storage_enums::Currency>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub router_return_url: Option<String>,
pub complete_authorize_url: Option<String>,
pub browser_info: Option<BrowserInformation>,
pub connector_transaction_id: Option<String>,
pub enrolled_for_3ds: bool,
pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
// New amount for amount frame work
pub minor_amount: Option<MinorUnit>,
}
impl TryFrom<PaymentsAuthorizeData> for PaymentsAuthenticateData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: Some(data.payment_method_data),
amount: Some(data.amount),
minor_amount: Some(data.minor_amount),
email: data.email,
currency: Some(data.currency),
payment_method_type: data.payment_method_type,
router_return_url: data.router_return_url,
complete_authorize_url: data.complete_authorize_url,
browser_info: data.browser_info,
connector_transaction_id: None,
redirect_response: None,
enrolled_for_3ds: data.enrolled_for_3ds,
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsPostAuthenticateData {
pub payment_method_data: Option<PaymentMethodData>,
pub amount: Option<i64>,
pub email: Option<pii::Email>,
pub currency: Option<storage_enums::Currency>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub router_return_url: Option<String>,
pub complete_authorize_url: Option<String>,
pub browser_info: Option<BrowserInformation>,
pub connector_transaction_id: Option<String>,
pub enrolled_for_3ds: bool,
pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
// New amount for amount frame work
pub minor_amount: Option<MinorUnit>,
}
impl TryFrom<PaymentsAuthorizeData> for PaymentsPostAuthenticateData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: PaymentsAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: Some(data.payment_method_data),
amount: Some(data.amount),
minor_amount: Some(data.minor_amount),
email: data.email,
currency: Some(data.currency),
payment_method_type: data.payment_method_type,
router_return_url: data.router_return_url,
complete_authorize_url: data.complete_authorize_url,
browser_info: data.browser_info,
connector_transaction_id: None,
redirect_response: None,
enrolled_for_3ds: data.enrolled_for_3ds,
})
}
}
impl TryFrom<CompleteAuthorizeData> for PaymentsPreProcessingData {
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(data: CompleteAuthorizeData) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data.payment_method_data,
amount: Some(data.amount),
minor_amount: Some(data.minor_amount),
email: data.email,
currency: Some(data.currency),
payment_method_type: None,
setup_mandate_details: data.setup_mandate_details,
capture_method: data.capture_method,
order_details: None,
router_return_url: None,
webhook_url: None,
complete_authorize_url: data.complete_authorize_url,
browser_info: data.browser_info,
surcharge_details: None,
connector_transaction_id: data.connector_transaction_id,
mandate_id: data.mandate_id,
related_transaction_id: None,
redirect_response: data.redirect_response,
split_payments: None,
enrolled_for_3ds: true,
metadata: data.connector_meta.map(Secret::new),
customer_acceptance: data.customer_acceptance,
setup_future_usage: data.setup_future_usage,
is_stored_credential: data.is_stored_credential,
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsPostProcessingData {
pub payment_method_data: PaymentMethodData,
pub customer_id: Option<id_type::CustomerId>,
pub connector_transaction_id: Option<String>,
pub country: Option<common_enums::CountryAlpha2>,
pub connector_meta_data: Option<pii::SecretSerdeValue>,
pub header_payload: Option<payments::HeaderPayload>,
}
impl<F> TryFrom<RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>>
for PaymentsPostProcessingData
{
type Error = error_stack::Report<ApiErrorResponse>;
fn try_from(
data: RouterData<F, PaymentsAuthorizeData, response_types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
payment_method_data: data.request.payment_method_data,
connector_transaction_id: match data.response {
Ok(response_types::PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(id),
..
}) => Some(id.clone()),
_ => None,
},
customer_id: data.request.customer_id,
country: data
.address
.get_payment_billing()
.and_then(|bl| bl.address.as_ref())
.and_then(|address| address.country),
connector_meta_data: data.connector_meta_data.clone(),
header_payload: data.header_payload,
})
}
}
#[derive(Debug, Clone, Serialize)]
pub struct CompleteAuthorizeData {
pub payment_method_data: Option<PaymentMethodData>,
pub amount: i64,
pub email: Option<pii::Email>,
pub currency: storage_enums::Currency,
pub confirm: bool,
pub statement_descriptor_suffix: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
// Mandates
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub off_session: Option<bool>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub redirect_response: Option<CompleteAuthorizeRedirectResponse>,
pub browser_info: Option<BrowserInformation>,
pub connector_transaction_id: Option<String>,
pub connector_meta: Option<serde_json::Value>,
pub complete_authorize_url: Option<String>,
pub metadata: Option<serde_json::Value>,
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
// New amount for amount frame work
pub minor_amount: MinorUnit,
pub merchant_account_id: Option<Secret<String>>,
pub merchant_config_currency: Option<storage_enums::Currency>,
pub threeds_method_comp_ind: Option<api_models::payments::ThreeDsCompletionIndicator>,
pub is_stored_credential: Option<bool>,
}
#[derive(Debug, Clone, Serialize)]
pub struct CompleteAuthorizeRedirectResponse {
pub params: Option<Secret<String>>,
pub payload: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Default, Clone, Serialize)]
pub struct PaymentsSyncData {
//TODO : add fields based on the connector requirements
pub connector_transaction_id: ResponseId,
pub encoded_data: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub connector_meta: Option<serde_json::Value>,
pub sync_type: SyncRequestType,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub currency: storage_enums::Currency,
pub payment_experience: Option<common_enums::PaymentExperience>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
pub amount: MinorUnit,
pub integrity_object: Option<SyncIntegrityObject>,
pub connector_reference_id: Option<String>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
}
#[derive(Debug, Default, Clone, Serialize)]
pub enum SyncRequestType {
MultipleCaptureSync(Vec<String>),
#[default]
SinglePaymentSync,
}
#[derive(Debug, Default, Clone, Serialize)]
pub struct PaymentsCancelData {
pub amount: Option<i64>,
pub currency: Option<storage_enums::Currency>,
pub connector_transaction_id: String,
pub cancellation_reason: Option<String>,
pub connector_meta: Option<serde_json::Value>,
pub browser_info: Option<BrowserInformation>,
pub metadata: Option<serde_json::Value>,
// This metadata is used to store the metadata shared during the payment intent request.
// minor amount data for amount framework
pub minor_amount: Option<MinorUnit>,
pub webhook_url: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
}
#[derive(Debug, Default, Clone, Serialize)]
pub struct PaymentsCancelPostCaptureData {
pub currency: Option<storage_enums::Currency>,
pub connector_transaction_id: String,
pub cancellation_reason: Option<String>,
pub connector_meta: Option<serde_json::Value>,
// minor amount data for amount framework
pub minor_amount: Option<MinorUnit>,
}
#[derive(Debug, Default, Clone, Serialize)]
pub struct PaymentsExtendAuthorizationData {
pub minor_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub connector_transaction_id: String,
pub connector_meta: Option<serde_json::Value>,
}
#[derive(Debug, Default, Clone)]
pub struct PaymentsRejectData {
pub amount: Option<i64>,
pub currency: Option<storage_enums::Currency>,
}
#[derive(Debug, Default, Clone)]
pub struct PaymentsApproveData {
pub amount: Option<i64>,
pub currency: Option<storage_enums::Currency>,
}
#[derive(Clone, Debug, Default, Serialize, serde::Deserialize)]
pub struct BrowserInformation {
pub color_depth: Option<u8>,
pub java_enabled: Option<bool>,
pub java_script_enabled: Option<bool>,
pub language: Option<String>,
pub screen_height: Option<u32>,
pub screen_width: Option<u32>,
pub time_zone: Option<i32>,
pub ip_address: Option<std::net::IpAddr>,
pub accept_header: Option<String>,
pub user_agent: Option<String>,
pub os_type: Option<String>,
pub os_version: Option<String>,
pub device_model: Option<String>,
pub accept_language: Option<String>,
pub referer: Option<String>,
}
#[cfg(feature = "v2")]
impl From<common_utils::types::BrowserInformation> for BrowserInformation {
fn from(value: common_utils::types::BrowserInformation) -> Self {
Self {
color_depth: value.color_depth,
java_enabled: value.java_enabled,
java_script_enabled: value.java_script_enabled,
language: value.language,
screen_height: value.screen_height,
screen_width: value.screen_width,
time_zone: value.time_zone,
ip_address: value.ip_address,
accept_header: value.accept_header,
user_agent: value.user_agent,
os_type: value.os_type,
os_version: value.os_version,
device_model: value.device_model,
accept_language: value.accept_language,
referer: value.referer,
}
}
}
#[cfg(feature = "v1")]
impl From<api_models::payments::BrowserInformation> for BrowserInformation {
fn from(value: api_models::payments::BrowserInformation) -> Self {
Self {
color_depth: value.color_depth,
java_enabled: value.java_enabled,
java_script_enabled: value.java_script_enabled,
language: value.language,
screen_height: value.screen_height,
screen_width: value.screen_width,
time_zone: value.time_zone,
ip_address: value.ip_address,
accept_header: value.accept_header,
user_agent: value.user_agent,
os_type: value.os_type,
os_version: value.os_version,
device_model: value.device_model,
accept_language: value.accept_language,
referer: value.referer,
}
}
}
#[derive(Debug, Clone, Default, Serialize)]
pub enum ResponseId {
ConnectorTransactionId(String),
EncodedData(String),
#[default]
NoResponseId,
}
impl ResponseId {
pub fn get_connector_transaction_id(
&self,
) -> errors::CustomResult<String, errors::ValidationError> {
match self {
Self::ConnectorTransactionId(txn_id) => Ok(txn_id.to_string()),
_ => Err(errors::ValidationError::IncorrectValueProvided {
field_name: "connector_transaction_id",
})
.attach_printable("Expected connector transaction ID not found"),
}
}
}
#[derive(Clone, Debug, serde::Deserialize, Serialize)]
pub struct SurchargeDetails {
/// original_amount
pub original_amount: MinorUnit,
/// surcharge value
pub surcharge: common_utils::types::Surcharge,
/// tax on surcharge value
pub tax_on_surcharge:
Option<common_utils::types::Percentage<{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH }>>,
/// surcharge amount for this payment
pub surcharge_amount: MinorUnit,
/// tax on surcharge amount for this payment
pub tax_on_surcharge_amount: MinorUnit,
}
impl SurchargeDetails {
pub fn get_total_surcharge_amount(&self) -> MinorUnit {
self.surcharge_amount + self.tax_on_surcharge_amount
}
}
#[cfg(feature = "v1")]
impl
From<(
&RequestSurchargeDetails,
&payments::payment_attempt::PaymentAttempt,
)> for SurchargeDetails
{
fn from(
(request_surcharge_details, payment_attempt): (
&RequestSurchargeDetails,
&payments::payment_attempt::PaymentAttempt,
),
) -> Self {
let surcharge_amount = request_surcharge_details.surcharge_amount;
let tax_on_surcharge_amount = request_surcharge_details.tax_amount.unwrap_or_default();
Self {
original_amount: payment_attempt.net_amount.get_order_amount(),
surcharge: common_utils::types::Surcharge::Fixed(
request_surcharge_details.surcharge_amount,
),
tax_on_surcharge: None,
surcharge_amount,
tax_on_surcharge_amount,
}
}
}
#[cfg(feature = "v2")]
impl
From<(
&RequestSurchargeDetails,
&payments::payment_attempt::PaymentAttempt,
)> for SurchargeDetails
{
fn from(
(_request_surcharge_details, _payment_attempt): (
&RequestSurchargeDetails,
&payments::payment_attempt::PaymentAttempt,
),
) -> Self {
todo!()
}
}
#[derive(Debug, Clone, Serialize)]
pub struct AuthenticationData {
pub eci: Option<String>,
pub cavv: Secret<String>,
pub threeds_server_transaction_id: Option<String>,
pub message_version: Option<common_utils::types::SemanticVersion>,
pub ds_trans_id: Option<String>,
pub created_at: time::PrimitiveDateTime,
pub challenge_code: Option<String>,
pub challenge_cancel: Option<String>,
pub challenge_code_reason: Option<String>,
pub message_extension: Option<pii::SecretSerdeValue>,
pub acs_trans_id: Option<String>,
pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,
}
#[derive(Debug, Clone)]
pub struct RefundsData {
pub refund_id: String,
pub connector_transaction_id: String,
pub connector_refund_id: Option<String>,
pub currency: storage_enums::Currency,
/// Amount for the payment against which this refund is issued
pub payment_amount: i64,
pub reason: Option<String>,
pub webhook_url: Option<String>,
/// Amount to be refunded
pub refund_amount: i64,
/// Arbitrary metadata required for refund
pub connector_metadata: Option<serde_json::Value>,
/// refund method
pub refund_connector_metadata: Option<pii::SecretSerdeValue>,
pub browser_info: Option<BrowserInformation>,
/// Charges associated with the payment
pub split_refunds: Option<SplitRefundsRequest>,
// New amount for amount frame work
pub minor_payment_amount: MinorUnit,
pub minor_refund_amount: MinorUnit,
pub integrity_object: Option<RefundIntegrityObject>,
pub refund_status: storage_enums::RefundStatus,
pub merchant_account_id: Option<Secret<String>>,
pub merchant_config_currency: Option<storage_enums::Currency>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub additional_payment_method_data: Option<AdditionalPaymentData>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct RefundIntegrityObject {
/// refund currency
pub currency: storage_enums::Currency,
/// refund amount
pub refund_amount: MinorUnit,
}
#[derive(Debug, serde::Deserialize, Clone)]
pub enum SplitRefundsRequest {
StripeSplitRefund(StripeSplitRefund),
AdyenSplitRefund(common_types::domain::AdyenSplitData),
XenditSplitRefund(common_types::domain::XenditSplitSubMerchantData),
}
#[derive(Debug, serde::Deserialize, Clone)]
pub struct StripeSplitRefund {
pub charge_id: String,
pub transfer_account_id: String,
pub charge_type: api_models::enums::PaymentChargeType,
pub options: ChargeRefundsOptions,
}
#[derive(Debug, serde::Deserialize, Clone)]
pub struct ChargeRefunds {
pub charge_id: String,
pub transfer_account_id: String,
pub charge_type: api_models::enums::PaymentChargeType,
pub options: ChargeRefundsOptions,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, Serialize)]
pub enum ChargeRefundsOptions {
Destination(DestinationChargeRefund),
Direct(DirectChargeRefund),
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, Serialize)]
pub struct DirectChargeRefund {
pub revert_platform_fee: bool,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, Serialize)]
pub struct DestinationChargeRefund {
pub revert_platform_fee: bool,
pub revert_transfer: bool,
}
#[derive(Debug, Clone)]
pub struct AccessTokenAuthenticationRequestData {
pub auth_creds: router_data::ConnectorAuthType,
}
impl TryFrom<router_data::ConnectorAuthType> for AccessTokenAuthenticationRequestData {
type Error = ApiErrorResponse;
fn try_from(connector_auth: router_data::ConnectorAuthType) -> Result<Self, Self::Error> {
Ok(Self {
auth_creds: connector_auth,
})
}
}
#[derive(Debug, Clone)]
pub struct AccessTokenRequestData {
pub app_id: Secret<String>,
pub id: Option<Secret<String>>,
pub authentication_token: Option<AccessTokenAuthenticationResponse>,
// Add more keys if required
}
// This is for backward compatibility
impl TryFrom<router_data::ConnectorAuthType> for AccessTokenRequestData {
type Error = ApiErrorResponse;
fn try_from(connector_auth: router_data::ConnectorAuthType) -> Result<Self, Self::Error> {
match connector_auth {
router_data::ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
app_id: api_key,
id: None,
authentication_token: None,
}),
router_data::ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
app_id: api_key,
id: Some(key1),
authentication_token: None,
}),
router_data::ConnectorAuthType::SignatureKey { api_key, key1, .. } => Ok(Self {
app_id: api_key,
id: Some(key1),
authentication_token: None,
}),
router_data::ConnectorAuthType::MultiAuthKey { api_key, key1, .. } => Ok(Self {
app_id: api_key,
id: Some(key1),
authentication_token: None,
}),
_ => Err(ApiErrorResponse::InvalidDataValue {
field_name: "connector_account_details",
}),
}
}
}
impl
TryFrom<(
router_data::ConnectorAuthType,
Option<AccessTokenAuthenticationResponse>,
)> for AccessTokenRequestData
{
type Error = ApiErrorResponse;
fn try_from(
(connector_auth, authentication_token): (
router_data::ConnectorAuthType,
Option<AccessTokenAuthenticationResponse>,
),
) -> Result<Self, Self::Error> {
let mut access_token_request_data = Self::try_from(connector_auth)?;
access_token_request_data.authentication_token = authentication_token;
Ok(access_token_request_data)
}
}
#[derive(Default, Debug, Clone)]
pub struct AcceptDisputeRequestData {
pub dispute_id: String,
pub connector_dispute_id: String,
pub dispute_status: storage_enums::DisputeStatus,
}
#[derive(Default, Debug, Clone)]
pub struct DefendDisputeRequestData {
pub dispute_id: String,
pub connector_dispute_id: String,
}
#[derive(Default, Debug, Clone)]
pub struct SubmitEvidenceRequestData {
pub dispute_id: String,
pub dispute_status: storage_enums::DisputeStatus,
pub connector_dispute_id: String,
pub access_activity_log: Option<String>,
pub billing_address: Option<String>,
//cancellation policy
pub cancellation_policy: Option<Vec<u8>>,
pub cancellation_policy_file_type: Option<String>,
pub cancellation_policy_provider_file_id: Option<String>,
pub cancellation_policy_disclosure: Option<String>,
pub cancellation_rebuttal: Option<String>,
//customer communication
pub customer_communication: Option<Vec<u8>>,
pub customer_communication_file_type: Option<String>,
pub customer_communication_provider_file_id: Option<String>,
pub customer_email_address: Option<String>,
pub customer_name: Option<String>,
pub customer_purchase_ip: Option<String>,
//customer signature
pub customer_signature: Option<Vec<u8>>,
pub customer_signature_file_type: Option<String>,
pub customer_signature_provider_file_id: Option<String>,
//product description
pub product_description: Option<String>,
//receipts
pub receipt: Option<Vec<u8>>,
pub receipt_file_type: Option<String>,
pub receipt_provider_file_id: Option<String>,
//refund policy
pub refund_policy: Option<Vec<u8>>,
pub refund_policy_file_type: Option<String>,
pub refund_policy_provider_file_id: Option<String>,
pub refund_policy_disclosure: Option<String>,
pub refund_refusal_explanation: Option<String>,
//service docs
pub service_date: Option<String>,
pub service_documentation: Option<Vec<u8>>,
pub service_documentation_file_type: Option<String>,
pub service_documentation_provider_file_id: Option<String>,
//shipping details docs
pub shipping_address: Option<String>,
pub shipping_carrier: Option<String>,
pub shipping_date: Option<String>,
pub shipping_documentation: Option<Vec<u8>>,
pub shipping_documentation_file_type: Option<String>,
pub shipping_documentation_provider_file_id: Option<String>,
pub shipping_tracking_number: Option<String>,
//invoice details
pub invoice_showing_distinct_transactions: Option<Vec<u8>>,
pub invoice_showing_distinct_transactions_file_type: Option<String>,
pub invoice_showing_distinct_transactions_provider_file_id: Option<String>,
//subscription details
pub recurring_transaction_agreement: Option<Vec<u8>>,
pub recurring_transaction_agreement_file_type: Option<String>,
pub recurring_transaction_agreement_provider_file_id: Option<String>,
//uncategorized details
pub uncategorized_file: Option<Vec<u8>>,
pub uncategorized_file_type: Option<String>,
pub uncategorized_file_provider_file_id: Option<String>,
pub uncategorized_text: Option<String>,
}
#[derive(Debug, Serialize, Clone)]
pub struct FetchDisputesRequestData {
pub created_from: time::PrimitiveDateTime,
pub created_till: time::PrimitiveDateTime,
}
#[derive(Clone, Debug)]
pub struct RetrieveFileRequestData {
pub provider_file_id: String,
pub connector_dispute_id: Option<String>,
}
#[serde_as]
#[derive(Clone, Debug, Serialize)]
pub struct UploadFileRequestData {
pub file_key: String,
#[serde(skip)]
pub file: Vec<u8>,
#[serde_as(as = "serde_with::DisplayFromStr")]
pub file_type: mime::Mime,
pub file_size: i32,
pub dispute_id: String,
pub connector_dispute_id: String,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone)]
pub struct PayoutsData {
pub payout_id: id_type::PayoutId,
pub amount: i64,
pub connector_payout_id: Option<String>,
pub destination_currency: storage_enums::Currency,
pub source_currency: storage_enums::Currency,
pub payout_type: Option<storage_enums::PayoutType>,
pub entity_type: storage_enums::PayoutEntityType,
pub customer_details: Option<CustomerDetails>,
pub vendor_details: Option<api_models::payouts::PayoutVendorAccountDetails>,
// New minor amount for amount framework
pub minor_amount: MinorUnit,
pub priority: Option<storage_enums::PayoutSendPriority>,
pub connector_transfer_method_id: Option<String>,
pub webhook_url: Option<String>,
pub browser_info: Option<BrowserInformation>,
pub payout_connector_metadata: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Default, Clone)]
pub struct CustomerDetails {
pub customer_id: Option<id_type::CustomerId>,
pub name: Option<Secret<String, masking::WithType>>,
pub email: Option<pii::Email>,
pub phone: Option<Secret<String, masking::WithType>>,
pub phone_country_code: Option<String>,
pub tax_registration_id: Option<Secret<String, masking::WithType>>,
}
#[derive(Debug, Clone)]
pub struct VerifyWebhookSourceRequestData {
pub webhook_headers: actix_web::http::header::HeaderMap,
pub webhook_body: Vec<u8>,
pub merchant_secret: api_models::webhooks::ConnectorWebhookSecrets,
}
#[derive(Debug, Clone)]
pub struct MandateRevokeRequestData {
pub mandate_id: String,
pub connector_mandate_id: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct PaymentsSessionData {
pub amount: i64,
pub currency: common_enums::Currency,
pub country: Option<common_enums::CountryAlpha2>,
pub surcharge_details: Option<SurchargeDetails>,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub email: Option<pii::Email>,
// Minor Unit amount for amount frame work
pub minor_amount: MinorUnit,
pub apple_pay_recurring_details: Option<api_models::payments::ApplePayRecurringPaymentRequest>,
pub customer_name: Option<Secret<String>>,
pub order_tax_amount: Option<MinorUnit>,
pub shipping_cost: Option<MinorUnit>,
pub metadata: Option<Secret<serde_json::Value>>,
/// The specific payment method type for which the session token is being generated
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub payment_method: Option<common_enums::PaymentMethod>,
}
#[derive(Debug, Clone, Default)]
pub struct PaymentsTaxCalculationData {
pub amount: MinorUnit,
pub currency: storage_enums::Currency,
pub shipping_cost: Option<MinorUnit>,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub shipping_address: address::Address,
}
#[derive(Debug, Clone, Default, Serialize)]
pub struct SdkPaymentsSessionUpdateData {
pub order_tax_amount: MinorUnit,
// amount here would include amount, surcharge_amount, order_tax_amount and shipping_cost
pub amount: MinorUnit,
/// original amount sent by the merchant
pub order_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub session_id: Option<String>,
pub shipping_cost: Option<MinorUnit>,
}
#[derive(Debug, Clone, Serialize)]
pub struct SetupMandateRequestData {
pub currency: storage_enums::Currency,
pub payment_method_data: PaymentMethodData,
pub amount: Option<i64>,
pub confirm: bool,
pub statement_descriptor_suffix: Option<String>,
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
pub mandate_id: Option<api_models::payments::MandateIds>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub off_session: Option<bool>,
pub setup_mandate_details: Option<mandates::MandateData>,
pub router_return_url: Option<String>,
pub webhook_url: Option<String>,
pub browser_info: Option<BrowserInformation>,
pub email: Option<pii::Email>,
pub customer_name: Option<Secret<String>>,
pub return_url: Option<String>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub request_incremental_authorization: bool,
pub metadata: Option<pii::SecretSerdeValue>,
pub complete_authorize_url: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
pub enrolled_for_3ds: bool,
pub related_transaction_id: Option<String>,
// MinorUnit for amount framework
pub minor_amount: Option<MinorUnit>,
pub shipping_cost: Option<MinorUnit>,
pub connector_testing_data: Option<pii::SecretSerdeValue>,
pub customer_id: Option<id_type::CustomerId>,
pub enable_partial_authorization:
Option<common_types::primitive_wrappers::EnablePartialAuthorizationBool>,
pub payment_channel: Option<storage_enums::PaymentChannel>,
pub is_stored_credential: Option<bool>,
}
#[derive(Debug, Clone)]
pub struct VaultRequestData {
pub payment_method_vaulting_data: Option<PaymentMethodVaultingData>,
pub connector_vault_id: Option<String>,
pub connector_customer_id: Option<String>,
}
#[derive(Debug, Serialize, Clone)]
pub struct DisputeSyncData {
pub dispute_id: String,
pub connector_dispute_id: String,
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_request_types.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 4,
"num_structs": 55,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-3032691075826909652
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/callback_mapper.rs
// Contains: 1 structs, 0 enums
use common_enums::enums as common_enums;
use common_types::callback_mapper::CallbackMapperData;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CallbackMapper {
pub id: String,
pub callback_mapper_id_type: common_enums::CallbackMapperIdType,
pub data: CallbackMapperData,
pub created_at: time::PrimitiveDateTime,
pub last_modified_at: time::PrimitiveDateTime,
}
impl CallbackMapper {
pub fn new(
id: String,
callback_mapper_id_type: common_enums::CallbackMapperIdType,
data: CallbackMapperData,
created_at: time::PrimitiveDateTime,
last_modified_at: time::PrimitiveDateTime,
) -> Self {
Self {
id,
callback_mapper_id_type,
data,
created_at,
last_modified_at,
}
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/callback_mapper.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-6621167028748419870
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/payment_methods.rs
// Contains: 6 structs, 1 enums
#[cfg(feature = "v2")]
use api_models::payment_methods::PaymentMethodsData;
use api_models::{customers, payment_methods, payments};
// specific imports because of using the macro
use common_enums::enums::MerchantStorageScheme;
#[cfg(feature = "v1")]
use common_utils::crypto::OptionalEncryptableValue;
#[cfg(feature = "v2")]
use common_utils::{crypto::Encryptable, encryption::Encryption, types::keymanager::ToEncryptable};
use common_utils::{
errors::{CustomResult, ParsingError, ValidationError},
id_type, pii, type_name,
types::keymanager,
};
pub use diesel_models::{enums as storage_enums, PaymentMethodUpdate};
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use masking::ExposeInterface;
use masking::{PeekInterface, Secret};
#[cfg(feature = "v1")]
use router_env::logger;
#[cfg(feature = "v2")]
use rustc_hash::FxHashMap;
#[cfg(feature = "v2")]
use serde_json::Value;
use time::PrimitiveDateTime;
#[cfg(feature = "v2")]
use crate::address::Address;
#[cfg(feature = "v1")]
use crate::type_encryption::AsyncLift;
use crate::{
mandates::{self, CommonMandateReference},
merchant_key_store::MerchantKeyStore,
payment_method_data as domain_payment_method_data,
transformers::ForeignTryFrom,
type_encryption::{crypto_operation, CryptoOperation},
};
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct VaultId(String);
impl VaultId {
pub fn get_string_repr(&self) -> &String {
&self.0
}
pub fn generate(id: String) -> Self {
Self(id)
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub struct PaymentMethod {
pub customer_id: id_type::CustomerId,
pub merchant_id: id_type::MerchantId,
pub payment_method_id: String,
pub accepted_currency: Option<Vec<storage_enums::Currency>>,
pub scheme: Option<String>,
pub token: Option<String>,
pub cardholder_name: Option<Secret<String>>,
pub issuer_name: Option<String>,
pub issuer_country: Option<String>,
pub payer_country: Option<Vec<String>>,
pub is_stored: Option<bool>,
pub swift_code: Option<String>,
pub direct_debit_token: Option<String>,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_issuer: Option<String>,
pub payment_method_issuer_code: Option<storage_enums::PaymentMethodIssuerCode>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_data: OptionalEncryptableValue,
pub locker_id: Option<String>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<serde_json::Value>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
pub payment_method_billing_address: OptionalEncryptableValue,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
pub network_token_payment_method_data: OptionalEncryptableValue,
pub vault_source_details: PaymentMethodVaultSourceDetails,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct PaymentMethod {
/// The identifier for the payment method. Using this recurring payments can be made
pub id: id_type::GlobalPaymentMethodId,
/// The customer id against which the payment method is saved
pub customer_id: id_type::GlobalCustomerId,
/// The merchant id against which the payment method is saved
pub merchant_id: id_type::MerchantId,
/// The merchant connector account id of the external vault where the payment method is saved
pub external_vault_source: Option<id_type::MerchantConnectorAccountId>,
pub created_at: PrimitiveDateTime,
pub last_modified: PrimitiveDateTime,
pub payment_method_type: Option<storage_enums::PaymentMethod>,
pub payment_method_subtype: Option<storage_enums::PaymentMethodType>,
#[encrypt(ty = Value)]
pub payment_method_data: Option<Encryptable<PaymentMethodsData>>,
pub locker_id: Option<VaultId>,
pub last_used_at: PrimitiveDateTime,
pub connector_mandate_details: Option<CommonMandateReference>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub status: storage_enums::PaymentMethodStatus,
pub network_transaction_id: Option<String>,
pub client_secret: Option<String>,
#[encrypt(ty = Value)]
pub payment_method_billing_address: Option<Encryptable<Address>>,
pub updated_by: Option<String>,
pub locker_fingerprint_id: Option<String>,
pub version: common_enums::ApiVersion,
pub network_token_requestor_reference_id: Option<String>,
pub network_token_locker_id: Option<String>,
#[encrypt(ty = Value)]
pub network_token_payment_method_data:
Option<Encryptable<domain_payment_method_data::PaymentMethodsData>>,
#[encrypt(ty = Value)]
pub external_vault_token_data:
Option<Encryptable<api_models::payment_methods::ExternalVaultTokenData>>,
pub vault_type: Option<storage_enums::VaultType>,
}
impl PaymentMethod {
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &String {
&self.payment_method_id
}
#[cfg(feature = "v1")]
pub fn get_payment_methods_data(
&self,
) -> Option<domain_payment_method_data::PaymentMethodsData> {
self.payment_method_data
.clone()
.map(|value| value.into_inner().expose())
.and_then(|value| {
serde_json::from_value::<domain_payment_method_data::PaymentMethodsData>(value)
.map_err(|error| {
logger::warn!(
?error,
"Failed to parse payment method data in payment method info"
);
})
.ok()
})
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &id_type::GlobalPaymentMethodId {
&self.id
}
#[cfg(feature = "v1")]
pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethod> {
self.payment_method
}
#[cfg(feature = "v2")]
pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethod> {
self.payment_method_type
}
#[cfg(feature = "v1")]
pub fn get_payment_method_subtype(&self) -> Option<storage_enums::PaymentMethodType> {
self.payment_method_type
}
#[cfg(feature = "v2")]
pub fn get_payment_method_subtype(&self) -> Option<storage_enums::PaymentMethodType> {
self.payment_method_subtype
}
#[cfg(feature = "v1")]
pub fn get_common_mandate_reference(&self) -> Result<CommonMandateReference, ParsingError> {
let payments_data = self
.connector_mandate_details
.clone()
.map(|mut mandate_details| {
mandate_details
.as_object_mut()
.map(|obj| obj.remove("payouts"));
serde_json::from_value::<mandates::PaymentsMandateReference>(mandate_details)
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payments data: {:?}", err);
})
})
.transpose()
.map_err(|err| {
router_env::logger::error!("Failed to parse payments data: {:?}", err);
ParsingError::StructParseFailure("Failed to parse payments data")
})?;
let payouts_data = self
.connector_mandate_details
.clone()
.map(|mandate_details| {
serde_json::from_value::<Option<CommonMandateReference>>(mandate_details)
.inspect_err(|err| {
router_env::logger::error!("Failed to parse payouts data: {:?}", err);
})
.map(|optional_common_mandate_details| {
optional_common_mandate_details
.and_then(|common_mandate_details| common_mandate_details.payouts)
})
})
.transpose()
.map_err(|err| {
router_env::logger::error!("Failed to parse payouts data: {:?}", err);
ParsingError::StructParseFailure("Failed to parse payouts data")
})?
.flatten();
Ok(CommonMandateReference {
payments: payments_data,
payouts: payouts_data,
})
}
#[cfg(feature = "v2")]
pub fn get_common_mandate_reference(&self) -> Result<CommonMandateReference, ParsingError> {
if let Some(value) = &self.connector_mandate_details {
Ok(value.clone())
} else {
Ok(CommonMandateReference {
payments: None,
payouts: None,
})
}
}
#[cfg(feature = "v2")]
pub fn set_payment_method_type(&mut self, payment_method_type: common_enums::PaymentMethod) {
self.payment_method_type = Some(payment_method_type);
}
#[cfg(feature = "v2")]
pub fn set_payment_method_subtype(
&mut self,
payment_method_subtype: common_enums::PaymentMethodType,
) {
self.payment_method_subtype = Some(payment_method_subtype);
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl super::behaviour::Conversion for PaymentMethod {
type DstType = diesel_models::payment_method::PaymentMethod;
type NewDstType = diesel_models::payment_method::PaymentMethodNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let (vault_type, external_vault_source) = self.vault_source_details.into();
Ok(Self::DstType {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
payment_method_id: self.payment_method_id,
accepted_currency: self.accepted_currency,
scheme: self.scheme,
token: self.token,
cardholder_name: self.cardholder_name,
issuer_name: self.issuer_name,
issuer_country: self.issuer_country,
payer_country: self.payer_country,
is_stored: self.is_stored,
swift_code: self.swift_code,
direct_debit_token: self.direct_debit_token,
created_at: self.created_at,
last_modified: self.last_modified,
payment_method: self.payment_method,
payment_method_type: self.payment_method_type,
payment_method_issuer: self.payment_method_issuer,
payment_method_issuer_code: self.payment_method_issuer_code,
metadata: self.metadata,
payment_method_data: self.payment_method_data.map(|val| val.into()),
locker_id: self.locker_id,
last_used_at: self.last_used_at,
connector_mandate_details: self.connector_mandate_details,
customer_acceptance: self.customer_acceptance,
status: self.status,
network_transaction_id: self.network_transaction_id,
client_secret: self.client_secret,
payment_method_billing_address: self
.payment_method_billing_address
.map(|val| val.into()),
updated_by: self.updated_by,
version: self.version,
network_token_requestor_reference_id: self.network_token_requestor_reference_id,
network_token_locker_id: self.network_token_locker_id,
network_token_payment_method_data: self
.network_token_payment_method_data
.map(|val| val.into()),
external_vault_source,
vault_type,
})
}
async fn convert_back(
state: &keymanager::KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
// Decrypt encrypted fields first
let (
payment_method_data,
payment_method_billing_address,
network_token_payment_method_data,
) = async {
let payment_method_data = item
.payment_method_data
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?;
let payment_method_billing_address = item
.payment_method_billing_address
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?;
let network_token_payment_method_data = item
.network_token_payment_method_data
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?;
Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>((
payment_method_data,
payment_method_billing_address,
network_token_payment_method_data,
))
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting payment method data".to_string(),
})?;
let vault_source_details = PaymentMethodVaultSourceDetails::try_from((
item.vault_type,
item.external_vault_source,
))?;
// Construct the domain type
Ok(Self {
customer_id: item.customer_id,
merchant_id: item.merchant_id,
payment_method_id: item.payment_method_id,
accepted_currency: item.accepted_currency,
scheme: item.scheme,
token: item.token,
cardholder_name: item.cardholder_name,
issuer_name: item.issuer_name,
issuer_country: item.issuer_country,
payer_country: item.payer_country,
is_stored: item.is_stored,
swift_code: item.swift_code,
direct_debit_token: item.direct_debit_token,
created_at: item.created_at,
last_modified: item.last_modified,
payment_method: item.payment_method,
payment_method_type: item.payment_method_type,
payment_method_issuer: item.payment_method_issuer,
payment_method_issuer_code: item.payment_method_issuer_code,
metadata: item.metadata,
payment_method_data,
locker_id: item.locker_id,
last_used_at: item.last_used_at,
connector_mandate_details: item.connector_mandate_details,
customer_acceptance: item.customer_acceptance,
status: item.status,
network_transaction_id: item.network_transaction_id,
client_secret: item.client_secret,
payment_method_billing_address,
updated_by: item.updated_by,
version: item.version,
network_token_requestor_reference_id: item.network_token_requestor_reference_id,
network_token_locker_id: item.network_token_locker_id,
network_token_payment_method_data,
vault_source_details,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let (vault_type, external_vault_source) = self.vault_source_details.into();
Ok(Self::NewDstType {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
payment_method_id: self.payment_method_id,
accepted_currency: self.accepted_currency,
scheme: self.scheme,
token: self.token,
cardholder_name: self.cardholder_name,
issuer_name: self.issuer_name,
issuer_country: self.issuer_country,
payer_country: self.payer_country,
is_stored: self.is_stored,
swift_code: self.swift_code,
direct_debit_token: self.direct_debit_token,
created_at: self.created_at,
last_modified: self.last_modified,
payment_method: self.payment_method,
payment_method_type: self.payment_method_type,
payment_method_issuer: self.payment_method_issuer,
payment_method_issuer_code: self.payment_method_issuer_code,
metadata: self.metadata,
payment_method_data: self.payment_method_data.map(|val| val.into()),
locker_id: self.locker_id,
last_used_at: self.last_used_at,
connector_mandate_details: self.connector_mandate_details,
customer_acceptance: self.customer_acceptance,
status: self.status,
network_transaction_id: self.network_transaction_id,
client_secret: self.client_secret,
payment_method_billing_address: self
.payment_method_billing_address
.map(|val| val.into()),
updated_by: self.updated_by,
version: self.version,
network_token_requestor_reference_id: self.network_token_requestor_reference_id,
network_token_locker_id: self.network_token_locker_id,
network_token_payment_method_data: self
.network_token_payment_method_data
.map(|val| val.into()),
external_vault_source,
vault_type,
})
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl super::behaviour::Conversion for PaymentMethod {
type DstType = diesel_models::payment_method::PaymentMethod;
type NewDstType = diesel_models::payment_method::PaymentMethodNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(Self::DstType {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
id: self.id,
created_at: self.created_at,
last_modified: self.last_modified,
payment_method_type_v2: self.payment_method_type,
payment_method_subtype: self.payment_method_subtype,
payment_method_data: self.payment_method_data.map(|val| val.into()),
locker_id: self.locker_id.map(|id| id.get_string_repr().clone()),
last_used_at: self.last_used_at,
connector_mandate_details: self.connector_mandate_details.map(|cmd| cmd.into()),
customer_acceptance: self.customer_acceptance,
status: self.status,
network_transaction_id: self.network_transaction_id,
client_secret: self.client_secret,
payment_method_billing_address: self
.payment_method_billing_address
.map(|val| val.into()),
updated_by: self.updated_by,
locker_fingerprint_id: self.locker_fingerprint_id,
version: self.version,
network_token_requestor_reference_id: self.network_token_requestor_reference_id,
network_token_locker_id: self.network_token_locker_id,
network_token_payment_method_data: self
.network_token_payment_method_data
.map(|val| val.into()),
external_vault_source: self.external_vault_source,
external_vault_token_data: self.external_vault_token_data.map(|val| val.into()),
vault_type: self.vault_type,
})
}
async fn convert_back(
state: &keymanager::KeyManagerState,
storage_model: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
use common_utils::ext_traits::ValueExt;
async {
let decrypted_data = crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::BatchDecrypt(EncryptedPaymentMethod::to_encryptable(
EncryptedPaymentMethod {
payment_method_data: storage_model.payment_method_data,
payment_method_billing_address: storage_model
.payment_method_billing_address,
network_token_payment_method_data: storage_model
.network_token_payment_method_data,
external_vault_token_data: storage_model.external_vault_token_data,
},
)),
key_manager_identifier,
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())?;
let data = EncryptedPaymentMethod::from_encryptable(decrypted_data)
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Invalid batch operation data")?;
let payment_method_billing_address = data
.payment_method_billing_address
.map(|billing| {
billing.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing Address")?;
let payment_method_data = data
.payment_method_data
.map(|payment_method_data| {
payment_method_data
.deserialize_inner_value(|value| value.parse_value("Payment Method Data"))
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing Payment Method Data")?;
let network_token_payment_method_data = data
.network_token_payment_method_data
.map(|network_token_payment_method_data| {
network_token_payment_method_data.deserialize_inner_value(|value| {
value.parse_value("Network token Payment Method Data")
})
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing Network token Payment Method Data")?;
let external_vault_token_data = data
.external_vault_token_data
.map(|external_vault_token_data| {
external_vault_token_data.deserialize_inner_value(|value| {
value.parse_value("External Vault Token Data")
})
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing External Vault Token Data")?;
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
customer_id: storage_model.customer_id,
merchant_id: storage_model.merchant_id,
id: storage_model.id,
created_at: storage_model.created_at,
last_modified: storage_model.last_modified,
payment_method_type: storage_model.payment_method_type_v2,
payment_method_subtype: storage_model.payment_method_subtype,
payment_method_data,
locker_id: storage_model.locker_id.map(VaultId::generate),
last_used_at: storage_model.last_used_at,
connector_mandate_details: storage_model.connector_mandate_details.map(From::from),
customer_acceptance: storage_model.customer_acceptance,
status: storage_model.status,
network_transaction_id: storage_model.network_transaction_id,
client_secret: storage_model.client_secret,
payment_method_billing_address,
updated_by: storage_model.updated_by,
locker_fingerprint_id: storage_model.locker_fingerprint_id,
version: storage_model.version,
network_token_requestor_reference_id: storage_model
.network_token_requestor_reference_id,
network_token_locker_id: storage_model.network_token_locker_id,
network_token_payment_method_data,
external_vault_source: storage_model.external_vault_source,
external_vault_token_data,
vault_type: storage_model.vault_type,
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting payment method data".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(Self::NewDstType {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
id: self.id,
created_at: self.created_at,
last_modified: self.last_modified,
payment_method_type_v2: self.payment_method_type,
payment_method_subtype: self.payment_method_subtype,
payment_method_data: self.payment_method_data.map(|val| val.into()),
locker_id: self.locker_id.map(|id| id.get_string_repr().clone()),
last_used_at: self.last_used_at,
connector_mandate_details: self.connector_mandate_details.map(|cmd| cmd.into()),
customer_acceptance: self.customer_acceptance,
status: self.status,
network_transaction_id: self.network_transaction_id,
client_secret: self.client_secret,
payment_method_billing_address: self
.payment_method_billing_address
.map(|val| val.into()),
updated_by: self.updated_by,
locker_fingerprint_id: self.locker_fingerprint_id,
version: self.version,
network_token_requestor_reference_id: self.network_token_requestor_reference_id,
network_token_locker_id: self.network_token_locker_id,
network_token_payment_method_data: self
.network_token_payment_method_data
.map(|val| val.into()),
external_vault_token_data: self.external_vault_token_data.map(|val| val.into()),
vault_type: self.vault_type,
})
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct PaymentMethodSession {
pub id: id_type::GlobalPaymentMethodSessionId,
pub customer_id: id_type::GlobalCustomerId,
#[encrypt(ty = Value)]
pub billing: Option<Encryptable<Address>>,
pub return_url: Option<common_utils::types::Url>,
pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>,
pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
pub tokenization_data: Option<pii::SecretSerdeValue>,
pub expires_at: PrimitiveDateTime,
pub associated_payment_methods: Option<Vec<String>>,
pub associated_payment: Option<id_type::GlobalPaymentId>,
pub associated_token_id: Option<id_type::GlobalTokenId>,
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl super::behaviour::Conversion for PaymentMethodSession {
type DstType = diesel_models::payment_methods_session::PaymentMethodSession;
type NewDstType = diesel_models::payment_methods_session::PaymentMethodSession;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(Self::DstType {
id: self.id,
customer_id: self.customer_id,
billing: self.billing.map(|val| val.into()),
psp_tokenization: self.psp_tokenization,
network_tokenization: self.network_tokenization,
tokenization_data: self.tokenization_data,
expires_at: self.expires_at,
associated_payment_methods: self.associated_payment_methods,
associated_payment: self.associated_payment,
return_url: self.return_url,
associated_token_id: self.associated_token_id,
})
}
async fn convert_back(
state: &keymanager::KeyManagerState,
storage_model: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
use common_utils::ext_traits::ValueExt;
async {
let decrypted_data = crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::BatchDecrypt(EncryptedPaymentMethodSession::to_encryptable(
EncryptedPaymentMethodSession {
billing: storage_model.billing,
},
)),
key_manager_identifier,
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())?;
let data = EncryptedPaymentMethodSession::from_encryptable(decrypted_data)
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Invalid batch operation data")?;
let billing = data
.billing
.map(|billing| {
billing.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing Address")?;
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
id: storage_model.id,
customer_id: storage_model.customer_id,
billing,
psp_tokenization: storage_model.psp_tokenization,
network_tokenization: storage_model.network_tokenization,
tokenization_data: storage_model.tokenization_data,
expires_at: storage_model.expires_at,
associated_payment_methods: storage_model.associated_payment_methods,
associated_payment: storage_model.associated_payment,
return_url: storage_model.return_url,
associated_token_id: storage_model.associated_token_id,
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting payment method data".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(Self::NewDstType {
id: self.id,
customer_id: self.customer_id,
billing: self.billing.map(|val| val.into()),
psp_tokenization: self.psp_tokenization,
network_tokenization: self.network_tokenization,
tokenization_data: self.tokenization_data,
expires_at: self.expires_at,
associated_payment_methods: self.associated_payment_methods,
associated_payment: self.associated_payment,
return_url: self.return_url,
associated_token_id: self.associated_token_id,
})
}
}
#[async_trait::async_trait]
pub trait PaymentMethodInterface {
type Error;
#[cfg(feature = "v1")]
async fn find_payment_method(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
payment_method_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentMethod, Self::Error>;
#[cfg(feature = "v2")]
async fn find_payment_method(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
payment_method_id: &id_type::GlobalPaymentMethodId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentMethod, Self::Error>;
#[cfg(feature = "v1")]
async fn find_payment_method_by_locker_id(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
locker_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentMethod, Self::Error>;
#[cfg(feature = "v1")]
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
limit: Option<i64>,
) -> CustomResult<Vec<PaymentMethod>, Self::Error>;
// Need to fix this once we start moving to v2 for payment method
#[cfg(feature = "v2")]
async fn find_payment_method_list_by_global_customer_id(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
id: &id_type::GlobalCustomerId,
limit: Option<i64>,
) -> CustomResult<Vec<PaymentMethod>, Self::Error>;
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<PaymentMethod>, Self::Error>;
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn find_payment_method_by_global_customer_id_merchant_id_status(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::GlobalCustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
limit: Option<i64>,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Vec<PaymentMethod>, Self::Error>;
#[cfg(feature = "v1")]
async fn get_payment_method_count_by_customer_id_merchant_id_status(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, Self::Error>;
async fn get_payment_method_count_by_merchant_id_status(
&self,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, Self::Error>;
async fn insert_payment_method(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: PaymentMethod,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentMethod, Self::Error>;
async fn update_payment_method(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: PaymentMethod,
payment_method_update: PaymentMethodUpdate,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<PaymentMethod, Self::Error>;
#[cfg(feature = "v2")]
async fn delete_payment_method(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: PaymentMethod,
) -> CustomResult<PaymentMethod, Self::Error>;
#[cfg(feature = "v2")]
async fn find_payment_method_by_fingerprint_id(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
fingerprint_id: &str,
) -> CustomResult<PaymentMethod, Self::Error>;
#[cfg(feature = "v1")]
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
state: &keymanager::KeyManagerState,
key_store: &MerchantKeyStore,
merchant_id: &id_type::MerchantId,
payment_method_id: &str,
) -> CustomResult<PaymentMethod, Self::Error>;
}
#[cfg(feature = "v2")]
pub enum PaymentMethodsSessionUpdateEnum {
GeneralUpdate {
billing: Box<Option<Encryptable<Address>>>,
psp_tokenization: Option<common_types::payment_methods::PspTokenization>,
network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
tokenization_data: Option<pii::SecretSerdeValue>,
},
UpdateAssociatedPaymentMethods {
associated_payment_methods: Option<Vec<String>>,
},
}
#[cfg(feature = "v2")]
impl From<PaymentMethodsSessionUpdateEnum> for PaymentMethodsSessionUpdateInternal {
fn from(update: PaymentMethodsSessionUpdateEnum) -> Self {
match update {
PaymentMethodsSessionUpdateEnum::GeneralUpdate {
billing,
psp_tokenization,
network_tokenization,
tokenization_data,
} => Self {
billing: *billing,
psp_tokenization,
network_tokenization,
tokenization_data,
associated_payment_methods: None,
},
PaymentMethodsSessionUpdateEnum::UpdateAssociatedPaymentMethods {
associated_payment_methods,
} => Self {
billing: None,
psp_tokenization: None,
network_tokenization: None,
tokenization_data: None,
associated_payment_methods,
},
}
}
}
#[cfg(feature = "v2")]
impl PaymentMethodSession {
pub fn apply_changeset(self, update_session: PaymentMethodsSessionUpdateInternal) -> Self {
let Self {
id,
customer_id,
billing,
psp_tokenization,
network_tokenization,
tokenization_data,
expires_at,
return_url,
associated_payment_methods,
associated_payment,
associated_token_id,
} = self;
Self {
id,
customer_id,
billing: update_session.billing.or(billing),
psp_tokenization: update_session.psp_tokenization.or(psp_tokenization),
network_tokenization: update_session.network_tokenization.or(network_tokenization),
tokenization_data: update_session.tokenization_data.or(tokenization_data),
expires_at,
return_url,
associated_payment_methods: update_session
.associated_payment_methods
.or(associated_payment_methods),
associated_payment,
associated_token_id,
}
}
}
#[cfg(feature = "v2")]
pub struct PaymentMethodsSessionUpdateInternal {
pub billing: Option<Encryptable<Address>>,
pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>,
pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>,
pub tokenization_data: Option<pii::SecretSerdeValue>,
pub associated_payment_methods: Option<Vec<String>>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct ConnectorCustomerDetails {
pub connector_customer_id: String,
pub merchant_connector_id: id_type::MerchantConnectorAccountId,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct PaymentMethodCustomerMigrate {
pub customer: customers::CustomerRequest,
pub connector_customer_details: Option<Vec<ConnectorCustomerDetails>>,
}
#[cfg(feature = "v1")]
impl TryFrom<(payment_methods::PaymentMethodRecord, id_type::MerchantId)>
for PaymentMethodCustomerMigrate
{
type Error = error_stack::Report<ValidationError>;
fn try_from(
value: (payment_methods::PaymentMethodRecord, id_type::MerchantId),
) -> Result<Self, Self::Error> {
let (record, merchant_id) = value;
let connector_customer_details = record
.connector_customer_id
.and_then(|connector_customer_id| {
// Handle single merchant_connector_id
record
.merchant_connector_id
.as_ref()
.map(|merchant_connector_id| {
Ok(vec![ConnectorCustomerDetails {
connector_customer_id: connector_customer_id.clone(),
merchant_connector_id: merchant_connector_id.clone(),
}])
})
// Handle comma-separated merchant_connector_ids
.or_else(|| {
record
.merchant_connector_ids
.as_ref()
.map(|merchant_connector_ids_str| {
merchant_connector_ids_str
.split(',')
.map(|id| id.trim())
.filter(|id| !id.is_empty())
.map(|merchant_connector_id| {
id_type::MerchantConnectorAccountId::wrap(
merchant_connector_id.to_string(),
)
.map_err(|_| {
error_stack::report!(ValidationError::InvalidValue {
message: format!(
"Invalid merchant_connector_account_id: {merchant_connector_id}"
),
})
})
.map(
|merchant_connector_id| ConnectorCustomerDetails {
connector_customer_id: connector_customer_id
.clone(),
merchant_connector_id,
},
)
})
.collect::<Result<Vec<_>, _>>()
})
})
})
.transpose()?;
Ok(Self {
customer: customers::CustomerRequest {
customer_id: Some(record.customer_id),
merchant_id,
name: record.name,
email: record.email,
phone: record.phone,
description: None,
phone_country_code: record.phone_country_code,
address: Some(payments::AddressDetails {
city: record.billing_address_city,
country: record.billing_address_country,
line1: record.billing_address_line1,
line2: record.billing_address_line2,
state: record.billing_address_state,
line3: record.billing_address_line3,
zip: record.billing_address_zip,
first_name: record.billing_address_first_name,
last_name: record.billing_address_last_name,
origin_zip: None,
}),
metadata: None,
tax_registration_id: None,
},
connector_customer_details,
})
}
}
#[cfg(feature = "v1")]
impl ForeignTryFrom<(&[payment_methods::PaymentMethodRecord], id_type::MerchantId)>
for Vec<PaymentMethodCustomerMigrate>
{
type Error = error_stack::Report<ValidationError>;
fn foreign_try_from(
(records, merchant_id): (&[payment_methods::PaymentMethodRecord], id_type::MerchantId),
) -> Result<Self, Self::Error> {
let (customers_migration, migration_errors): (Self, Vec<_>) = records
.iter()
.map(|record| {
PaymentMethodCustomerMigrate::try_from((record.clone(), merchant_id.clone()))
})
.fold((Self::new(), Vec::new()), |mut acc, result| {
match result {
Ok(customer) => acc.0.push(customer),
Err(e) => acc.1.push(e.to_string()),
}
acc
});
migration_errors
.is_empty()
.then_some(customers_migration)
.ok_or_else(|| {
error_stack::report!(ValidationError::InvalidValue {
message: migration_errors.join(", "),
})
})
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Default)]
pub enum PaymentMethodVaultSourceDetails {
ExternalVault {
external_vault_source: id_type::MerchantConnectorAccountId,
},
#[default]
InternalVault,
}
#[cfg(feature = "v1")]
impl
TryFrom<(
Option<storage_enums::VaultType>,
Option<id_type::MerchantConnectorAccountId>,
)> for PaymentMethodVaultSourceDetails
{
type Error = error_stack::Report<ValidationError>;
fn try_from(
value: (
Option<storage_enums::VaultType>,
Option<id_type::MerchantConnectorAccountId>,
),
) -> Result<Self, Self::Error> {
match value {
(Some(storage_enums::VaultType::External), Some(external_vault_source)) => {
Ok(Self::ExternalVault {
external_vault_source,
})
}
(Some(storage_enums::VaultType::External), None) => {
Err(ValidationError::MissingRequiredField {
field_name: "external vault mca id".to_string(),
}
.into())
}
(Some(storage_enums::VaultType::Internal), _) | (None, _) => Ok(Self::InternalVault), // defaulting to internal vault if vault type is none
}
}
}
#[cfg(feature = "v1")]
impl From<PaymentMethodVaultSourceDetails>
for (
Option<storage_enums::VaultType>,
Option<id_type::MerchantConnectorAccountId>,
)
{
fn from(value: PaymentMethodVaultSourceDetails) -> Self {
match value {
PaymentMethodVaultSourceDetails::ExternalVault {
external_vault_source,
} => (
Some(storage_enums::VaultType::External),
Some(external_vault_source),
),
PaymentMethodVaultSourceDetails::InternalVault => {
(Some(storage_enums::VaultType::Internal), None)
}
}
}
}
#[cfg(feature = "v1")]
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use id_type::MerchantConnectorAccountId;
use super::*;
fn get_payment_method_with_mandate_data(
mandate_data: Option<serde_json::Value>,
) -> PaymentMethod {
let payment_method = PaymentMethod {
customer_id: id_type::CustomerId::default(),
merchant_id: id_type::MerchantId::default(),
payment_method_id: String::from("abc"),
accepted_currency: None,
scheme: None,
token: None,
cardholder_name: None,
issuer_name: None,
issuer_country: None,
payer_country: None,
is_stored: None,
swift_code: None,
direct_debit_token: None,
created_at: common_utils::date_time::now(),
last_modified: common_utils::date_time::now(),
payment_method: None,
payment_method_type: None,
payment_method_issuer: None,
payment_method_issuer_code: None,
metadata: None,
payment_method_data: None,
locker_id: None,
last_used_at: common_utils::date_time::now(),
connector_mandate_details: mandate_data,
customer_acceptance: None,
status: storage_enums::PaymentMethodStatus::Active,
network_transaction_id: None,
client_secret: None,
payment_method_billing_address: None,
updated_by: None,
version: common_enums::ApiVersion::V1,
network_token_requestor_reference_id: None,
network_token_locker_id: None,
network_token_payment_method_data: None,
vault_source_details: Default::default(),
};
payment_method.clone()
}
#[test]
fn test_get_common_mandate_reference_payments_only() {
let connector_mandate_details = serde_json::json!({
"mca_kGz30G8B95MxRwmeQqy6": {
"mandate_metadata": null,
"payment_method_type": null,
"connector_mandate_id": "RcBww0a02c-R22w22w22wNJV-V14o20u24y18sTB18sB24y06g04eVZ04e20u14o",
"connector_mandate_status": "active",
"original_payment_authorized_amount": 51,
"original_payment_authorized_currency": "USD",
"connector_mandate_request_reference_id": "RowbU9ULN9H59bMhWk"
}
});
let payment_method = get_payment_method_with_mandate_data(Some(connector_mandate_details));
let result = payment_method.get_common_mandate_reference();
assert!(result.is_ok());
let common_mandate = result.unwrap();
assert!(common_mandate.payments.is_some());
assert!(common_mandate.payouts.is_none());
let payments = common_mandate.payments.unwrap();
let result_mca = MerchantConnectorAccountId::wrap("mca_kGz30G8B95MxRwmeQqy6".to_string());
assert!(
result_mca.is_ok(),
"Expected Ok, but got Err: {result_mca:?}",
);
let mca = result_mca.unwrap();
assert!(payments.0.contains_key(&mca));
}
#[test]
fn test_get_common_mandate_reference_empty_details() {
let payment_method = get_payment_method_with_mandate_data(None);
let result = payment_method.get_common_mandate_reference();
assert!(result.is_ok());
let common_mandate = result.unwrap();
assert!(common_mandate.payments.is_none());
assert!(common_mandate.payouts.is_none());
}
#[test]
fn test_get_common_mandate_reference_payouts_only() {
let connector_mandate_details = serde_json::json!({
"payouts": {
"mca_DAHVXbXpbYSjnL7fQWEs": {
"transfer_method_id": "TRM-678ab3997b16cb7cd"
}
}
});
let payment_method = get_payment_method_with_mandate_data(Some(connector_mandate_details));
let result = payment_method.get_common_mandate_reference();
assert!(result.is_ok());
let common_mandate = result.unwrap();
assert!(common_mandate.payments.is_some());
assert!(common_mandate.payouts.is_some());
let payouts = common_mandate.payouts.unwrap();
let result_mca = MerchantConnectorAccountId::wrap("mca_DAHVXbXpbYSjnL7fQWEs".to_string());
assert!(
result_mca.is_ok(),
"Expected Ok, but got Err: {result_mca:?}",
);
let mca = result_mca.unwrap();
assert!(payouts.0.contains_key(&mca));
}
#[test]
fn test_get_common_mandate_reference_invalid_data() {
let connector_mandate_details = serde_json::json!("invalid");
let payment_method = get_payment_method_with_mandate_data(Some(connector_mandate_details));
let result = payment_method.get_common_mandate_reference();
assert!(result.is_err());
}
#[test]
fn test_get_common_mandate_reference_with_payments_and_payouts_details() {
let connector_mandate_details = serde_json::json!({
"mca_kGz30G8B95MxRwmeQqy6": {
"mandate_metadata": null,
"payment_method_type": null,
"connector_mandate_id": "RcBww0a02c-R22w22w22wNJV-V14o20u24y18sTB18sB24y06g04eVZ04e20u14o",
"connector_mandate_status": "active",
"original_payment_authorized_amount": 51,
"original_payment_authorized_currency": "USD",
"connector_mandate_request_reference_id": "RowbU9ULN9H59bMhWk"
},
"payouts": {
"mca_DAHVXbXpbYSjnL7fQWEs": {
"transfer_method_id": "TRM-678ab3997b16cb7cd"
}
}
});
let payment_method = get_payment_method_with_mandate_data(Some(connector_mandate_details));
let result = payment_method.get_common_mandate_reference();
assert!(result.is_ok());
let common_mandate = result.unwrap();
assert!(common_mandate.payments.is_some());
assert!(common_mandate.payouts.is_some());
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/payment_methods.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 6,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_27187086768077354
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/payment_address.rs
// Contains: 1 structs, 0 enums
use crate::address::Address;
#[derive(Clone, Default, Debug, serde::Serialize)]
pub struct PaymentAddress {
shipping: Option<Address>,
billing: Option<Address>,
unified_payment_method_billing: Option<Address>,
payment_method_billing: Option<Address>,
}
impl PaymentAddress {
pub fn new(
shipping: Option<Address>,
billing: Option<Address>,
payment_method_billing: Option<Address>,
should_unify_address: Option<bool>,
) -> Self {
// billing -> .billing, this is the billing details passed in the root of payments request
// payment_method_billing -> .payment_method_data.billing
let unified_payment_method_billing = if should_unify_address.unwrap_or(true) {
// Merge the billing details field from both `payment.billing` and `payment.payment_method_data.billing`
// The unified payment_method_billing will be used as billing address and passed to the connector module
// This unification is required in order to provide backwards compatibility
// so that if `payment.billing` is passed it should be sent to the connector module
// Unify the billing details with `payment_method_data.billing`
payment_method_billing
.as_ref()
.map(|payment_method_billing| {
payment_method_billing
.clone()
.unify_address(billing.as_ref())
})
.or(billing.clone())
} else {
payment_method_billing.clone()
};
Self {
shipping,
billing,
unified_payment_method_billing,
payment_method_billing,
}
}
pub fn get_shipping(&self) -> Option<&Address> {
self.shipping.as_ref()
}
pub fn get_payment_method_billing(&self) -> Option<&Address> {
self.unified_payment_method_billing.as_ref()
}
/// Unify the billing details from `payment_method_data.[payment_method_data].billing details`.
/// Here the fields passed in payment_method_data_billing takes precedence
pub fn unify_with_payment_method_data_billing(
self,
payment_method_data_billing: Option<Address>,
) -> Self {
// Unify the billing details with `payment_method_data.billing_details`
let unified_payment_method_billing = payment_method_data_billing
.map(|payment_method_data_billing| {
payment_method_data_billing.unify_address(self.get_payment_method_billing())
})
.or(self.get_payment_method_billing().cloned());
Self {
shipping: self.shipping,
billing: self.billing,
unified_payment_method_billing,
payment_method_billing: self.payment_method_billing,
}
}
/// Unify the billing details from `payment_method_data.[payment_method_data].billing details`.
/// Here the `self` takes precedence
pub fn unify_with_payment_data_billing(
self,
other_payment_method_billing: Option<Address>,
) -> Self {
let unified_payment_method_billing = self
.get_payment_method_billing()
.map(|payment_method_billing| {
payment_method_billing
.clone()
.unify_address(other_payment_method_billing.as_ref())
})
.or(other_payment_method_billing);
Self {
shipping: self.shipping,
billing: self.billing,
unified_payment_method_billing,
payment_method_billing: self.payment_method_billing,
}
}
pub fn get_request_payment_method_billing(&self) -> Option<&Address> {
self.payment_method_billing.as_ref()
}
pub fn get_payment_billing(&self) -> Option<&Address> {
self.billing.as_ref()
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/payment_address.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_4656405390708126527
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/merchant_account.rs
// Contains: 2 structs, 2 enums
use common_utils::{
crypto::{OptionalEncryptableName, OptionalEncryptableValue},
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
ext_traits::ValueExt,
pii, type_name,
types::keymanager::{self},
};
use diesel_models::{
enums::MerchantStorageScheme, merchant_account::MerchantAccountUpdateInternal,
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use router_env::logger;
use crate::{
behaviour::Conversion,
merchant_key_store,
type_encryption::{crypto_operation, AsyncLift, CryptoOperation},
};
#[cfg(feature = "v1")]
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantAccount {
merchant_id: common_utils::id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub merchant_name: OptionalEncryptableName,
pub merchant_details: OptionalEncryptableValue,
pub webhook_details: Option<diesel_models::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: serde_json::Value,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub intent_fulfillment_time: Option<i64>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<common_utils::id_type::ProfileId>,
pub recon_status: diesel_models::enums::ReconStatus,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[cfg(feature = "v1")]
#[derive(Clone)]
/// Set the private fields of merchant account
pub struct MerchantAccountSetter {
pub merchant_id: common_utils::id_type::MerchantId,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub merchant_name: OptionalEncryptableName,
pub merchant_details: OptionalEncryptableValue,
pub webhook_details: Option<diesel_models::business_profile::WebhookDetails>,
pub sub_merchants_enabled: Option<bool>,
pub parent_merchant_id: Option<common_utils::id_type::MerchantId>,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub locker_id: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub primary_business_details: serde_json::Value,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub intent_fulfillment_time: Option<i64>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub is_recon_enabled: bool,
pub default_profile: Option<common_utils::id_type::ProfileId>,
pub recon_status: diesel_models::enums::ReconStatus,
pub payment_link_config: Option<serde_json::Value>,
pub pm_collect_link_config: Option<serde_json::Value>,
pub version: common_enums::ApiVersion,
pub is_platform_account: bool,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[cfg(feature = "v1")]
impl From<MerchantAccountSetter> for MerchantAccount {
fn from(item: MerchantAccountSetter) -> Self {
Self {
merchant_id: item.merchant_id,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
payment_response_hash_key: item.payment_response_hash_key,
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
merchant_name: item.merchant_name,
merchant_details: item.merchant_details,
webhook_details: item.webhook_details,
sub_merchants_enabled: item.sub_merchants_enabled,
parent_merchant_id: item.parent_merchant_id,
publishable_key: item.publishable_key,
storage_scheme: item.storage_scheme,
locker_id: item.locker_id,
metadata: item.metadata,
routing_algorithm: item.routing_algorithm,
primary_business_details: item.primary_business_details,
frm_routing_algorithm: item.frm_routing_algorithm,
created_at: item.created_at,
modified_at: item.modified_at,
intent_fulfillment_time: item.intent_fulfillment_time,
payout_routing_algorithm: item.payout_routing_algorithm,
organization_id: item.organization_id,
is_recon_enabled: item.is_recon_enabled,
default_profile: item.default_profile,
recon_status: item.recon_status,
payment_link_config: item.payment_link_config,
pm_collect_link_config: item.pm_collect_link_config,
version: item.version,
is_platform_account: item.is_platform_account,
product_type: item.product_type,
merchant_account_type: item.merchant_account_type,
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone)]
/// Set the private fields of merchant account
pub struct MerchantAccountSetter {
pub id: common_utils::id_type::MerchantId,
pub merchant_name: OptionalEncryptableName,
pub merchant_details: OptionalEncryptableValue,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub organization_id: common_utils::id_type::OrganizationId,
pub recon_status: diesel_models::enums::ReconStatus,
pub is_platform_account: bool,
pub version: common_enums::ApiVersion,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
#[cfg(feature = "v2")]
impl From<MerchantAccountSetter> for MerchantAccount {
fn from(item: MerchantAccountSetter) -> Self {
let MerchantAccountSetter {
id,
merchant_name,
merchant_details,
publishable_key,
storage_scheme,
metadata,
created_at,
modified_at,
organization_id,
recon_status,
is_platform_account,
version,
product_type,
merchant_account_type,
} = item;
Self {
id,
merchant_name,
merchant_details,
publishable_key,
storage_scheme,
metadata,
created_at,
modified_at,
organization_id,
recon_status,
is_platform_account,
version,
product_type,
merchant_account_type,
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantAccount {
id: common_utils::id_type::MerchantId,
pub merchant_name: OptionalEncryptableName,
pub merchant_details: OptionalEncryptableValue,
pub publishable_key: String,
pub storage_scheme: MerchantStorageScheme,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub organization_id: common_utils::id_type::OrganizationId,
pub recon_status: diesel_models::enums::ReconStatus,
pub is_platform_account: bool,
pub version: common_enums::ApiVersion,
pub product_type: Option<common_enums::MerchantProductType>,
pub merchant_account_type: common_enums::MerchantAccountType,
}
impl MerchantAccount {
#[cfg(feature = "v1")]
/// Get the unique identifier of MerchantAccount
pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
&self.merchant_id
}
#[cfg(feature = "v2")]
/// Get the unique identifier of MerchantAccount
pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
&self.id
}
/// Get the organization_id from MerchantAccount
pub fn get_org_id(&self) -> &common_utils::id_type::OrganizationId {
&self.organization_id
}
/// Get the merchant_details from MerchantAccount
pub fn get_merchant_details(&self) -> &OptionalEncryptableValue {
&self.merchant_details
}
/// Extract merchant_tax_registration_id from merchant_details
pub fn get_merchant_tax_registration_id(&self) -> Option<Secret<String>> {
self.merchant_details.as_ref().and_then(|details| {
details
.get_inner()
.peek()
.get("merchant_tax_registration_id")
.and_then(|id| id.as_str().map(|s| Secret::new(s.to_string())))
})
}
/// Check whether the merchant account is a platform account
pub fn is_platform_account(&self) -> bool {
matches!(
self.merchant_account_type,
common_enums::MerchantAccountType::Platform
)
}
}
#[cfg(feature = "v1")]
#[allow(clippy::large_enum_variant)]
#[derive(Debug, Clone)]
pub enum MerchantAccountUpdate {
Update {
merchant_name: OptionalEncryptableName,
merchant_details: OptionalEncryptableValue,
return_url: Option<String>,
webhook_details: Option<diesel_models::business_profile::WebhookDetails>,
sub_merchants_enabled: Option<bool>,
parent_merchant_id: Option<common_utils::id_type::MerchantId>,
enable_payment_response_hash: Option<bool>,
payment_response_hash_key: Option<String>,
redirect_to_merchant_with_http_post: Option<bool>,
publishable_key: Option<String>,
locker_id: Option<String>,
metadata: Option<pii::SecretSerdeValue>,
routing_algorithm: Option<serde_json::Value>,
primary_business_details: Option<serde_json::Value>,
intent_fulfillment_time: Option<i64>,
frm_routing_algorithm: Option<serde_json::Value>,
payout_routing_algorithm: Option<serde_json::Value>,
default_profile: Option<Option<common_utils::id_type::ProfileId>>,
payment_link_config: Option<serde_json::Value>,
pm_collect_link_config: Option<serde_json::Value>,
},
StorageSchemeUpdate {
storage_scheme: MerchantStorageScheme,
},
ReconUpdate {
recon_status: diesel_models::enums::ReconStatus,
},
UnsetDefaultProfile,
ModifiedAtUpdate,
ToPlatformAccount,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone)]
pub enum MerchantAccountUpdate {
Update {
merchant_name: OptionalEncryptableName,
merchant_details: OptionalEncryptableValue,
publishable_key: Option<String>,
metadata: Option<Box<pii::SecretSerdeValue>>,
},
StorageSchemeUpdate {
storage_scheme: MerchantStorageScheme,
},
ReconUpdate {
recon_status: diesel_models::enums::ReconStatus,
},
ModifiedAtUpdate,
ToPlatformAccount,
}
#[cfg(feature = "v1")]
impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
fn from(merchant_account_update: MerchantAccountUpdate) -> Self {
let now = date_time::now();
match merchant_account_update {
MerchantAccountUpdate::Update {
merchant_name,
merchant_details,
webhook_details,
return_url,
routing_algorithm,
sub_merchants_enabled,
parent_merchant_id,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
publishable_key,
locker_id,
metadata,
primary_business_details,
intent_fulfillment_time,
frm_routing_algorithm,
payout_routing_algorithm,
default_profile,
payment_link_config,
pm_collect_link_config,
} => Self {
merchant_name: merchant_name.map(Encryption::from),
merchant_details: merchant_details.map(Encryption::from),
frm_routing_algorithm,
webhook_details,
routing_algorithm,
sub_merchants_enabled,
parent_merchant_id,
return_url,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
publishable_key,
locker_id,
metadata,
primary_business_details,
modified_at: now,
intent_fulfillment_time,
payout_routing_algorithm,
default_profile,
payment_link_config,
pm_collect_link_config,
storage_scheme: None,
organization_id: None,
is_recon_enabled: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self {
storage_scheme: Some(storage_scheme),
modified_at: now,
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ReconUpdate { recon_status } => Self {
recon_status: Some(recon_status),
modified_at: now,
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::UnsetDefaultProfile => Self {
default_profile: Some(None),
modified_at: now,
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ModifiedAtUpdate => Self {
modified_at: now,
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ToPlatformAccount => Self {
modified_at: now,
merchant_name: None,
merchant_details: None,
return_url: None,
webhook_details: None,
sub_merchants_enabled: None,
parent_merchant_id: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
publishable_key: None,
storage_scheme: None,
locker_id: None,
metadata: None,
routing_algorithm: None,
primary_business_details: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
organization_id: None,
is_recon_enabled: None,
default_profile: None,
recon_status: None,
payment_link_config: None,
pm_collect_link_config: None,
is_platform_account: Some(true),
product_type: None,
},
}
}
}
#[cfg(feature = "v2")]
impl From<MerchantAccountUpdate> for MerchantAccountUpdateInternal {
fn from(merchant_account_update: MerchantAccountUpdate) -> Self {
let now = date_time::now();
match merchant_account_update {
MerchantAccountUpdate::Update {
merchant_name,
merchant_details,
publishable_key,
metadata,
} => Self {
merchant_name: merchant_name.map(Encryption::from),
merchant_details: merchant_details.map(Encryption::from),
publishable_key,
metadata: metadata.map(|metadata| *metadata),
modified_at: now,
storage_scheme: None,
organization_id: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::StorageSchemeUpdate { storage_scheme } => Self {
storage_scheme: Some(storage_scheme),
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
metadata: None,
organization_id: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ReconUpdate { recon_status } => Self {
recon_status: Some(recon_status),
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
storage_scheme: None,
metadata: None,
organization_id: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ModifiedAtUpdate => Self {
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
storage_scheme: None,
metadata: None,
organization_id: None,
recon_status: None,
is_platform_account: None,
product_type: None,
},
MerchantAccountUpdate::ToPlatformAccount => Self {
modified_at: now,
merchant_name: None,
merchant_details: None,
publishable_key: None,
storage_scheme: None,
metadata: None,
organization_id: None,
recon_status: None,
is_platform_account: Some(true),
product_type: None,
},
}
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl Conversion for MerchantAccount {
type DstType = diesel_models::merchant_account::MerchantAccount;
type NewDstType = diesel_models::merchant_account::MerchantAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let id = self.get_id().to_owned();
let setter = diesel_models::merchant_account::MerchantAccountSetter {
id,
merchant_name: self.merchant_name.map(|name| name.into()),
merchant_details: self.merchant_details.map(|details| details.into()),
publishable_key: Some(self.publishable_key),
storage_scheme: self.storage_scheme,
metadata: self.metadata,
created_at: self.created_at,
modified_at: self.modified_at,
organization_id: self.organization_id,
recon_status: self.recon_status,
version: common_types::consts::API_VERSION,
is_platform_account: self.is_platform_account,
product_type: self.product_type,
merchant_account_type: self.merchant_account_type,
};
Ok(diesel_models::MerchantAccount::from(setter))
}
async fn convert_back(
state: &keymanager::KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let id = item.get_id().to_owned();
let publishable_key =
item.publishable_key
.ok_or(ValidationError::MissingRequiredField {
field_name: "publishable_key".to_string(),
})?;
async {
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
id,
merchant_name: item
.merchant_name
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
merchant_details: item
.merchant_details
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
publishable_key,
storage_scheme: item.storage_scheme,
metadata: item.metadata,
created_at: item.created_at,
modified_at: item.modified_at,
organization_id: item.organization_id,
recon_status: item.recon_status,
is_platform_account: item.is_platform_account,
version: item.version,
product_type: item.product_type,
merchant_account_type: item.merchant_account_type.unwrap_or_default(),
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting merchant data".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(diesel_models::merchant_account::MerchantAccountNew {
id: self.id,
merchant_name: self.merchant_name.map(Encryption::from),
merchant_details: self.merchant_details.map(Encryption::from),
publishable_key: Some(self.publishable_key),
metadata: self.metadata,
created_at: now,
modified_at: now,
organization_id: self.organization_id,
recon_status: self.recon_status,
version: common_types::consts::API_VERSION,
is_platform_account: self.is_platform_account,
product_type: self
.product_type
.or(Some(common_enums::MerchantProductType::Orchestration)),
merchant_account_type: self.merchant_account_type,
})
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl Conversion for MerchantAccount {
type DstType = diesel_models::merchant_account::MerchantAccount;
type NewDstType = diesel_models::merchant_account::MerchantAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let setter = diesel_models::merchant_account::MerchantAccountSetter {
merchant_id: self.merchant_id,
return_url: self.return_url,
enable_payment_response_hash: self.enable_payment_response_hash,
payment_response_hash_key: self.payment_response_hash_key,
redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post,
merchant_name: self.merchant_name.map(|name| name.into()),
merchant_details: self.merchant_details.map(|details| details.into()),
webhook_details: self.webhook_details,
sub_merchants_enabled: self.sub_merchants_enabled,
parent_merchant_id: self.parent_merchant_id,
publishable_key: Some(self.publishable_key),
storage_scheme: self.storage_scheme,
locker_id: self.locker_id,
metadata: self.metadata,
routing_algorithm: self.routing_algorithm,
primary_business_details: self.primary_business_details,
created_at: self.created_at,
modified_at: self.modified_at,
intent_fulfillment_time: self.intent_fulfillment_time,
frm_routing_algorithm: self.frm_routing_algorithm,
payout_routing_algorithm: self.payout_routing_algorithm,
organization_id: self.organization_id,
is_recon_enabled: self.is_recon_enabled,
default_profile: self.default_profile,
recon_status: self.recon_status,
payment_link_config: self.payment_link_config,
pm_collect_link_config: self.pm_collect_link_config,
version: self.version,
is_platform_account: self.is_platform_account,
product_type: self.product_type,
merchant_account_type: self.merchant_account_type,
};
Ok(diesel_models::MerchantAccount::from(setter))
}
async fn convert_back(
state: &keymanager::KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let merchant_id = item.get_id().to_owned();
let publishable_key =
item.publishable_key
.ok_or(ValidationError::MissingRequiredField {
field_name: "publishable_key".to_string(),
})?;
async {
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
merchant_id,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
payment_response_hash_key: item.payment_response_hash_key,
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
merchant_name: item
.merchant_name
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
merchant_details: item
.merchant_details
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
webhook_details: item.webhook_details,
sub_merchants_enabled: item.sub_merchants_enabled,
parent_merchant_id: item.parent_merchant_id,
publishable_key,
storage_scheme: item.storage_scheme,
locker_id: item.locker_id,
metadata: item.metadata,
routing_algorithm: item.routing_algorithm,
frm_routing_algorithm: item.frm_routing_algorithm,
primary_business_details: item.primary_business_details,
created_at: item.created_at,
modified_at: item.modified_at,
intent_fulfillment_time: item.intent_fulfillment_time,
payout_routing_algorithm: item.payout_routing_algorithm,
organization_id: item.organization_id,
is_recon_enabled: item.is_recon_enabled,
default_profile: item.default_profile,
recon_status: item.recon_status,
payment_link_config: item.payment_link_config,
pm_collect_link_config: item.pm_collect_link_config,
version: item.version,
is_platform_account: item.is_platform_account,
product_type: item.product_type,
merchant_account_type: item.merchant_account_type.unwrap_or_default(),
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting merchant data".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(diesel_models::merchant_account::MerchantAccountNew {
id: Some(self.merchant_id.clone()),
merchant_id: self.merchant_id,
merchant_name: self.merchant_name.map(Encryption::from),
merchant_details: self.merchant_details.map(Encryption::from),
return_url: self.return_url,
webhook_details: self.webhook_details,
sub_merchants_enabled: self.sub_merchants_enabled,
parent_merchant_id: self.parent_merchant_id,
enable_payment_response_hash: Some(self.enable_payment_response_hash),
payment_response_hash_key: self.payment_response_hash_key,
redirect_to_merchant_with_http_post: Some(self.redirect_to_merchant_with_http_post),
publishable_key: Some(self.publishable_key),
locker_id: self.locker_id,
metadata: self.metadata,
routing_algorithm: self.routing_algorithm,
primary_business_details: self.primary_business_details,
created_at: now,
modified_at: now,
intent_fulfillment_time: self.intent_fulfillment_time,
frm_routing_algorithm: self.frm_routing_algorithm,
payout_routing_algorithm: self.payout_routing_algorithm,
organization_id: self.organization_id,
is_recon_enabled: self.is_recon_enabled,
default_profile: self.default_profile,
recon_status: self.recon_status,
payment_link_config: self.payment_link_config,
pm_collect_link_config: self.pm_collect_link_config,
version: common_types::consts::API_VERSION,
is_platform_account: self.is_platform_account,
product_type: self
.product_type
.or(Some(common_enums::MerchantProductType::Orchestration)),
merchant_account_type: self.merchant_account_type,
})
}
}
impl MerchantAccount {
pub fn get_compatible_connector(&self) -> Option<api_models::enums::Connector> {
let metadata: Option<api_models::admin::MerchantAccountMetadata> =
self.metadata.as_ref().and_then(|meta| {
meta.clone()
.parse_value("MerchantAccountMetadata")
.map_err(|err| logger::error!("Failed to deserialize {:?}", err))
.ok()
});
metadata.and_then(|a| a.compatible_connector)
}
}
#[async_trait::async_trait]
pub trait MerchantAccountInterface
where
MerchantAccount: Conversion<
DstType = diesel_models::merchant_account::MerchantAccount,
NewDstType = diesel_models::merchant_account::MerchantAccountNew,
>,
{
type Error;
async fn insert_merchant(
&self,
state: &keymanager::KeyManagerState,
merchant_account: MerchantAccount,
merchant_key_store: &merchant_key_store::MerchantKeyStore,
) -> CustomResult<MerchantAccount, Self::Error>;
async fn find_merchant_account_by_merchant_id(
&self,
state: &keymanager::KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
merchant_key_store: &merchant_key_store::MerchantKeyStore,
) -> CustomResult<MerchantAccount, Self::Error>;
async fn update_all_merchant_account(
&self,
merchant_account: MerchantAccountUpdate,
) -> CustomResult<usize, Self::Error>;
async fn update_merchant(
&self,
state: &keymanager::KeyManagerState,
this: MerchantAccount,
merchant_account: MerchantAccountUpdate,
merchant_key_store: &merchant_key_store::MerchantKeyStore,
) -> CustomResult<MerchantAccount, Self::Error>;
async fn update_specific_fields_in_merchant(
&self,
state: &keymanager::KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
merchant_account: MerchantAccountUpdate,
merchant_key_store: &merchant_key_store::MerchantKeyStore,
) -> CustomResult<MerchantAccount, Self::Error>;
async fn find_merchant_account_by_publishable_key(
&self,
state: &keymanager::KeyManagerState,
publishable_key: &str,
) -> CustomResult<(MerchantAccount, merchant_key_store::MerchantKeyStore), Self::Error>;
#[cfg(feature = "olap")]
async fn list_merchant_accounts_by_organization_id(
&self,
state: &keymanager::KeyManagerState,
organization_id: &common_utils::id_type::OrganizationId,
) -> CustomResult<Vec<MerchantAccount>, Self::Error>;
async fn delete_merchant_account_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, Self::Error>;
#[cfg(feature = "olap")]
async fn list_multiple_merchant_accounts(
&self,
state: &keymanager::KeyManagerState,
merchant_ids: Vec<common_utils::id_type::MerchantId>,
) -> CustomResult<Vec<MerchantAccount>, Self::Error>;
#[cfg(feature = "olap")]
async fn list_merchant_and_org_ids(
&self,
state: &keymanager::KeyManagerState,
limit: u32,
offset: Option<u32>,
) -> CustomResult<
Vec<(
common_utils::id_type::MerchantId,
common_utils::id_type::OrganizationId,
)>,
Self::Error,
>;
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/merchant_account.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_6464004582089313144
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_data_v2.rs
// Contains: 1 structs, 0 enums
pub mod flow_common_types;
use std::{marker::PhantomData, ops::Deref};
use common_utils::id_type;
#[cfg(feature = "frm")]
pub use flow_common_types::FrmFlowData;
#[cfg(feature = "payouts")]
pub use flow_common_types::PayoutFlowData;
pub use flow_common_types::{
AccessTokenFlowData, AuthenticationTokenFlowData, DisputesFlowData,
ExternalAuthenticationFlowData, ExternalVaultProxyFlowData, FilesFlowData,
MandateRevokeFlowData, PaymentFlowData, RefundFlowData, UasFlowData, VaultConnectorFlowData,
WebhookSourceVerifyData,
};
use crate::router_data::{ConnectorAuthType, ErrorResponse};
#[derive(Debug, Clone)]
pub struct RouterDataV2<Flow, ResourceCommonData, FlowSpecificRequest, FlowSpecificResponse> {
pub flow: PhantomData<Flow>,
pub tenant_id: id_type::TenantId,
pub resource_common_data: ResourceCommonData,
pub connector_auth_type: ConnectorAuthType,
/// Contains flow-specific data required to construct a request and send it to the connector.
pub request: FlowSpecificRequest,
/// Contains flow-specific data that the connector responds with.
pub response: Result<FlowSpecificResponse, ErrorResponse>,
}
impl<Flow, ResourceCommonData, FlowSpecificRequest, FlowSpecificResponse> Deref
for RouterDataV2<Flow, ResourceCommonData, FlowSpecificRequest, FlowSpecificResponse>
{
type Target = ResourceCommonData;
fn deref(&self) -> &Self::Target {
&self.resource_common_data
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_data_v2.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-2409175948284331607
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/merchant_connector_account.rs
// Contains: 7 structs, 3 enums
#[cfg(feature = "v2")]
use std::collections::HashMap;
use common_utils::{
crypto::Encryptable,
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
ext_traits::ValueExt,
id_type, pii, type_name,
types::keymanager::{Identifier, KeyManagerState, ToEncryptable},
};
#[cfg(feature = "v2")]
use diesel_models::merchant_connector_account::{
BillingAccountReference as DieselBillingAccountReference,
MerchantConnectorAccountFeatureMetadata as DieselMerchantConnectorAccountFeatureMetadata,
RevenueRecoveryMetadata as DieselRevenueRecoveryMetadata,
};
use diesel_models::{
enums,
merchant_connector_account::{self as storage, MerchantConnectorAccountUpdateInternal},
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use rustc_hash::FxHashMap;
use serde_json::Value;
use super::behaviour;
#[cfg(feature = "v2")]
use crate::errors::api_error_response;
use crate::{
mandates::CommonMandateReference,
merchant_key_store::MerchantKeyStore,
router_data,
type_encryption::{crypto_operation, CryptoOperation},
};
#[cfg(feature = "v1")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct MerchantConnectorAccount {
pub merchant_id: id_type::MerchantId,
pub connector_name: String,
#[encrypt]
pub connector_account_details: Encryptable<Secret<Value>>,
pub test_mode: Option<bool>,
pub disabled: Option<bool>,
pub merchant_connector_id: id_type::MerchantConnectorAccountId,
pub payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>,
pub connector_type: enums::ConnectorType,
pub metadata: Option<pii::SecretSerdeValue>,
pub frm_configs: Option<Vec<pii::SecretSerdeValue>>,
pub connector_label: Option<String>,
pub business_country: Option<enums::CountryAlpha2>,
pub business_label: Option<String>,
pub business_sub_label: Option<String>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
pub profile_id: id_type::ProfileId,
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: enums::ConnectorStatus,
#[encrypt]
pub connector_wallets_details: Option<Encryptable<Secret<Value>>>,
#[encrypt]
pub additional_merchant_data: Option<Encryptable<Secret<Value>>>,
pub version: common_enums::ApiVersion,
}
#[cfg(feature = "v1")]
impl MerchantConnectorAccount {
pub fn get_id(&self) -> id_type::MerchantConnectorAccountId {
self.merchant_connector_id.clone()
}
pub fn get_connector_account_details(
&self,
) -> error_stack::Result<router_data::ConnectorAuthType, common_utils::errors::ParsingError>
{
self.connector_account_details
.get_inner()
.clone()
.parse_value("ConnectorAuthType")
}
pub fn get_connector_wallets_details(&self) -> Option<Secret<Value>> {
self.connector_wallets_details.as_deref().cloned()
}
pub fn get_connector_test_mode(&self) -> Option<bool> {
self.test_mode
}
pub fn get_connector_name_as_string(&self) -> String {
self.connector_name.clone()
}
pub fn get_metadata(&self) -> Option<Secret<Value>> {
self.metadata.clone()
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub enum MerchantConnectorAccountTypeDetails {
MerchantConnectorAccount(Box<MerchantConnectorAccount>),
MerchantConnectorDetails(common_types::domain::MerchantConnectorAuthDetails),
}
#[cfg(feature = "v2")]
impl MerchantConnectorAccountTypeDetails {
pub fn get_connector_account_details(
&self,
) -> error_stack::Result<router_data::ConnectorAuthType, common_utils::errors::ParsingError>
{
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
merchant_connector_account
.connector_account_details
.peek()
.clone()
.parse_value("ConnectorAuthType")
}
Self::MerchantConnectorDetails(merchant_connector_details) => {
merchant_connector_details
.merchant_connector_creds
.peek()
.clone()
.parse_value("ConnectorAuthType")
}
}
}
pub fn is_disabled(&self) -> bool {
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
merchant_connector_account.disabled.unwrap_or(false)
}
Self::MerchantConnectorDetails(_) => false,
}
}
pub fn get_metadata(&self) -> Option<Secret<Value>> {
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
merchant_connector_account.metadata.to_owned()
}
Self::MerchantConnectorDetails(_) => None,
}
}
pub fn get_id(&self) -> Option<id_type::MerchantConnectorAccountId> {
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
Some(merchant_connector_account.id.clone())
}
Self::MerchantConnectorDetails(_) => None,
}
}
pub fn get_mca_id(&self) -> Option<id_type::MerchantConnectorAccountId> {
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
Some(merchant_connector_account.get_id())
}
Self::MerchantConnectorDetails(_) => None,
}
}
pub fn get_connector_name(&self) -> Option<common_enums::connector_enums::Connector> {
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
Some(merchant_connector_account.connector_name)
}
Self::MerchantConnectorDetails(merchant_connector_details) => {
Some(merchant_connector_details.connector_name)
}
}
}
pub fn get_connector_name_as_string(&self) -> String {
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
merchant_connector_account.connector_name.to_string()
}
Self::MerchantConnectorDetails(merchant_connector_details) => {
merchant_connector_details.connector_name.to_string()
}
}
}
pub fn get_inner_db_merchant_connector_account(&self) -> Option<&MerchantConnectorAccount> {
match self {
Self::MerchantConnectorAccount(merchant_connector_account) => {
Some(merchant_connector_account)
}
Self::MerchantConnectorDetails(_) => None,
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct MerchantConnectorAccount {
pub id: id_type::MerchantConnectorAccountId,
pub merchant_id: id_type::MerchantId,
pub connector_name: common_enums::connector_enums::Connector,
#[encrypt]
pub connector_account_details: Encryptable<Secret<Value>>,
pub disabled: Option<bool>,
pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>,
pub connector_type: enums::ConnectorType,
pub metadata: Option<pii::SecretSerdeValue>,
pub frm_configs: Option<Vec<pii::SecretSerdeValue>>,
pub connector_label: Option<String>,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub connector_webhook_details: Option<pii::SecretSerdeValue>,
pub profile_id: id_type::ProfileId,
pub applepay_verified_domains: Option<Vec<String>>,
pub pm_auth_config: Option<pii::SecretSerdeValue>,
pub status: enums::ConnectorStatus,
#[encrypt]
pub connector_wallets_details: Option<Encryptable<Secret<Value>>>,
#[encrypt]
pub additional_merchant_data: Option<Encryptable<Secret<Value>>>,
pub version: common_enums::ApiVersion,
pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>,
}
#[cfg(feature = "v2")]
impl MerchantConnectorAccount {
pub fn get_retry_threshold(&self) -> Option<u16> {
self.feature_metadata
.as_ref()
.and_then(|metadata| metadata.revenue_recovery.as_ref())
.map(|recovery| recovery.billing_connector_retry_threshold)
}
pub fn get_id(&self) -> id_type::MerchantConnectorAccountId {
self.id.clone()
}
pub fn get_metadata(&self) -> Option<pii::SecretSerdeValue> {
self.metadata.clone()
}
pub fn is_disabled(&self) -> bool {
self.disabled.unwrap_or(false)
}
pub fn get_connector_account_details(
&self,
) -> error_stack::Result<router_data::ConnectorAuthType, common_utils::errors::ParsingError>
{
use common_utils::ext_traits::ValueExt;
self.connector_account_details
.get_inner()
.clone()
.parse_value("ConnectorAuthType")
}
pub fn get_connector_wallets_details(&self) -> Option<Secret<Value>> {
self.connector_wallets_details.as_deref().cloned()
}
pub fn get_connector_test_mode(&self) -> Option<bool> {
todo!()
}
pub fn get_connector_name_as_string(&self) -> String {
self.connector_name.clone().to_string()
}
#[cfg(feature = "v2")]
pub fn get_connector_name(&self) -> common_enums::connector_enums::Connector {
self.connector_name
}
pub fn get_payment_merchant_connector_account_id_using_account_reference_id(
&self,
account_reference_id: String,
) -> Option<id_type::MerchantConnectorAccountId> {
self.feature_metadata.as_ref().and_then(|metadata| {
metadata.revenue_recovery.as_ref().and_then(|recovery| {
recovery
.mca_reference
.billing_to_recovery
.get(&account_reference_id)
.cloned()
})
})
}
pub fn get_account_reference_id_using_payment_merchant_connector_account_id(
&self,
payment_merchant_connector_account_id: id_type::MerchantConnectorAccountId,
) -> Option<String> {
self.feature_metadata.as_ref().and_then(|metadata| {
metadata.revenue_recovery.as_ref().and_then(|recovery| {
recovery
.mca_reference
.recovery_to_billing
.get(&payment_merchant_connector_account_id)
.cloned()
})
})
}
}
#[cfg(feature = "v2")]
/// Holds the payment methods enabled for a connector along with the connector name
/// This struct is a flattened representation of the payment methods enabled for a connector
#[derive(Debug)]
pub struct PaymentMethodsEnabledForConnector {
pub payment_methods_enabled: common_types::payment_methods::RequestPaymentMethodTypes,
pub payment_method: common_enums::PaymentMethod,
pub connector: common_enums::connector_enums::Connector,
pub merchant_connector_id: id_type::MerchantConnectorAccountId,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone)]
pub struct MerchantConnectorAccountFeatureMetadata {
pub revenue_recovery: Option<RevenueRecoveryMetadata>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone)]
pub struct RevenueRecoveryMetadata {
pub max_retry_count: u16,
pub billing_connector_retry_threshold: u16,
pub mca_reference: AccountReferenceMap,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Deserialize)]
pub struct ExternalVaultConnectorMetadata {
pub proxy_url: common_utils::types::Url,
pub certificate: Secret<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone)]
pub struct AccountReferenceMap {
pub recovery_to_billing: HashMap<id_type::MerchantConnectorAccountId, String>,
pub billing_to_recovery: HashMap<String, id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v2")]
impl AccountReferenceMap {
pub fn new(
hash_map: HashMap<id_type::MerchantConnectorAccountId, String>,
) -> Result<Self, api_error_response::ApiErrorResponse> {
Self::validate(&hash_map)?;
let recovery_to_billing = hash_map.clone();
let mut billing_to_recovery = HashMap::new();
for (key, value) in &hash_map {
billing_to_recovery.insert(value.clone(), key.clone());
}
Ok(Self {
recovery_to_billing,
billing_to_recovery,
})
}
fn validate(
hash_map: &HashMap<id_type::MerchantConnectorAccountId, String>,
) -> Result<(), api_error_response::ApiErrorResponse> {
let mut seen_values = std::collections::HashSet::new(); // To check uniqueness of values
for value in hash_map.values() {
if !seen_values.insert(value.clone()) {
return Err(api_error_response::ApiErrorResponse::InvalidRequestData {
message: "Duplicate account reference IDs found in Recovery feature metadata. Each account reference ID must be unique.".to_string(),
});
}
}
Ok(())
}
}
#[cfg(feature = "v2")]
/// Holds the payment methods enabled for a connector
pub struct FlattenedPaymentMethodsEnabled {
pub payment_methods_enabled: Vec<PaymentMethodsEnabledForConnector>,
}
#[cfg(feature = "v2")]
impl FlattenedPaymentMethodsEnabled {
/// This functions flattens the payment methods enabled from the connector accounts
/// Retains the connector name and payment method in every flattened element
pub fn from_payment_connectors_list(payment_connectors: Vec<MerchantConnectorAccount>) -> Self {
let payment_methods_enabled_flattened_with_connector = payment_connectors
.into_iter()
.map(|connector| {
(
connector
.payment_methods_enabled
.clone()
.unwrap_or_default(),
connector.connector_name,
connector.get_id(),
)
})
.flat_map(
|(payment_method_enabled, connector, merchant_connector_id)| {
payment_method_enabled
.into_iter()
.flat_map(move |payment_method| {
let request_payment_methods_enabled =
payment_method.payment_method_subtypes.unwrap_or_default();
let length = request_payment_methods_enabled.len();
request_payment_methods_enabled
.into_iter()
.zip(std::iter::repeat_n(
(
connector,
merchant_connector_id.clone(),
payment_method.payment_method_type,
),
length,
))
})
},
)
.map(
|(request_payment_methods, (connector, merchant_connector_id, payment_method))| {
PaymentMethodsEnabledForConnector {
payment_methods_enabled: request_payment_methods,
connector,
payment_method,
merchant_connector_id,
}
},
)
.collect();
Self {
payment_methods_enabled: payment_methods_enabled_flattened_with_connector,
}
}
}
#[cfg(feature = "v1")]
#[derive(Debug)]
pub enum MerchantConnectorAccountUpdate {
Update {
connector_type: Option<enums::ConnectorType>,
connector_name: Option<String>,
connector_account_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
test_mode: Option<bool>,
disabled: Option<bool>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
payment_methods_enabled: Option<Vec<pii::SecretSerdeValue>>,
metadata: Option<pii::SecretSerdeValue>,
frm_configs: Option<Vec<pii::SecretSerdeValue>>,
connector_webhook_details: Box<Option<pii::SecretSerdeValue>>,
applepay_verified_domains: Option<Vec<String>>,
pm_auth_config: Box<Option<pii::SecretSerdeValue>>,
connector_label: Option<String>,
status: Option<enums::ConnectorStatus>,
connector_wallets_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
additional_merchant_data: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
},
ConnectorWalletDetailsUpdate {
connector_wallets_details: Encryptable<pii::SecretSerdeValue>,
},
}
#[cfg(feature = "v2")]
#[derive(Debug)]
pub enum MerchantConnectorAccountUpdate {
Update {
connector_type: Option<enums::ConnectorType>,
connector_account_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
disabled: Option<bool>,
payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>,
metadata: Option<pii::SecretSerdeValue>,
frm_configs: Option<Vec<pii::SecretSerdeValue>>,
connector_webhook_details: Box<Option<pii::SecretSerdeValue>>,
applepay_verified_domains: Option<Vec<String>>,
pm_auth_config: Box<Option<pii::SecretSerdeValue>>,
connector_label: Option<String>,
status: Option<enums::ConnectorStatus>,
connector_wallets_details: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
additional_merchant_data: Box<Option<Encryptable<pii::SecretSerdeValue>>>,
feature_metadata: Box<Option<MerchantConnectorAccountFeatureMetadata>>,
},
ConnectorWalletDetailsUpdate {
connector_wallets_details: Encryptable<pii::SecretSerdeValue>,
},
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl behaviour::Conversion for MerchantConnectorAccount {
type DstType = storage::MerchantConnectorAccount;
type NewDstType = storage::MerchantConnectorAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(storage::MerchantConnectorAccount {
merchant_id: self.merchant_id,
connector_name: self.connector_name,
connector_account_details: self.connector_account_details.into(),
test_mode: self.test_mode,
disabled: self.disabled,
merchant_connector_id: self.merchant_connector_id.clone(),
id: Some(self.merchant_connector_id),
payment_methods_enabled: self.payment_methods_enabled,
connector_type: self.connector_type,
metadata: self.metadata,
frm_configs: None,
frm_config: self.frm_configs,
business_country: self.business_country,
business_label: self.business_label,
connector_label: self.connector_label,
business_sub_label: self.business_sub_label,
created_at: self.created_at,
modified_at: self.modified_at,
connector_webhook_details: self.connector_webhook_details,
profile_id: Some(self.profile_id),
applepay_verified_domains: self.applepay_verified_domains,
pm_auth_config: self.pm_auth_config,
status: self.status,
connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),
version: self.version,
})
}
async fn convert_back(
state: &KeyManagerState,
other: Self::DstType,
key: &Secret<Vec<u8>>,
_key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let identifier = Identifier::Merchant(other.merchant_id.clone());
let decrypted_data = crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::BatchDecrypt(EncryptedMerchantConnectorAccount::to_encryptable(
EncryptedMerchantConnectorAccount {
connector_account_details: other.connector_account_details,
additional_merchant_data: other.additional_merchant_data,
connector_wallets_details: other.connector_wallets_details,
},
)),
identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector account details".to_string(),
})?;
let decrypted_data = EncryptedMerchantConnectorAccount::from_encryptable(decrypted_data)
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector account details".to_string(),
})?;
Ok(Self {
merchant_id: other.merchant_id,
connector_name: other.connector_name,
connector_account_details: decrypted_data.connector_account_details,
test_mode: other.test_mode,
disabled: other.disabled,
merchant_connector_id: other.merchant_connector_id,
payment_methods_enabled: other.payment_methods_enabled,
connector_type: other.connector_type,
metadata: other.metadata,
frm_configs: other.frm_config,
business_country: other.business_country,
business_label: other.business_label,
connector_label: other.connector_label,
business_sub_label: other.business_sub_label,
created_at: other.created_at,
modified_at: other.modified_at,
connector_webhook_details: other.connector_webhook_details,
profile_id: other
.profile_id
.ok_or(ValidationError::MissingRequiredField {
field_name: "profile_id".to_string(),
})?,
applepay_verified_domains: other.applepay_verified_domains,
pm_auth_config: other.pm_auth_config,
status: other.status,
connector_wallets_details: decrypted_data.connector_wallets_details,
additional_merchant_data: decrypted_data.additional_merchant_data,
version: other.version,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(Self::NewDstType {
merchant_id: Some(self.merchant_id),
connector_name: Some(self.connector_name),
connector_account_details: Some(self.connector_account_details.into()),
test_mode: self.test_mode,
disabled: self.disabled,
merchant_connector_id: self.merchant_connector_id.clone(),
id: Some(self.merchant_connector_id),
payment_methods_enabled: self.payment_methods_enabled,
connector_type: Some(self.connector_type),
metadata: self.metadata,
frm_configs: None,
frm_config: self.frm_configs,
business_country: self.business_country,
business_label: self.business_label,
connector_label: self.connector_label,
business_sub_label: self.business_sub_label,
created_at: now,
modified_at: now,
connector_webhook_details: self.connector_webhook_details,
profile_id: Some(self.profile_id),
applepay_verified_domains: self.applepay_verified_domains,
pm_auth_config: self.pm_auth_config,
status: self.status,
connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),
version: self.version,
})
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl behaviour::Conversion for MerchantConnectorAccount {
type DstType = storage::MerchantConnectorAccount;
type NewDstType = storage::MerchantConnectorAccountNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(storage::MerchantConnectorAccount {
id: self.id,
merchant_id: self.merchant_id,
connector_name: self.connector_name,
connector_account_details: self.connector_account_details.into(),
disabled: self.disabled,
payment_methods_enabled: self.payment_methods_enabled,
connector_type: self.connector_type,
metadata: self.metadata,
frm_config: self.frm_configs,
connector_label: self.connector_label,
created_at: self.created_at,
modified_at: self.modified_at,
connector_webhook_details: self.connector_webhook_details,
profile_id: self.profile_id,
applepay_verified_domains: self.applepay_verified_domains,
pm_auth_config: self.pm_auth_config,
status: self.status,
connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),
version: self.version,
feature_metadata: self.feature_metadata.map(From::from),
})
}
async fn convert_back(
state: &KeyManagerState,
other: Self::DstType,
key: &Secret<Vec<u8>>,
_key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError> {
let identifier = Identifier::Merchant(other.merchant_id.clone());
let decrypted_data = crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::BatchDecrypt(EncryptedMerchantConnectorAccount::to_encryptable(
EncryptedMerchantConnectorAccount {
connector_account_details: other.connector_account_details,
additional_merchant_data: other.additional_merchant_data,
connector_wallets_details: other.connector_wallets_details,
},
)),
identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector account details".to_string(),
})?;
let decrypted_data = EncryptedMerchantConnectorAccount::from_encryptable(decrypted_data)
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting connector account details".to_string(),
})?;
Ok(Self {
id: other.id,
merchant_id: other.merchant_id,
connector_name: other.connector_name,
connector_account_details: decrypted_data.connector_account_details,
disabled: other.disabled,
payment_methods_enabled: other.payment_methods_enabled,
connector_type: other.connector_type,
metadata: other.metadata,
frm_configs: other.frm_config,
connector_label: other.connector_label,
created_at: other.created_at,
modified_at: other.modified_at,
connector_webhook_details: other.connector_webhook_details,
profile_id: other.profile_id,
applepay_verified_domains: other.applepay_verified_domains,
pm_auth_config: other.pm_auth_config,
status: other.status,
connector_wallets_details: decrypted_data.connector_wallets_details,
additional_merchant_data: decrypted_data.additional_merchant_data,
version: other.version,
feature_metadata: other.feature_metadata.map(From::from),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(Self::NewDstType {
id: self.id,
merchant_id: Some(self.merchant_id),
connector_name: Some(self.connector_name),
connector_account_details: Some(self.connector_account_details.into()),
disabled: self.disabled,
payment_methods_enabled: self.payment_methods_enabled,
connector_type: Some(self.connector_type),
metadata: self.metadata,
frm_config: self.frm_configs,
connector_label: self.connector_label,
created_at: now,
modified_at: now,
connector_webhook_details: self.connector_webhook_details,
profile_id: self.profile_id,
applepay_verified_domains: self.applepay_verified_domains,
pm_auth_config: self.pm_auth_config,
status: self.status,
connector_wallets_details: self.connector_wallets_details.map(Encryption::from),
additional_merchant_data: self.additional_merchant_data.map(|data| data.into()),
version: self.version,
feature_metadata: self.feature_metadata.map(From::from),
})
}
}
#[cfg(feature = "v1")]
impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInternal {
fn from(merchant_connector_account_update: MerchantConnectorAccountUpdate) -> Self {
match merchant_connector_account_update {
MerchantConnectorAccountUpdate::Update {
connector_type,
connector_name,
connector_account_details,
test_mode,
disabled,
merchant_connector_id,
payment_methods_enabled,
metadata,
frm_configs,
connector_webhook_details,
applepay_verified_domains,
pm_auth_config,
connector_label,
status,
connector_wallets_details,
additional_merchant_data,
} => Self {
connector_type,
connector_name,
connector_account_details: connector_account_details.map(Encryption::from),
test_mode,
disabled,
merchant_connector_id,
payment_methods_enabled,
metadata,
frm_configs: None,
frm_config: frm_configs,
modified_at: Some(date_time::now()),
connector_webhook_details: *connector_webhook_details,
applepay_verified_domains,
pm_auth_config: *pm_auth_config,
connector_label,
status,
connector_wallets_details: connector_wallets_details.map(Encryption::from),
additional_merchant_data: additional_merchant_data.map(Encryption::from),
},
MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate {
connector_wallets_details,
} => Self {
connector_wallets_details: Some(Encryption::from(connector_wallets_details)),
connector_type: None,
connector_name: None,
connector_account_details: None,
connector_label: None,
test_mode: None,
disabled: None,
merchant_connector_id: None,
payment_methods_enabled: None,
frm_configs: None,
metadata: None,
modified_at: None,
connector_webhook_details: None,
frm_config: None,
applepay_verified_domains: None,
pm_auth_config: None,
status: None,
additional_merchant_data: None,
},
}
}
}
#[cfg(feature = "v2")]
impl From<MerchantConnectorAccountUpdate> for MerchantConnectorAccountUpdateInternal {
fn from(merchant_connector_account_update: MerchantConnectorAccountUpdate) -> Self {
match merchant_connector_account_update {
MerchantConnectorAccountUpdate::Update {
connector_type,
connector_account_details,
disabled,
payment_methods_enabled,
metadata,
frm_configs,
connector_webhook_details,
applepay_verified_domains,
pm_auth_config,
connector_label,
status,
connector_wallets_details,
additional_merchant_data,
feature_metadata,
} => Self {
connector_type,
connector_account_details: connector_account_details.map(Encryption::from),
disabled,
payment_methods_enabled,
metadata,
frm_config: frm_configs,
modified_at: Some(date_time::now()),
connector_webhook_details: *connector_webhook_details,
applepay_verified_domains,
pm_auth_config: *pm_auth_config,
connector_label,
status,
connector_wallets_details: connector_wallets_details.map(Encryption::from),
additional_merchant_data: additional_merchant_data.map(Encryption::from),
feature_metadata: feature_metadata.map(From::from),
},
MerchantConnectorAccountUpdate::ConnectorWalletDetailsUpdate {
connector_wallets_details,
} => Self {
connector_wallets_details: Some(Encryption::from(connector_wallets_details)),
connector_type: None,
connector_account_details: None,
connector_label: None,
disabled: None,
payment_methods_enabled: None,
metadata: None,
modified_at: None,
connector_webhook_details: None,
frm_config: None,
applepay_verified_domains: None,
pm_auth_config: None,
status: None,
additional_merchant_data: None,
feature_metadata: None,
},
}
}
}
common_utils::create_list_wrapper!(
MerchantConnectorAccounts,
MerchantConnectorAccount,
impl_functions: {
fn filter_and_map<'a, T>(
&'a self,
filter: impl Fn(&'a MerchantConnectorAccount) -> bool,
func: impl Fn(&'a MerchantConnectorAccount) -> T,
) -> rustc_hash::FxHashSet<T>
where
T: std::hash::Hash + Eq,
{
self.0
.iter()
.filter(|mca| filter(mca))
.map(func)
.collect::<rustc_hash::FxHashSet<_>>()
}
pub fn filter_by_profile<'a, T>(
&'a self,
profile_id: &'a id_type::ProfileId,
func: impl Fn(&'a MerchantConnectorAccount) -> T,
) -> rustc_hash::FxHashSet<T>
where
T: std::hash::Hash + Eq,
{
self.filter_and_map(|mca| mca.profile_id == *profile_id, func)
}
#[cfg(feature = "v2")]
pub fn get_connector_and_supporting_payment_method_type_for_session_call(
&self,
) -> Vec<(&MerchantConnectorAccount, common_enums::PaymentMethodType, common_enums::PaymentMethod)> {
// This vector is created to work around lifetimes
let ref_vector = Vec::default();
let connector_and_supporting_payment_method_type = self.iter().flat_map(|connector_account| {
connector_account
.payment_methods_enabled.as_ref()
.unwrap_or(&Vec::default())
.iter()
.flat_map(|payment_method_types| payment_method_types.payment_method_subtypes.as_ref().unwrap_or(&ref_vector).iter().map(|payment_method_subtype| (payment_method_subtype, payment_method_types.payment_method_type)).collect::<Vec<_>>())
.filter(|(payment_method_types_enabled, _)| {
payment_method_types_enabled.payment_experience == Some(api_models::enums::PaymentExperience::InvokeSdkClient)
})
.map(|(payment_method_subtypes, payment_method_type)| {
(connector_account, payment_method_subtypes.payment_method_subtype, payment_method_type)
})
.collect::<Vec<_>>()
}).collect();
connector_and_supporting_payment_method_type
}
pub fn filter_based_on_profile_and_connector_type(
self,
profile_id: &id_type::ProfileId,
connector_type: common_enums::ConnectorType,
) -> Self {
self.into_iter()
.filter(|mca| &mca.profile_id == profile_id && mca.connector_type == connector_type)
.collect()
}
pub fn is_merchant_connector_account_id_in_connector_mandate_details(
&self,
profile_id: Option<&id_type::ProfileId>,
connector_mandate_details: &CommonMandateReference,
) -> bool {
let mca_ids = self
.iter()
.filter(|mca| {
mca.disabled.is_some_and(|disabled| !disabled)
&& profile_id.is_some_and(|profile_id| *profile_id == mca.profile_id)
})
.map(|mca| mca.get_id())
.collect::<std::collections::HashSet<_>>();
connector_mandate_details
.payments
.as_ref()
.as_ref().is_some_and(|payments| {
payments.0.keys().any(|mca_id| mca_ids.contains(mca_id))
})
}
}
);
#[cfg(feature = "v2")]
impl From<MerchantConnectorAccountFeatureMetadata>
for DieselMerchantConnectorAccountFeatureMetadata
{
fn from(feature_metadata: MerchantConnectorAccountFeatureMetadata) -> Self {
let revenue_recovery = feature_metadata.revenue_recovery.map(|recovery_metadata| {
DieselRevenueRecoveryMetadata {
max_retry_count: recovery_metadata.max_retry_count,
billing_connector_retry_threshold: recovery_metadata
.billing_connector_retry_threshold,
billing_account_reference: DieselBillingAccountReference(
recovery_metadata.mca_reference.recovery_to_billing,
),
}
});
Self { revenue_recovery }
}
}
#[cfg(feature = "v2")]
impl From<DieselMerchantConnectorAccountFeatureMetadata>
for MerchantConnectorAccountFeatureMetadata
{
fn from(feature_metadata: DieselMerchantConnectorAccountFeatureMetadata) -> Self {
let revenue_recovery = feature_metadata.revenue_recovery.map(|recovery_metadata| {
let mut billing_to_recovery = HashMap::new();
for (key, value) in &recovery_metadata.billing_account_reference.0 {
billing_to_recovery.insert(value.to_string(), key.clone());
}
RevenueRecoveryMetadata {
max_retry_count: recovery_metadata.max_retry_count,
billing_connector_retry_threshold: recovery_metadata
.billing_connector_retry_threshold,
mca_reference: AccountReferenceMap {
recovery_to_billing: recovery_metadata.billing_account_reference.0,
billing_to_recovery,
},
}
});
Self { revenue_recovery }
}
}
#[async_trait::async_trait]
pub trait MerchantConnectorAccountInterface
where
MerchantConnectorAccount: behaviour::Conversion<
DstType = storage::MerchantConnectorAccount,
NewDstType = storage::MerchantConnectorAccountNew,
>,
{
type Error;
#[cfg(feature = "v1")]
async fn find_merchant_connector_account_by_merchant_id_connector_label(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
connector_label: &str,
key_store: &MerchantKeyStore,
) -> CustomResult<MerchantConnectorAccount, Self::Error>;
#[cfg(feature = "v1")]
async fn find_merchant_connector_account_by_profile_id_connector_name(
&self,
state: &KeyManagerState,
profile_id: &id_type::ProfileId,
connector_name: &str,
key_store: &MerchantKeyStore,
) -> CustomResult<MerchantConnectorAccount, Self::Error>;
#[cfg(feature = "v1")]
async fn find_merchant_connector_account_by_merchant_id_connector_name(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
connector_name: &str,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<MerchantConnectorAccount>, Self::Error>;
async fn insert_merchant_connector_account(
&self,
state: &KeyManagerState,
t: MerchantConnectorAccount,
key_store: &MerchantKeyStore,
) -> CustomResult<MerchantConnectorAccount, Self::Error>;
#[cfg(feature = "v1")]
async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
merchant_connector_id: &id_type::MerchantConnectorAccountId,
key_store: &MerchantKeyStore,
) -> CustomResult<MerchantConnectorAccount, Self::Error>;
#[cfg(feature = "v2")]
async fn find_merchant_connector_account_by_id(
&self,
state: &KeyManagerState,
id: &id_type::MerchantConnectorAccountId,
key_store: &MerchantKeyStore,
) -> CustomResult<MerchantConnectorAccount, Self::Error>;
async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
get_disabled: bool,
key_store: &MerchantKeyStore,
) -> CustomResult<MerchantConnectorAccounts, Self::Error>;
#[cfg(all(feature = "olap", feature = "v2"))]
async fn list_connector_account_by_profile_id(
&self,
state: &KeyManagerState,
profile_id: &id_type::ProfileId,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<MerchantConnectorAccount>, Self::Error>;
async fn list_enabled_connector_accounts_by_profile_id(
&self,
state: &KeyManagerState,
profile_id: &id_type::ProfileId,
key_store: &MerchantKeyStore,
connector_type: common_enums::ConnectorType,
) -> CustomResult<Vec<MerchantConnectorAccount>, Self::Error>;
async fn update_merchant_connector_account(
&self,
state: &KeyManagerState,
this: MerchantConnectorAccount,
merchant_connector_account: MerchantConnectorAccountUpdateInternal,
key_store: &MerchantKeyStore,
) -> CustomResult<MerchantConnectorAccount, Self::Error>;
async fn update_multiple_merchant_connector_accounts(
&self,
this: Vec<(
MerchantConnectorAccount,
MerchantConnectorAccountUpdateInternal,
)>,
) -> CustomResult<(), Self::Error>;
#[cfg(feature = "v1")]
async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
&self,
merchant_id: &id_type::MerchantId,
merchant_connector_id: &id_type::MerchantConnectorAccountId,
) -> CustomResult<bool, Self::Error>;
#[cfg(feature = "v2")]
async fn delete_merchant_connector_account_by_id(
&self,
id: &id_type::MerchantConnectorAccountId,
) -> CustomResult<bool, Self::Error>;
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/merchant_connector_account.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 3,
"num_structs": 7,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_2938545218451679103
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/payments.rs
// Contains: 18 structs, 2 enums
#[cfg(feature = "v2")]
use std::marker::PhantomData;
#[cfg(feature = "v2")]
use api_models::payments::{ConnectorMetadata, SessionToken, VaultSessionDetails};
use common_types::primitive_wrappers;
#[cfg(feature = "v1")]
use common_types::primitive_wrappers::{
AlwaysRequestExtendedAuthorization, EnableOvercaptureBool, RequestExtendedAuthorizationBool,
};
use common_utils::{
self,
crypto::Encryptable,
encryption::Encryption,
errors::CustomResult,
ext_traits::ValueExt,
id_type, pii,
types::{keymanager::ToEncryptable, CreatedBy, MinorUnit},
};
use diesel_models::payment_intent::TaxDetails;
#[cfg(feature = "v2")]
use error_stack::ResultExt;
use masking::Secret;
use router_derive::ToEncryption;
use rustc_hash::FxHashMap;
use serde_json::Value;
use time::PrimitiveDateTime;
pub mod payment_attempt;
pub mod payment_intent;
use common_enums as storage_enums;
#[cfg(feature = "v2")]
use diesel_models::types::{FeatureMetadata, OrderDetailsWithAmount};
use self::payment_attempt::PaymentAttempt;
#[cfg(feature = "v2")]
use crate::{
address::Address, business_profile, customer, errors, merchant_connector_account,
merchant_connector_account::MerchantConnectorAccountTypeDetails, merchant_context,
payment_address, payment_method_data, payment_methods, revenue_recovery, routing,
ApiModelToDieselModelConvertor,
};
#[cfg(feature = "v1")]
use crate::{payment_method_data, RemoteStorageObject};
#[cfg(feature = "v1")]
#[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)]
pub struct PaymentIntent {
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
pub status: storage_enums::IntentStatus,
pub amount: MinorUnit,
pub shipping_cost: Option<MinorUnit>,
pub currency: Option<storage_enums::Currency>,
pub amount_captured: Option<MinorUnit>,
pub customer_id: Option<id_type::CustomerId>,
pub description: Option<String>,
pub return_url: Option<String>,
pub metadata: Option<Value>,
pub connector_id: Option<String>,
pub shipping_address_id: Option<String>,
pub billing_address_id: Option<String>,
pub statement_descriptor_name: Option<String>,
pub statement_descriptor_suffix: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub setup_future_usage: Option<storage_enums::FutureUsage>,
pub off_session: Option<bool>,
pub client_secret: Option<String>,
pub active_attempt: RemoteStorageObject<PaymentAttempt>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
pub allowed_payment_method_types: Option<Value>,
pub connector_metadata: Option<Value>,
pub feature_metadata: Option<Value>,
pub attempt_count: i16,
pub profile_id: Option<id_type::ProfileId>,
pub payment_link_id: Option<String>,
// Denotes the action(approve or reject) taken by merchant in case of manual review.
// Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment
pub merchant_decision: Option<String>,
pub payment_confirm_source: Option<storage_enums::PaymentSource>,
pub updated_by: String,
pub surcharge_applicable: Option<bool>,
pub request_incremental_authorization: Option<storage_enums::RequestIncrementalAuthorization>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
pub fingerprint_id: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub session_expiry: Option<PrimitiveDateTime>,
pub request_external_three_ds_authentication: Option<bool>,
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
#[encrypt]
pub customer_details: Option<Encryptable<Secret<Value>>>,
#[encrypt]
pub billing_details: Option<Encryptable<Secret<Value>>>,
pub merchant_order_reference_id: Option<String>,
#[encrypt]
pub shipping_details: Option<Encryptable<Secret<Value>>>,
pub is_payment_processor_token_flow: Option<bool>,
pub organization_id: id_type::OrganizationId,
pub tax_details: Option<TaxDetails>,
pub skip_external_tax_calculation: Option<bool>,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>,
pub processor_merchant_id: id_type::MerchantId,
pub created_by: Option<CreatedBy>,
pub force_3ds_challenge: Option<bool>,
pub force_3ds_challenge_trigger: Option<bool>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_payment_id_from_merchant: Option<bool>,
pub payment_channel: Option<common_enums::PaymentChannel>,
pub tax_status: Option<storage_enums::TaxStatus>,
pub discount_amount: Option<MinorUnit>,
pub order_date: Option<PrimitiveDateTime>,
pub shipping_amount_tax: Option<MinorUnit>,
pub duty_amount: Option<MinorUnit>,
pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,
pub enable_overcapture: Option<EnableOvercaptureBool>,
pub mit_category: Option<common_enums::MitCategory>,
}
impl PaymentIntent {
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &id_type::PaymentId {
&self.payment_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &id_type::GlobalPaymentId {
&self.id
}
#[cfg(feature = "v2")]
/// This is the url to which the customer will be redirected to, to complete the redirection flow
pub fn create_start_redirection_url(
&self,
base_url: &str,
publishable_key: String,
) -> CustomResult<url::Url, errors::api_error_response::ApiErrorResponse> {
let start_redirection_url = &format!(
"{}/v2/payments/{}/start-redirection?publishable_key={}&profile_id={}",
base_url,
self.get_id().get_string_repr(),
publishable_key,
self.profile_id.get_string_repr()
);
url::Url::parse(start_redirection_url)
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Error creating start redirection url")
}
#[cfg(feature = "v1")]
pub fn get_request_extended_authorization_bool_if_connector_supports(
&self,
connector: common_enums::connector_enums::Connector,
always_request_extended_authorization_optional: Option<AlwaysRequestExtendedAuthorization>,
payment_method_optional: Option<common_enums::PaymentMethod>,
payment_method_type_optional: Option<common_enums::PaymentMethodType>,
) -> Option<RequestExtendedAuthorizationBool> {
use router_env::logger;
let is_extended_authorization_supported_by_connector = || {
let supported_pms = connector.get_payment_methods_supporting_extended_authorization();
let supported_pmts =
connector.get_payment_method_types_supporting_extended_authorization();
// check if payment method or payment method type is supported by the connector
logger::info!(
"Extended Authentication Connector:{:?}, Supported payment methods: {:?}, Supported payment method types: {:?}, Payment method Selected: {:?}, Payment method type Selected: {:?}",
connector,
supported_pms,
supported_pmts,
payment_method_optional,
payment_method_type_optional
);
match (payment_method_optional, payment_method_type_optional) {
(Some(payment_method), Some(payment_method_type)) => {
supported_pms.contains(&payment_method)
&& supported_pmts.contains(&payment_method_type)
}
(Some(payment_method), None) => supported_pms.contains(&payment_method),
(None, Some(payment_method_type)) => supported_pmts.contains(&payment_method_type),
(None, None) => false,
}
};
let intent_request_extended_authorization_optional = self.request_extended_authorization;
let is_extended_authorization_requested = intent_request_extended_authorization_optional
.map(|should_request_extended_authorization| *should_request_extended_authorization)
.or(always_request_extended_authorization_optional.map(
|should_always_request_extended_authorization| {
*should_always_request_extended_authorization
},
));
is_extended_authorization_requested
.map(|requested| {
if requested {
is_extended_authorization_supported_by_connector()
} else {
false
}
})
.map(RequestExtendedAuthorizationBool::from)
}
#[cfg(feature = "v1")]
pub fn get_enable_overcapture_bool_if_connector_supports(
&self,
connector: common_enums::connector_enums::Connector,
always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
capture_method: &Option<common_enums::CaptureMethod>,
) -> Option<EnableOvercaptureBool> {
let is_overcapture_supported_by_connector =
connector.is_overcapture_supported_by_connector();
if matches!(capture_method, Some(common_enums::CaptureMethod::Manual))
&& is_overcapture_supported_by_connector
{
self.enable_overcapture
.or_else(|| always_enable_overcapture.map(EnableOvercaptureBool::from))
} else {
None
}
}
#[cfg(feature = "v2")]
/// This is the url to which the customer will be redirected to, after completing the redirection flow
pub fn create_finish_redirection_url(
&self,
base_url: &str,
publishable_key: &str,
) -> CustomResult<url::Url, errors::api_error_response::ApiErrorResponse> {
let finish_redirection_url = format!(
"{base_url}/v2/payments/{}/finish-redirection/{publishable_key}/{}",
self.id.get_string_repr(),
self.profile_id.get_string_repr()
);
url::Url::parse(&finish_redirection_url)
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Error creating finish redirection url")
}
pub fn parse_and_get_metadata<T>(
&self,
type_name: &'static str,
) -> CustomResult<Option<T>, common_utils::errors::ParsingError>
where
T: for<'de> masking::Deserialize<'de>,
{
self.metadata
.clone()
.map(|metadata| metadata.parse_value(type_name))
.transpose()
}
#[cfg(feature = "v1")]
pub fn merge_metadata(
&self,
request_metadata: Value,
) -> Result<Value, common_utils::errors::ParsingError> {
if !request_metadata.is_null() {
match (&self.metadata, &request_metadata) {
(Some(Value::Object(existing_map)), Value::Object(req_map)) => {
let mut merged = existing_map.clone();
merged.extend(req_map.clone());
Ok(Value::Object(merged))
}
(None, Value::Object(_)) => Ok(request_metadata),
_ => {
router_env::logger::error!(
"Expected metadata to be an object, got: {:?}",
request_metadata
);
Err(common_utils::errors::ParsingError::UnknownError)
}
}
} else {
router_env::logger::error!("Metadata does not contain any key");
Err(common_utils::errors::ParsingError::UnknownError)
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
pub struct AmountDetails {
/// The amount of the order in the lowest denomination of currency
pub order_amount: MinorUnit,
/// The currency of the order
pub currency: common_enums::Currency,
/// The shipping cost of the order. This has to be collected from the merchant
pub shipping_cost: Option<MinorUnit>,
/// Tax details related to the order. This will be calculated by the external tax provider
pub tax_details: Option<TaxDetails>,
/// The action to whether calculate tax by calling external tax provider or not
pub skip_external_tax_calculation: common_enums::TaxCalculationOverride,
/// The action to whether calculate surcharge or not
pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride,
/// The surcharge amount to be added to the order, collected from the merchant
pub surcharge_amount: Option<MinorUnit>,
/// tax on surcharge amount
pub tax_on_surcharge: Option<MinorUnit>,
/// The total amount captured for the order. This is the sum of all the captured amounts for the order.
/// For automatic captures, this will be the same as net amount for the order
pub amount_captured: Option<MinorUnit>,
}
#[cfg(feature = "v2")]
impl AmountDetails {
/// Get the action to whether calculate surcharge or not as a boolean value
fn get_surcharge_action_as_bool(&self) -> bool {
self.skip_surcharge_calculation.as_bool()
}
/// Get the action to whether calculate external tax or not as a boolean value
pub fn get_external_tax_action_as_bool(&self) -> bool {
self.skip_external_tax_calculation.as_bool()
}
/// Calculate the net amount for the order
pub fn calculate_net_amount(&self) -> MinorUnit {
self.order_amount
+ self.shipping_cost.unwrap_or(MinorUnit::zero())
+ self.surcharge_amount.unwrap_or(MinorUnit::zero())
+ self.tax_on_surcharge.unwrap_or(MinorUnit::zero())
}
pub fn create_attempt_amount_details(
&self,
confirm_intent_request: &api_models::payments::PaymentsConfirmIntentRequest,
) -> payment_attempt::AttemptAmountDetails {
let net_amount = self.calculate_net_amount();
let surcharge_amount = match self.skip_surcharge_calculation {
common_enums::SurchargeCalculationOverride::Skip => self.surcharge_amount,
common_enums::SurchargeCalculationOverride::Calculate => None,
};
let tax_on_surcharge = match self.skip_surcharge_calculation {
common_enums::SurchargeCalculationOverride::Skip => self.tax_on_surcharge,
common_enums::SurchargeCalculationOverride::Calculate => None,
};
let order_tax_amount = match self.skip_external_tax_calculation {
common_enums::TaxCalculationOverride::Skip => {
self.tax_details.as_ref().and_then(|tax_details| {
tax_details.get_tax_amount(Some(confirm_intent_request.payment_method_subtype))
})
}
common_enums::TaxCalculationOverride::Calculate => None,
};
payment_attempt::AttemptAmountDetails::from(payment_attempt::AttemptAmountDetailsSetter {
net_amount,
amount_to_capture: None,
surcharge_amount,
tax_on_surcharge,
// This will be updated when we receive response from the connector
amount_capturable: MinorUnit::zero(),
shipping_cost: self.shipping_cost,
order_tax_amount,
})
}
pub fn proxy_create_attempt_amount_details(
&self,
_confirm_intent_request: &api_models::payments::ProxyPaymentsRequest,
) -> payment_attempt::AttemptAmountDetails {
let net_amount = self.calculate_net_amount();
let surcharge_amount = match self.skip_surcharge_calculation {
common_enums::SurchargeCalculationOverride::Skip => self.surcharge_amount,
common_enums::SurchargeCalculationOverride::Calculate => None,
};
let tax_on_surcharge = match self.skip_surcharge_calculation {
common_enums::SurchargeCalculationOverride::Skip => self.tax_on_surcharge,
common_enums::SurchargeCalculationOverride::Calculate => None,
};
let order_tax_amount = match self.skip_external_tax_calculation {
common_enums::TaxCalculationOverride::Skip => self
.tax_details
.as_ref()
.and_then(|tax_details| tax_details.get_tax_amount(None)),
common_enums::TaxCalculationOverride::Calculate => None,
};
payment_attempt::AttemptAmountDetails::from(payment_attempt::AttemptAmountDetailsSetter {
net_amount,
amount_to_capture: None,
surcharge_amount,
tax_on_surcharge,
// This will be updated when we receive response from the connector
amount_capturable: MinorUnit::zero(),
shipping_cost: self.shipping_cost,
order_tax_amount,
})
}
pub fn update_from_request(self, req: &api_models::payments::AmountDetailsUpdate) -> Self {
Self {
order_amount: req
.order_amount()
.unwrap_or(self.order_amount.into())
.into(),
currency: req.currency().unwrap_or(self.currency),
shipping_cost: req.shipping_cost().or(self.shipping_cost),
tax_details: req
.order_tax_amount()
.map(|order_tax_amount| TaxDetails {
default: Some(diesel_models::DefaultTax { order_tax_amount }),
payment_method_type: None,
})
.or(self.tax_details),
skip_external_tax_calculation: req
.skip_external_tax_calculation()
.unwrap_or(self.skip_external_tax_calculation),
skip_surcharge_calculation: req
.skip_surcharge_calculation()
.unwrap_or(self.skip_surcharge_calculation),
surcharge_amount: req.surcharge_amount().or(self.surcharge_amount),
tax_on_surcharge: req.tax_on_surcharge().or(self.tax_on_surcharge),
amount_captured: self.amount_captured,
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, PartialEq, serde::Serialize, ToEncryption)]
pub struct PaymentIntent {
/// The global identifier for the payment intent. This is generated by the system.
/// The format of the global id is `{cell_id:5}_pay_{time_ordered_uuid:32}`.
pub id: id_type::GlobalPaymentId,
/// The identifier for the merchant. This is automatically derived from the api key used to create the payment.
pub merchant_id: id_type::MerchantId,
/// The status of payment intent.
pub status: storage_enums::IntentStatus,
/// The amount related details of the payment
pub amount_details: AmountDetails,
/// The total amount captured for the order. This is the sum of all the captured amounts for the order.
pub amount_captured: Option<MinorUnit>,
/// The identifier for the customer. This is the identifier for the customer in the merchant's system.
pub customer_id: Option<id_type::GlobalCustomerId>,
/// The description of the order. This will be passed to connectors which support description.
pub description: Option<common_utils::types::Description>,
/// The return url for the payment. This is the url to which the user will be redirected after the payment is completed.
pub return_url: Option<common_utils::types::Url>,
/// The metadata for the payment intent. This is the metadata that will be passed to the connectors.
pub metadata: Option<pii::SecretSerdeValue>,
/// The statement descriptor for the order, this will be displayed in the user's bank statement.
pub statement_descriptor: Option<common_utils::types::StatementDescriptor>,
/// The time at which the order was created
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
/// The time at which the order was last modified
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub setup_future_usage: storage_enums::FutureUsage,
/// The active attempt for the payment intent. This is the payment attempt that is currently active for the payment intent.
pub active_attempt_id: Option<id_type::GlobalAttemptId>,
/// This field represents whether there are attempt groups for this payment intent. Used in split payments workflow
pub active_attempt_id_type: common_enums::ActiveAttemptIDType,
/// The ID of the active attempt group for the payment intent
pub active_attempts_group_id: Option<String>,
/// The order details for the payment.
pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>,
/// This is the list of payment method types that are allowed for the payment intent.
/// This field allows the merchant to restrict the payment methods that can be used for the payment intent.
pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>,
/// This metadata contains connector-specific details like Apple Pay certificates, Airwallex data, Noon order category, Braintree merchant account ID, and Adyen testing data
pub connector_metadata: Option<ConnectorMetadata>,
pub feature_metadata: Option<FeatureMetadata>,
/// Number of attempts that have been made for the order
pub attempt_count: i16,
/// The profile id for the payment.
pub profile_id: id_type::ProfileId,
/// The payment link id for the payment. This is generated only if `enable_payment_link` is set to true.
pub payment_link_id: Option<String>,
/// This Denotes the action(approve or reject) taken by merchant in case of manual review.
/// Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment
pub frm_merchant_decision: Option<common_enums::MerchantDecision>,
/// Denotes the last instance which updated the payment
pub updated_by: String,
/// Denotes whether merchant requested for incremental authorization to be enabled for this payment.
pub request_incremental_authorization: storage_enums::RequestIncrementalAuthorization,
/// Denotes whether merchant requested for split payments to be enabled for this payment
pub split_txns_enabled: storage_enums::SplitTxnsEnabled,
/// Denotes the number of authorizations that have been made for the payment.
pub authorization_count: Option<i32>,
/// Denotes the client secret expiry for the payment. This is the time at which the client secret will expire.
#[serde(with = "common_utils::custom_serde::iso8601")]
pub session_expiry: PrimitiveDateTime,
/// Denotes whether merchant requested for 3ds authentication to be enabled for this payment.
pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest,
/// Metadata related to fraud and risk management
pub frm_metadata: Option<pii::SecretSerdeValue>,
/// The details of the customer in a denormalized form. Only a subset of fields are stored.
#[encrypt]
pub customer_details: Option<Encryptable<Secret<Value>>>,
/// The reference id for the order in the merchant's system. This value can be passed by the merchant.
pub merchant_reference_id: Option<id_type::PaymentReferenceId>,
/// The billing address for the order in a denormalized form.
#[encrypt(ty = Value)]
pub billing_address: Option<Encryptable<Address>>,
/// The shipping address for the order in a denormalized form.
#[encrypt(ty = Value)]
pub shipping_address: Option<Encryptable<Address>>,
/// Capture method for the payment
pub capture_method: storage_enums::CaptureMethod,
/// Authentication type that is requested by the merchant for this payment.
pub authentication_type: Option<common_enums::AuthenticationType>,
/// This contains the pre routing results that are done when routing is done during listing the payment methods.
pub prerouting_algorithm: Option<routing::PaymentRoutingInfo>,
/// The organization id for the payment. This is derived from the merchant account
pub organization_id: id_type::OrganizationId,
/// Denotes the request by the merchant whether to enable a payment link for this payment.
pub enable_payment_link: common_enums::EnablePaymentLinkRequest,
/// Denotes the request by the merchant whether to apply MIT exemption for this payment
pub apply_mit_exemption: common_enums::MitExemptionRequest,
/// Denotes whether the customer is present during the payment flow. This information may be used for 3ds authentication
pub customer_present: common_enums::PresenceOfCustomerDuringPayment,
/// Denotes the override for payment link configuration
pub payment_link_config: Option<diesel_models::PaymentLinkConfigRequestForPayments>,
/// The straight through routing algorithm id that is used for this payment. This overrides the default routing algorithm that is configured in business profile.
pub routing_algorithm_id: Option<id_type::RoutingId>,
/// Split Payment Data
pub split_payments: Option<common_types::payments::SplitPaymentsRequest>,
pub force_3ds_challenge: Option<bool>,
pub force_3ds_challenge_trigger: Option<bool>,
/// merchant who owns the credentials of the processor, i.e. processor owner
pub processor_merchant_id: id_type::MerchantId,
/// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard))
pub created_by: Option<CreatedBy>,
/// Indicates if the redirection has to open in the iframe
pub is_iframe_redirection_enabled: Option<bool>,
/// 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>,
/// Denotes whether merchant requested for partial authorization to be enabled for this payment.
pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,
}
#[cfg(feature = "v2")]
impl PaymentIntent {
/// Extract customer_id from payment intent feature metadata
pub fn extract_connector_customer_id_from_payment_intent(
&self,
) -> Result<String, common_utils::errors::ValidationError> {
self.feature_metadata
.as_ref()
.and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref())
.map(|recovery| {
recovery
.billing_connector_payment_details
.connector_customer_id
.clone()
})
.ok_or(
common_utils::errors::ValidationError::MissingRequiredField {
field_name: "connector_customer_id".to_string(),
},
)
}
fn get_payment_method_sub_type(&self) -> Option<common_enums::PaymentMethodType> {
self.feature_metadata
.as_ref()
.and_then(|metadata| metadata.get_payment_method_sub_type())
}
fn get_payment_method_type(&self) -> Option<common_enums::PaymentMethod> {
self.feature_metadata
.as_ref()
.and_then(|metadata| metadata.get_payment_method_type())
}
pub fn get_connector_customer_id_from_feature_metadata(&self) -> Option<String> {
self.feature_metadata
.as_ref()
.and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref())
.map(|recovery_metadata| {
recovery_metadata
.billing_connector_payment_details
.connector_customer_id
.clone()
})
}
pub fn get_billing_merchant_connector_account_id(
&self,
) -> Option<id_type::MerchantConnectorAccountId> {
self.feature_metadata.as_ref().and_then(|feature_metadata| {
feature_metadata.get_billing_merchant_connector_account_id()
})
}
fn get_request_incremental_authorization_value(
request: &api_models::payments::PaymentsCreateIntentRequest,
) -> CustomResult<
common_enums::RequestIncrementalAuthorization,
errors::api_error_response::ApiErrorResponse,
> {
request.request_incremental_authorization
.map(|request_incremental_authorization| {
if request_incremental_authorization == common_enums::RequestIncrementalAuthorization::True {
if request.capture_method == Some(common_enums::CaptureMethod::Automatic) {
Err(errors::api_error_response::ApiErrorResponse::InvalidRequestData { message: "incremental authorization is not supported when capture_method is automatic".to_owned() })?
}
Ok(common_enums::RequestIncrementalAuthorization::True)
} else {
Ok(common_enums::RequestIncrementalAuthorization::False)
}
})
.unwrap_or(Ok(common_enums::RequestIncrementalAuthorization::default()))
}
pub async fn create_domain_model_from_request(
payment_id: &id_type::GlobalPaymentId,
merchant_context: &merchant_context::MerchantContext,
profile: &business_profile::Profile,
request: api_models::payments::PaymentsCreateIntentRequest,
decrypted_payment_intent: DecryptedPaymentIntent,
) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> {
let request_incremental_authorization =
Self::get_request_incremental_authorization_value(&request)?;
let allowed_payment_method_types = request.allowed_payment_method_types;
let session_expiry =
common_utils::date_time::now().saturating_add(time::Duration::seconds(
request.session_expiry.map(i64::from).unwrap_or(
profile
.session_expiry
.unwrap_or(common_utils::consts::DEFAULT_SESSION_EXPIRY),
),
));
let order_details = request.order_details.map(|order_details| {
order_details
.into_iter()
.map(|order_detail| Secret::new(OrderDetailsWithAmount::convert_from(order_detail)))
.collect()
});
Ok(Self {
id: payment_id.clone(),
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
// Intent status would be RequiresPaymentMethod because we are creating a new payment intent
status: common_enums::IntentStatus::RequiresPaymentMethod,
amount_details: AmountDetails::from(request.amount_details),
amount_captured: None,
customer_id: request.customer_id,
description: request.description,
return_url: request.return_url,
metadata: request.metadata,
statement_descriptor: request.statement_descriptor,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
last_synced: None,
setup_future_usage: request.setup_future_usage.unwrap_or_default(),
active_attempt_id: None,
active_attempt_id_type: common_enums::ActiveAttemptIDType::AttemptID,
active_attempts_group_id: None,
order_details,
allowed_payment_method_types,
connector_metadata: request.connector_metadata,
feature_metadata: request.feature_metadata.map(FeatureMetadata::convert_from),
// Attempt count is 0 in create intent as no attempt is made yet
attempt_count: 0,
profile_id: profile.get_id().clone(),
payment_link_id: None,
frm_merchant_decision: None,
updated_by: merchant_context
.get_merchant_account()
.storage_scheme
.to_string(),
request_incremental_authorization,
// Authorization count is 0 in create intent as no authorization is made yet
authorization_count: Some(0),
session_expiry,
request_external_three_ds_authentication: request
.request_external_three_ds_authentication
.unwrap_or_default(),
split_txns_enabled: profile.split_txns_enabled,
frm_metadata: request.frm_metadata,
customer_details: None,
merchant_reference_id: request.merchant_reference_id,
billing_address: decrypted_payment_intent
.billing_address
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode billing address")?,
shipping_address: decrypted_payment_intent
.shipping_address
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode shipping address")?,
capture_method: request.capture_method.unwrap_or_default(),
authentication_type: request.authentication_type,
prerouting_algorithm: None,
organization_id: merchant_context
.get_merchant_account()
.organization_id
.clone(),
enable_payment_link: request.payment_link_enabled.unwrap_or_default(),
apply_mit_exemption: request.apply_mit_exemption.unwrap_or_default(),
customer_present: request.customer_present.unwrap_or_default(),
payment_link_config: request
.payment_link_config
.map(ApiModelToDieselModelConvertor::convert_from),
routing_algorithm_id: request.routing_algorithm_id,
split_payments: None,
force_3ds_challenge: None,
force_3ds_challenge_trigger: None,
processor_merchant_id: merchant_context.get_merchant_account().get_id().clone(),
created_by: None,
is_iframe_redirection_enabled: None,
is_payment_id_from_merchant: None,
enable_partial_authorization: request.enable_partial_authorization,
})
}
pub fn get_revenue_recovery_metadata(
&self,
) -> Option<diesel_models::types::PaymentRevenueRecoveryMetadata> {
self.feature_metadata
.as_ref()
.and_then(|feature_metadata| feature_metadata.payment_revenue_recovery_metadata.clone())
}
pub fn get_feature_metadata(&self) -> Option<FeatureMetadata> {
self.feature_metadata.clone()
}
pub fn create_revenue_recovery_attempt_data(
&self,
revenue_recovery_metadata: api_models::payments::PaymentRevenueRecoveryMetadata,
billing_connector_account: &merchant_connector_account::MerchantConnectorAccount,
card_info: api_models::payments::AdditionalCardInfo,
payment_processor_token: &str,
) -> CustomResult<
revenue_recovery::RevenueRecoveryAttemptData,
errors::api_error_response::ApiErrorResponse,
> {
let merchant_reference_id = self.merchant_reference_id.clone().ok_or_else(|| {
error_stack::report!(
errors::api_error_response::ApiErrorResponse::GenericNotFoundError {
message: "mandate reference id not found".to_string()
}
)
})?;
let connector_account_reference_id = billing_connector_account
.get_account_reference_id_using_payment_merchant_connector_account_id(
revenue_recovery_metadata.active_attempt_payment_connector_id,
)
.ok_or_else(|| {
error_stack::report!(
errors::api_error_response::ApiErrorResponse::GenericNotFoundError {
message: "connector account reference id not found".to_string()
}
)
})?;
Ok(revenue_recovery::RevenueRecoveryAttemptData {
amount: self.amount_details.order_amount,
currency: self.amount_details.currency,
merchant_reference_id,
connector_transaction_id: None, // No connector id
error_code: None,
error_message: None,
processor_payment_method_token: payment_processor_token.to_string(),
connector_customer_id: revenue_recovery_metadata
.billing_connector_payment_details
.connector_customer_id,
connector_account_reference_id,
transaction_created_at: None, // would unwrap_or as now
status: common_enums::AttemptStatus::Started,
payment_method_type: self
.get_payment_method_type()
.unwrap_or(revenue_recovery_metadata.payment_method_type),
payment_method_sub_type: self
.get_payment_method_sub_type()
.unwrap_or(revenue_recovery_metadata.payment_method_subtype),
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
retry_count: None,
invoice_next_billing_time: None,
invoice_billing_started_at_time: None,
// No charge id is present here since it is an internal payment and we didn't call connector yet.
charge_id: None,
card_info: card_info.clone(),
})
}
pub fn get_optional_customer_id(
&self,
) -> CustomResult<Option<id_type::CustomerId>, common_utils::errors::ValidationError> {
self.customer_id
.as_ref()
.map(|customer_id| id_type::CustomerId::try_from(customer_id.clone()))
.transpose()
}
pub fn get_currency(&self) -> storage_enums::Currency {
self.amount_details.currency
}
}
#[cfg(feature = "v1")]
#[derive(Default, Debug, Clone, serde::Serialize)]
pub struct HeaderPayload {
pub payment_confirm_source: Option<common_enums::PaymentSource>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub x_hs_latency: Option<bool>,
pub browser_name: Option<common_enums::BrowserName>,
pub x_client_platform: Option<common_enums::ClientPlatform>,
pub x_merchant_domain: Option<String>,
pub locale: Option<String>,
pub x_app_id: Option<String>,
pub x_redirect_uri: Option<String>,
pub x_reference_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ClickToPayMetaData {
pub dpa_id: String,
pub dpa_name: String,
pub locale: String,
pub acquirer_bin: String,
pub acquirer_merchant_id: String,
pub merchant_category_code: String,
pub merchant_country_code: String,
pub dpa_client_id: Option<String>,
}
// TODO: uncomment fields as necessary
#[cfg(feature = "v2")]
#[derive(Default, Debug, Clone, serde::Serialize)]
pub struct HeaderPayload {
/// The source with which the payment is confirmed.
pub payment_confirm_source: Option<common_enums::PaymentSource>,
// pub client_source: Option<String>,
// pub client_version: Option<String>,
pub x_hs_latency: Option<bool>,
pub browser_name: Option<common_enums::BrowserName>,
pub x_client_platform: Option<common_enums::ClientPlatform>,
pub x_merchant_domain: Option<String>,
pub locale: Option<String>,
pub x_app_id: Option<String>,
pub x_redirect_uri: Option<String>,
pub x_reference_id: Option<String>,
}
impl HeaderPayload {
pub fn with_source(payment_confirm_source: common_enums::PaymentSource) -> Self {
Self {
payment_confirm_source: Some(payment_confirm_source),
..Default::default()
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone)]
pub struct PaymentIntentData<F>
where
F: Clone,
{
pub flow: PhantomData<F>,
pub payment_intent: PaymentIntent,
pub sessions_token: Vec<SessionToken>,
pub client_secret: Option<Secret<String>>,
pub vault_session_details: Option<VaultSessionDetails>,
pub connector_customer_id: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Clone)]
pub struct PaymentAttemptListData<F>
where
F: Clone,
{
pub flow: PhantomData<F>,
pub payment_attempt_list: Vec<PaymentAttempt>,
}
// TODO: Check if this can be merged with existing payment data
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct PaymentConfirmData<F>
where
F: Clone,
{
pub flow: PhantomData<F>,
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
pub payment_method_data: Option<payment_method_data::PaymentMethodData>,
pub payment_address: payment_address::PaymentAddress,
pub mandate_data: Option<api_models::payments::MandateIds>,
pub payment_method: Option<payment_methods::PaymentMethod>,
pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>,
pub external_vault_pmd: Option<payment_method_data::ExternalVaultPaymentMethodData>,
/// The webhook url of the merchant, to which the connector will send the webhook.
pub webhook_url: Option<String>,
}
#[cfg(feature = "v2")]
impl<F: Clone> PaymentConfirmData<F> {
pub fn get_connector_customer_id(
&self,
customer: Option<&customer::Customer>,
merchant_connector_account: &MerchantConnectorAccountTypeDetails,
) -> Option<String> {
match merchant_connector_account {
MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(_) => customer
.and_then(|customer| customer.get_connector_customer_id(merchant_connector_account))
.map(|id| id.to_string())
.or_else(|| {
self.payment_intent
.get_connector_customer_id_from_feature_metadata()
}),
MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None,
}
}
pub fn update_payment_method_data(
&mut self,
payment_method_data: payment_method_data::PaymentMethodData,
) {
self.payment_method_data = Some(payment_method_data);
}
pub fn update_payment_method_and_pm_id(
&mut self,
payment_method_id: id_type::GlobalPaymentMethodId,
payment_method: payment_methods::PaymentMethod,
) {
self.payment_attempt.payment_method_id = Some(payment_method_id);
self.payment_method = Some(payment_method);
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct PaymentStatusData<F>
where
F: Clone,
{
pub flow: PhantomData<F>,
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
pub payment_address: payment_address::PaymentAddress,
pub attempts: Option<Vec<PaymentAttempt>>,
/// Should the payment status be synced with connector
/// This will depend on the payment status and the force sync flag in the request
pub should_sync_with_connector: bool,
pub merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>,
}
#[cfg(feature = "v2")]
#[derive(Clone)]
pub struct PaymentCaptureData<F>
where
F: Clone,
{
pub flow: PhantomData<F>,
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
}
#[cfg(feature = "v2")]
#[derive(Clone)]
pub struct PaymentCancelData<F>
where
F: Clone,
{
pub flow: PhantomData<F>,
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
}
#[cfg(feature = "v2")]
impl<F> PaymentStatusData<F>
where
F: Clone,
{
pub fn get_payment_id(&self) -> &id_type::GlobalPaymentId {
&self.payment_intent.id
}
}
#[cfg(feature = "v2")]
#[derive(Clone)]
pub struct PaymentAttemptRecordData<F>
where
F: Clone,
{
pub flow: PhantomData<F>,
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
pub revenue_recovery_data: RevenueRecoveryData,
pub payment_address: payment_address::PaymentAddress,
}
#[cfg(feature = "v2")]
#[derive(Clone)]
pub struct RevenueRecoveryData {
pub billing_connector_id: id_type::MerchantConnectorAccountId,
pub processor_payment_method_token: String,
pub connector_customer_id: String,
pub retry_count: Option<u16>,
pub invoice_next_billing_time: Option<PrimitiveDateTime>,
pub triggered_by: storage_enums::enums::TriggeredBy,
pub card_network: Option<common_enums::CardNetwork>,
pub card_issuer: Option<String>,
}
#[cfg(feature = "v2")]
impl<F> PaymentAttemptRecordData<F>
where
F: Clone,
{
pub fn get_updated_feature_metadata(
&self,
) -> CustomResult<Option<FeatureMetadata>, errors::api_error_response::ApiErrorResponse> {
let payment_intent_feature_metadata = self.payment_intent.get_feature_metadata();
let revenue_recovery = self.payment_intent.get_revenue_recovery_metadata();
let payment_attempt_connector = self.payment_attempt.connector.clone();
let feature_metadata_first_pg_error_code = revenue_recovery
.as_ref()
.and_then(|data| data.first_payment_attempt_pg_error_code.clone());
let (first_pg_error_code, first_network_advice_code, first_network_decline_code) =
feature_metadata_first_pg_error_code.map_or_else(
|| {
let first_pg_error_code = self
.payment_attempt
.error
.as_ref()
.map(|error| error.code.clone());
let first_network_advice_code = self
.payment_attempt
.error
.as_ref()
.and_then(|error| error.network_advice_code.clone());
let first_network_decline_code = self
.payment_attempt
.error
.as_ref()
.and_then(|error| error.network_decline_code.clone());
(
first_pg_error_code,
first_network_advice_code,
first_network_decline_code,
)
},
|pg_code| {
let advice_code = revenue_recovery
.as_ref()
.and_then(|data| data.first_payment_attempt_network_advice_code.clone());
let decline_code = revenue_recovery
.as_ref()
.and_then(|data| data.first_payment_attempt_network_decline_code.clone());
(Some(pg_code), advice_code, decline_code)
},
);
let billing_connector_payment_method_details = Some(
diesel_models::types::BillingConnectorPaymentMethodDetails::Card(
diesel_models::types::BillingConnectorAdditionalCardInfo {
card_network: self.revenue_recovery_data.card_network.clone(),
card_issuer: self.revenue_recovery_data.card_issuer.clone(),
},
),
);
let payment_revenue_recovery_metadata = match payment_attempt_connector {
Some(connector) => Some(diesel_models::types::PaymentRevenueRecoveryMetadata {
// Update retry count by one.
total_retry_count: revenue_recovery.as_ref().map_or(
self.revenue_recovery_data
.retry_count
.map_or_else(|| 1, |retry_count| retry_count),
|data| (data.total_retry_count + 1),
),
// Since this is an external system call, marking this payment_connector_transmission to ConnectorCallSucceeded.
payment_connector_transmission:
common_enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
billing_connector_id: self.revenue_recovery_data.billing_connector_id.clone(),
active_attempt_payment_connector_id: self
.payment_attempt
.get_attempt_merchant_connector_account_id()?,
billing_connector_payment_details:
diesel_models::types::BillingConnectorPaymentDetails {
payment_processor_token: self
.revenue_recovery_data
.processor_payment_method_token
.clone(),
connector_customer_id: self
.revenue_recovery_data
.connector_customer_id
.clone(),
},
payment_method_type: self.payment_attempt.payment_method_type,
payment_method_subtype: self.payment_attempt.payment_method_subtype,
connector: connector.parse().map_err(|err| {
router_env::logger::error!(?err, "Failed to parse connector string to enum");
errors::api_error_response::ApiErrorResponse::InternalServerError
})?,
invoice_next_billing_time: self.revenue_recovery_data.invoice_next_billing_time,
invoice_billing_started_at_time: self
.revenue_recovery_data
.invoice_next_billing_time,
billing_connector_payment_method_details,
first_payment_attempt_network_advice_code: first_network_advice_code,
first_payment_attempt_network_decline_code: first_network_decline_code,
first_payment_attempt_pg_error_code: first_pg_error_code,
}),
None => Err(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Connector not found in payment attempt")?,
};
Ok(Some(FeatureMetadata {
redirect_response: payment_intent_feature_metadata
.as_ref()
.and_then(|data| data.redirect_response.clone()),
search_tags: payment_intent_feature_metadata
.as_ref()
.and_then(|data| data.search_tags.clone()),
apple_pay_recurring_details: payment_intent_feature_metadata
.as_ref()
.and_then(|data| data.apple_pay_recurring_details.clone()),
payment_revenue_recovery_metadata,
}))
}
}
#[derive(Default, Clone, serde::Serialize, Debug)]
pub struct CardAndNetworkTokenDataForVault {
pub card_data: payment_method_data::Card,
pub network_token: NetworkTokenDataForVault,
}
#[derive(Default, Clone, serde::Serialize, Debug)]
pub struct NetworkTokenDataForVault {
pub network_token_data: payment_method_data::NetworkTokenData,
pub network_token_req_ref_id: String,
}
#[derive(Default, Clone, serde::Serialize, Debug)]
pub struct CardDataForVault {
pub card_data: payment_method_data::Card,
pub network_token_req_ref_id: Option<String>,
}
#[derive(Clone, serde::Serialize, Debug)]
pub enum VaultOperation {
ExistingVaultData(VaultData),
SaveCardData(CardDataForVault),
SaveCardAndNetworkTokenData(Box<CardAndNetworkTokenDataForVault>),
}
impl VaultOperation {
pub fn get_updated_vault_data(
existing_vault_data: Option<&Self>,
payment_method_data: &payment_method_data::PaymentMethodData,
) -> Option<Self> {
match (existing_vault_data, payment_method_data) {
(None, payment_method_data::PaymentMethodData::Card(card)) => {
Some(Self::ExistingVaultData(VaultData::Card(card.clone())))
}
(None, payment_method_data::PaymentMethodData::NetworkToken(nt_data)) => Some(
Self::ExistingVaultData(VaultData::NetworkToken(nt_data.clone())),
),
(Some(Self::ExistingVaultData(vault_data)), payment_method_data) => {
match (vault_data, payment_method_data) {
(
VaultData::Card(card),
payment_method_data::PaymentMethodData::NetworkToken(nt_data),
) => Some(Self::ExistingVaultData(VaultData::CardAndNetworkToken(
Box::new(CardAndNetworkTokenData {
card_data: card.clone(),
network_token_data: nt_data.clone(),
}),
))),
(
VaultData::NetworkToken(nt_data),
payment_method_data::PaymentMethodData::Card(card),
) => Some(Self::ExistingVaultData(VaultData::CardAndNetworkToken(
Box::new(CardAndNetworkTokenData {
card_data: card.clone(),
network_token_data: nt_data.clone(),
}),
))),
_ => Some(Self::ExistingVaultData(vault_data.clone())),
}
}
//payment_method_data is not card or network token
_ => None,
}
}
}
#[derive(Clone, serde::Serialize, Debug)]
pub enum VaultData {
Card(payment_method_data::Card),
NetworkToken(payment_method_data::NetworkTokenData),
CardAndNetworkToken(Box<CardAndNetworkTokenData>),
}
#[derive(Default, Clone, serde::Serialize, Debug)]
pub struct CardAndNetworkTokenData {
pub card_data: payment_method_data::Card,
pub network_token_data: payment_method_data::NetworkTokenData,
}
impl VaultData {
pub fn get_card_vault_data(&self) -> Option<payment_method_data::Card> {
match self {
Self::Card(card_data) => Some(card_data.clone()),
Self::NetworkToken(_network_token_data) => None,
Self::CardAndNetworkToken(vault_data) => Some(vault_data.card_data.clone()),
}
}
pub fn get_network_token_data(&self) -> Option<payment_method_data::NetworkTokenData> {
match self {
Self::Card(_card_data) => None,
Self::NetworkToken(network_token_data) => Some(network_token_data.clone()),
Self::CardAndNetworkToken(vault_data) => Some(vault_data.network_token_data.clone()),
}
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/payments.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 18,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-578505191631499505
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/merchant_context.rs
// Contains: 1 structs, 1 enums
pub use crate::{merchant_account::MerchantAccount, merchant_key_store::MerchantKeyStore};
/// `MerchantContext` represents the authentication and operational context for a merchant.
///
/// This enum encapsulates the merchant's account information and cryptographic keys
/// needed for secure operations. Currently supports only normal merchant operations,
/// but the enum structure allows for future expansion to different merchant types for example a
/// **platform** context.
#[derive(Clone, Debug)]
pub enum MerchantContext {
/// Represents a normal operation merchant context.
NormalMerchant(Box<Context>),
}
/// `Context` holds the merchant account details and cryptographic key store.
#[derive(Clone, Debug)]
pub struct Context(pub MerchantAccount, pub MerchantKeyStore);
impl MerchantContext {
pub fn get_merchant_account(&self) -> &MerchantAccount {
match self {
Self::NormalMerchant(merchant_account) => &merchant_account.0,
}
}
pub fn get_merchant_key_store(&self) -> &MerchantKeyStore {
match self {
Self::NormalMerchant(merchant_account) => &merchant_account.1,
}
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/merchant_context.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-6235428715713616719
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/connector_endpoints.rs
// Contains: 10 structs, 0 enums
//! Configs interface
use common_enums::{connector_enums, ApplicationError};
use common_utils::errors::CustomResult;
use masking::Secret;
use router_derive;
use serde::Deserialize;
use crate::errors::api_error_response;
// struct Connectors
#[allow(missing_docs, missing_debug_implementations)]
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct Connectors {
pub aci: ConnectorParams,
pub authipay: ConnectorParams,
pub adyen: AdyenParamsWithThreeBaseUrls,
pub adyenplatform: ConnectorParams,
pub affirm: ConnectorParams,
pub airwallex: ConnectorParams,
pub amazonpay: ConnectorParams,
pub applepay: ConnectorParams,
pub archipel: ConnectorParams,
pub authorizedotnet: ConnectorParams,
pub bambora: ConnectorParams,
pub bamboraapac: ConnectorParams,
pub bankofamerica: ConnectorParams,
pub barclaycard: ConnectorParams,
pub billwerk: ConnectorParams,
pub bitpay: ConnectorParams,
pub blackhawknetwork: ConnectorParams,
pub calida: ConnectorParams,
pub bluesnap: ConnectorParamsWithSecondaryBaseUrl,
pub boku: ConnectorParams,
pub braintree: ConnectorParams,
pub breadpay: ConnectorParams,
pub cashtocode: ConnectorParams,
pub celero: ConnectorParams,
pub chargebee: ConnectorParams,
pub checkbook: ConnectorParams,
pub checkout: ConnectorParams,
pub coinbase: ConnectorParams,
pub coingate: ConnectorParams,
pub cryptopay: ConnectorParams,
pub ctp_mastercard: NoParams,
pub ctp_visa: NoParams,
pub custombilling: NoParams,
pub cybersource: ConnectorParams,
pub datatrans: ConnectorParamsWithSecondaryBaseUrl,
pub deutschebank: ConnectorParams,
pub digitalvirgo: ConnectorParams,
pub dlocal: ConnectorParams,
#[cfg(feature = "dummy_connector")]
pub dummyconnector: ConnectorParams,
pub dwolla: ConnectorParams,
pub ebanx: ConnectorParams,
pub elavon: ConnectorParams,
pub facilitapay: ConnectorParams,
pub finix: ConnectorParams,
pub fiserv: ConnectorParams,
pub fiservemea: ConnectorParams,
pub fiuu: ConnectorParamsWithThreeUrls,
pub flexiti: ConnectorParams,
pub forte: ConnectorParams,
pub getnet: ConnectorParams,
pub gigadat: ConnectorParams,
pub globalpay: ConnectorParams,
pub globepay: ConnectorParams,
pub gocardless: ConnectorParams,
pub gpayments: ConnectorParams,
pub helcim: ConnectorParams,
pub hipay: ConnectorParamsWithThreeUrls,
pub hyperswitch_vault: ConnectorParams,
pub hyperwallet: ConnectorParams,
pub iatapay: ConnectorParams,
pub inespay: ConnectorParams,
pub itaubank: ConnectorParams,
pub jpmorgan: ConnectorParams,
pub juspaythreedsserver: ConnectorParams,
pub cardinal: NoParams,
pub katapult: ConnectorParams,
pub klarna: ConnectorParams,
pub loonio: ConnectorParams,
pub mifinity: ConnectorParams,
pub mollie: ConnectorParams,
pub moneris: ConnectorParams,
pub mpgs: ConnectorParams,
pub multisafepay: ConnectorParams,
pub netcetera: ConnectorParams,
pub nexinets: ConnectorParams,
pub nexixpay: ConnectorParams,
pub nmi: ConnectorParams,
pub nomupay: ConnectorParams,
pub noon: ConnectorParamsWithModeType,
pub nordea: ConnectorParams,
pub novalnet: ConnectorParams,
pub nuvei: ConnectorParams,
pub opayo: ConnectorParams,
pub opennode: ConnectorParams,
pub paybox: ConnectorParamsWithSecondaryBaseUrl,
pub payeezy: ConnectorParams,
pub payload: ConnectorParams,
pub payme: ConnectorParams,
pub payone: ConnectorParams,
pub paypal: ConnectorParams,
pub paysafe: ConnectorParams,
pub paystack: ConnectorParams,
pub paytm: ConnectorParams,
pub payu: ConnectorParams,
pub peachpayments: ConnectorParams,
pub phonepe: ConnectorParams,
pub placetopay: ConnectorParams,
pub plaid: ConnectorParams,
pub powertranz: ConnectorParams,
pub prophetpay: ConnectorParams,
pub rapyd: ConnectorParams,
pub razorpay: ConnectorParamsWithKeys,
pub recurly: ConnectorParams,
pub redsys: ConnectorParams,
pub riskified: ConnectorParams,
pub santander: ConnectorParams,
pub shift4: ConnectorParams,
pub sift: ConnectorParams,
pub silverflow: ConnectorParams,
pub signifyd: ConnectorParams,
pub square: ConnectorParams,
pub stax: ConnectorParams,
pub stripe: ConnectorParamsWithFileUploadUrl,
pub stripebilling: ConnectorParams,
pub taxjar: ConnectorParams,
pub tesouro: ConnectorParams,
pub threedsecureio: ConnectorParams,
pub thunes: ConnectorParams,
pub tokenex: ConnectorParams,
pub tokenio: ConnectorParams,
pub trustpay: ConnectorParamsWithMoreUrls,
pub trustpayments: ConnectorParams,
pub tsys: ConnectorParams,
pub unified_authentication_service: ConnectorParams,
pub vgs: ConnectorParams,
pub volt: ConnectorParams,
pub wellsfargo: ConnectorParams,
pub wellsfargopayout: ConnectorParams,
pub wise: ConnectorParams,
pub worldline: ConnectorParams,
pub worldpay: ConnectorParams,
pub worldpayvantiv: ConnectorParamsWithThreeUrls,
pub worldpayxml: ConnectorParams,
pub xendit: ConnectorParams,
pub zen: ConnectorParams,
pub zsl: ConnectorParams,
}
impl Connectors {
pub fn get_connector_params(
&self,
connector: connector_enums::Connector,
) -> CustomResult<ConnectorParams, api_error_response::ApiErrorResponse> {
match connector {
connector_enums::Connector::Recurly => Ok(self.recurly.clone()),
connector_enums::Connector::Stripebilling => Ok(self.stripebilling.clone()),
connector_enums::Connector::Chargebee => Ok(self.chargebee.clone()),
_ => Err(api_error_response::ApiErrorResponse::IncorrectConnectorNameGiven.into()),
}
}
}
/// struct ConnectorParams
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct ConnectorParams {
/// base url
pub base_url: String,
/// secondary base url
pub secondary_base_url: Option<String>,
}
///struct No Param for connectors with no params
#[derive(Debug, Deserialize, Clone, Default)]
pub struct NoParams;
impl NoParams {
/// function to satisfy connector param validation macro
pub fn validate(&self, _parent_field: &str) -> Result<(), ApplicationError> {
Ok(())
}
}
/// struct ConnectorParamsWithKeys
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct ConnectorParamsWithKeys {
/// base url
pub base_url: String,
/// api key
pub api_key: Secret<String>,
/// merchant ID
pub merchant_id: Secret<String>,
}
/// struct ConnectorParamsWithModeType
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct ConnectorParamsWithModeType {
/// base url
pub base_url: String,
/// secondary base url
pub secondary_base_url: Option<String>,
/// Can take values like Test or Live for Noon
pub key_mode: String,
}
/// struct ConnectorParamsWithMoreUrls
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct ConnectorParamsWithMoreUrls {
/// base url
pub base_url: String,
/// base url for bank redirects
pub base_url_bank_redirects: String,
}
/// struct ConnectorParamsWithFileUploadUrl
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct ConnectorParamsWithFileUploadUrl {
/// base url
pub base_url: String,
/// base url for file upload
pub base_url_file_upload: String,
}
/// struct ConnectorParamsWithThreeBaseUrls
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct AdyenParamsWithThreeBaseUrls {
/// base url
pub base_url: String,
/// secondary base url
#[cfg(feature = "payouts")]
pub payout_base_url: String,
/// third base url
pub dispute_base_url: String,
}
/// struct ConnectorParamsWithSecondaryBaseUrl
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct ConnectorParamsWithSecondaryBaseUrl {
/// base url
pub base_url: String,
/// secondary base url
pub secondary_base_url: String,
}
/// struct ConnectorParamsWithThreeUrls
#[derive(Debug, Deserialize, Clone, Default, router_derive::ConfigValidate)]
#[serde(default)]
pub struct ConnectorParamsWithThreeUrls {
/// base url
pub base_url: String,
/// secondary base url
pub secondary_base_url: String,
/// third base url
pub third_base_url: String,
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/connector_endpoints.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 10,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_2744224804307599317
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/subscription.rs
// Contains: 2 structs, 1 enums
use common_utils::{
errors::{CustomResult, ValidationError},
events::ApiEventMetric,
generate_id_with_default_len,
pii::SecretSerdeValue,
types::keymanager::{self, KeyManagerState},
};
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret};
use time::PrimitiveDateTime;
use crate::{errors::api_error_response::ApiErrorResponse, merchant_key_store::MerchantKeyStore};
const SECRET_SPLIT: &str = "_secret";
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ClientSecret(String);
impl ClientSecret {
pub fn new(secret: String) -> Self {
Self(secret)
}
pub fn get_subscription_id(&self) -> error_stack::Result<String, ApiErrorResponse> {
let sub_id = self
.0
.split(SECRET_SPLIT)
.next()
.ok_or(ApiErrorResponse::MissingRequiredField {
field_name: "client_secret",
})
.attach_printable("Failed to extract subscription_id from client_secret")?;
Ok(sub_id.to_string())
}
}
impl std::fmt::Display for ClientSecret {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.0)
}
}
impl ApiEventMetric for ClientSecret {}
impl From<api_models::subscription::ClientSecret> for ClientSecret {
fn from(api_secret: api_models::subscription::ClientSecret) -> Self {
Self::new(api_secret.as_str().to_string())
}
}
impl From<ClientSecret> for api_models::subscription::ClientSecret {
fn from(domain_secret: ClientSecret) -> Self {
Self::new(domain_secret.to_string())
}
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct Subscription {
pub id: common_utils::id_type::SubscriptionId,
pub status: String,
pub billing_processor: Option<String>,
pub payment_method_id: Option<String>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub client_secret: Option<String>,
pub connector_subscription_id: Option<String>,
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: common_utils::id_type::CustomerId,
pub metadata: Option<SecretSerdeValue>,
pub created_at: PrimitiveDateTime,
pub modified_at: PrimitiveDateTime,
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_reference_id: Option<String>,
pub plan_id: Option<String>,
pub item_price_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub enum SubscriptionStatus {
Active,
Created,
InActive,
Pending,
Trial,
Paused,
Unpaid,
Onetime,
Cancelled,
Failed,
}
impl std::fmt::Display for SubscriptionStatus {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Active => write!(f, "Active"),
Self::Created => write!(f, "Created"),
Self::InActive => write!(f, "InActive"),
Self::Pending => write!(f, "Pending"),
Self::Trial => write!(f, "Trial"),
Self::Paused => write!(f, "Paused"),
Self::Unpaid => write!(f, "Unpaid"),
Self::Onetime => write!(f, "Onetime"),
Self::Cancelled => write!(f, "Cancelled"),
Self::Failed => write!(f, "Failed"),
}
}
}
impl Subscription {
pub fn generate_and_set_client_secret(&mut self) -> Secret<String> {
let client_secret =
generate_id_with_default_len(&format!("{}_secret", self.id.get_string_repr()));
self.client_secret = Some(client_secret.clone());
Secret::new(client_secret)
}
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for Subscription {
type DstType = diesel_models::subscription::Subscription;
type NewDstType = diesel_models::subscription::SubscriptionNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let now = common_utils::date_time::now();
Ok(diesel_models::subscription::Subscription {
id: self.id,
status: self.status,
billing_processor: self.billing_processor,
payment_method_id: self.payment_method_id,
merchant_connector_id: self.merchant_connector_id,
client_secret: self.client_secret,
connector_subscription_id: self.connector_subscription_id,
merchant_id: self.merchant_id,
customer_id: self.customer_id,
metadata: self.metadata.map(|m| m.expose()),
created_at: now,
modified_at: now,
profile_id: self.profile_id,
merchant_reference_id: self.merchant_reference_id,
plan_id: self.plan_id,
item_price_id: self.item_price_id,
})
}
async fn convert_back(
_state: &KeyManagerState,
item: Self::DstType,
_key: &Secret<Vec<u8>>,
_key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
Ok(Self {
id: item.id,
status: item.status,
billing_processor: item.billing_processor,
payment_method_id: item.payment_method_id,
merchant_connector_id: item.merchant_connector_id,
client_secret: item.client_secret,
connector_subscription_id: item.connector_subscription_id,
merchant_id: item.merchant_id,
customer_id: item.customer_id,
metadata: item.metadata.map(SecretSerdeValue::new),
created_at: item.created_at,
modified_at: item.modified_at,
profile_id: item.profile_id,
merchant_reference_id: item.merchant_reference_id,
plan_id: item.plan_id,
item_price_id: item.item_price_id,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::subscription::SubscriptionNew::new(
self.id,
self.status,
self.billing_processor,
self.payment_method_id,
self.merchant_connector_id,
self.client_secret,
self.connector_subscription_id,
self.merchant_id,
self.customer_id,
self.metadata,
self.profile_id,
self.merchant_reference_id,
self.plan_id,
self.item_price_id,
))
}
}
#[async_trait::async_trait]
pub trait SubscriptionInterface {
type Error;
async fn insert_subscription_entry(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
subscription_new: Subscription,
) -> CustomResult<Subscription, Self::Error>;
async fn find_by_merchant_id_subscription_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
subscription_id: String,
) -> CustomResult<Subscription, Self::Error>;
async fn update_subscription_entry(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
subscription_id: String,
data: SubscriptionUpdate,
) -> CustomResult<Subscription, Self::Error>;
}
pub struct SubscriptionUpdate {
pub connector_subscription_id: Option<String>,
pub payment_method_id: Option<String>,
pub status: Option<String>,
pub modified_at: PrimitiveDateTime,
pub plan_id: Option<String>,
pub item_price_id: Option<String>,
}
impl SubscriptionUpdate {
pub fn new(
connector_subscription_id: Option<String>,
payment_method_id: Option<Secret<String>>,
status: Option<String>,
plan_id: Option<String>,
item_price_id: Option<String>,
) -> Self {
Self {
connector_subscription_id,
payment_method_id: payment_method_id.map(|pmid| pmid.peek().clone()),
status,
modified_at: common_utils::date_time::now(),
plan_id,
item_price_id,
}
}
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for SubscriptionUpdate {
type DstType = diesel_models::subscription::SubscriptionUpdate;
type NewDstType = diesel_models::subscription::SubscriptionUpdate;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::subscription::SubscriptionUpdate {
connector_subscription_id: self.connector_subscription_id,
payment_method_id: self.payment_method_id,
status: self.status,
modified_at: self.modified_at,
plan_id: self.plan_id,
item_price_id: self.item_price_id,
})
}
async fn convert_back(
_state: &KeyManagerState,
item: Self::DstType,
_key: &Secret<Vec<u8>>,
_key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
Ok(Self {
connector_subscription_id: item.connector_subscription_id,
payment_method_id: item.payment_method_id,
status: item.status,
modified_at: item.modified_at,
plan_id: item.plan_id,
item_price_id: item.item_price_id,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::subscription::SubscriptionUpdate {
connector_subscription_id: self.connector_subscription_id,
payment_method_id: self.payment_method_id,
status: self.status,
modified_at: self.modified_at,
plan_id: self.plan_id,
item_price_id: self.item_price_id,
})
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/subscription.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-771751598370408119
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/address.rs
// Contains: 3 structs, 0 enums
use masking::{PeekInterface, Secret};
#[derive(Default, Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct Address {
pub address: Option<AddressDetails>,
pub phone: Option<PhoneDetails>,
pub email: Option<common_utils::pii::Email>,
}
impl masking::SerializableSecret for Address {}
impl Address {
/// Unify the address, giving priority to `self` when details are present in both
pub fn unify_address(&self, other: Option<&Self>) -> Self {
let other_address_details = other.and_then(|address| address.address.as_ref());
Self {
address: self
.address
.as_ref()
.map(|address| address.unify_address_details(other_address_details))
.or(other_address_details.cloned()),
email: self
.email
.clone()
.or(other.and_then(|other| other.email.clone())),
phone: {
self.phone
.clone()
.and_then(|phone_details| {
if phone_details.number.is_some() {
Some(phone_details)
} else {
None
}
})
.or_else(|| other.and_then(|other| other.phone.clone()))
},
}
}
}
#[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq)]
pub struct AddressDetails {
pub city: Option<String>,
pub country: Option<common_enums::CountryAlpha2>,
pub line1: Option<Secret<String>>,
pub line2: Option<Secret<String>>,
pub line3: Option<Secret<String>>,
pub zip: Option<Secret<String>>,
pub state: Option<Secret<String>>,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub origin_zip: Option<Secret<String>>,
}
impl AddressDetails {
pub fn get_optional_full_name(&self) -> Option<Secret<String>> {
match (self.first_name.as_ref(), self.last_name.as_ref()) {
(Some(first_name), Some(last_name)) => Some(Secret::new(format!(
"{} {}",
first_name.peek(),
last_name.peek()
))),
(Some(name), None) | (None, Some(name)) => Some(name.to_owned()),
_ => None,
}
}
/// Unify the address details, giving priority to `self` when details are present in both
pub fn unify_address_details(&self, other: Option<&Self>) -> Self {
if let Some(other) = other {
let (first_name, last_name) = if self
.first_name
.as_ref()
.is_some_and(|first_name| !first_name.peek().trim().is_empty())
{
(self.first_name.clone(), self.last_name.clone())
} else {
(other.first_name.clone(), other.last_name.clone())
};
Self {
first_name,
last_name,
city: self.city.clone().or(other.city.clone()),
country: self.country.or(other.country),
line1: self.line1.clone().or(other.line1.clone()),
line2: self.line2.clone().or(other.line2.clone()),
line3: self.line3.clone().or(other.line3.clone()),
zip: self.zip.clone().or(other.zip.clone()),
state: self.state.clone().or(other.state.clone()),
origin_zip: self.origin_zip.clone().or(other.origin_zip.clone()),
}
} else {
self.clone()
}
}
}
#[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct PhoneDetails {
pub number: Option<Secret<String>>,
pub country_code: Option<String>,
}
impl From<api_models::payments::Address> for Address {
fn from(address: api_models::payments::Address) -> Self {
Self {
address: address.address.map(AddressDetails::from),
phone: address.phone.map(PhoneDetails::from),
email: address.email,
}
}
}
impl From<api_models::payments::AddressDetails> for AddressDetails {
fn from(address: api_models::payments::AddressDetails) -> Self {
Self {
city: address.city,
country: address.country,
line1: address.line1,
line2: address.line2,
line3: address.line3,
zip: address.zip,
state: address.state,
first_name: address.first_name,
last_name: address.last_name,
origin_zip: address.origin_zip,
}
}
}
impl From<api_models::payments::PhoneDetails> for PhoneDetails {
fn from(phone: api_models::payments::PhoneDetails) -> Self {
Self {
number: phone.number,
country_code: phone.country_code,
}
}
}
impl From<Address> for api_models::payments::Address {
fn from(address: Address) -> Self {
Self {
address: address
.address
.map(api_models::payments::AddressDetails::from),
phone: address.phone.map(api_models::payments::PhoneDetails::from),
email: address.email,
}
}
}
impl From<AddressDetails> for api_models::payments::AddressDetails {
fn from(address: AddressDetails) -> Self {
Self {
city: address.city,
country: address.country,
line1: address.line1,
line2: address.line2,
line3: address.line3,
zip: address.zip,
state: address.state,
first_name: address.first_name,
last_name: address.last_name,
origin_zip: address.origin_zip,
}
}
}
impl From<PhoneDetails> for api_models::payments::PhoneDetails {
fn from(phone: PhoneDetails) -> Self {
Self {
number: phone.number,
country_code: phone.country_code,
}
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/address.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 3,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-4106817757083272893
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/bulk_tokenization.rs
// Contains: 4 structs, 1 enums
use api_models::{payment_methods as payment_methods_api, payments as payments_api};
use cards::CardNumber;
use common_enums as enums;
use common_utils::{
errors,
ext_traits::OptionExt,
id_type, pii,
transformers::{ForeignFrom, ForeignTryFrom},
};
use error_stack::report;
use crate::{
address::{Address, AddressDetails, PhoneDetails},
router_request_types::CustomerDetails,
};
#[derive(Debug)]
pub struct CardNetworkTokenizeRequest {
pub data: TokenizeDataRequest,
pub customer: CustomerDetails,
pub billing: Option<Address>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payment_method_issuer: Option<String>,
}
#[derive(Debug)]
pub enum TokenizeDataRequest {
Card(TokenizeCardRequest),
ExistingPaymentMethod(TokenizePaymentMethodRequest),
}
#[derive(Clone, Debug)]
pub struct TokenizeCardRequest {
pub raw_card_number: CardNumber,
pub card_expiry_month: masking::Secret<String>,
pub card_expiry_year: masking::Secret<String>,
pub card_cvc: Option<masking::Secret<String>>,
pub card_holder_name: Option<masking::Secret<String>>,
pub nick_name: Option<masking::Secret<String>>,
pub card_issuing_country: Option<String>,
pub card_network: Option<enums::CardNetwork>,
pub card_issuer: Option<String>,
pub card_type: Option<payment_methods_api::CardType>,
}
#[derive(Clone, Debug)]
pub struct TokenizePaymentMethodRequest {
pub payment_method_id: String,
pub card_cvc: Option<masking::Secret<String>>,
}
#[derive(Default, Debug, serde::Deserialize, serde::Serialize)]
pub struct CardNetworkTokenizeRecord {
// Card details
pub raw_card_number: Option<CardNumber>,
pub card_expiry_month: Option<masking::Secret<String>>,
pub card_expiry_year: Option<masking::Secret<String>>,
pub card_cvc: Option<masking::Secret<String>>,
pub card_holder_name: Option<masking::Secret<String>>,
pub nick_name: Option<masking::Secret<String>>,
pub card_issuing_country: Option<String>,
pub card_network: Option<enums::CardNetwork>,
pub card_issuer: Option<String>,
pub card_type: Option<payment_methods_api::CardType>,
// Payment method details
pub payment_method_id: Option<String>,
pub payment_method_type: Option<payment_methods_api::CardType>,
pub payment_method_issuer: Option<String>,
// Customer details
pub customer_id: id_type::CustomerId,
#[serde(rename = "name")]
pub customer_name: Option<masking::Secret<String>>,
#[serde(rename = "email")]
pub customer_email: Option<pii::Email>,
#[serde(rename = "phone")]
pub customer_phone: Option<masking::Secret<String>>,
#[serde(rename = "phone_country_code")]
pub customer_phone_country_code: Option<String>,
#[serde(rename = "tax_registration_id")]
pub customer_tax_registration_id: Option<masking::Secret<String>>,
// Billing details
pub billing_address_city: Option<String>,
pub billing_address_country: Option<enums::CountryAlpha2>,
pub billing_address_line1: Option<masking::Secret<String>>,
pub billing_address_line2: Option<masking::Secret<String>>,
pub billing_address_line3: Option<masking::Secret<String>>,
pub billing_address_zip: Option<masking::Secret<String>>,
pub billing_address_state: Option<masking::Secret<String>>,
pub billing_address_first_name: Option<masking::Secret<String>>,
pub billing_address_last_name: Option<masking::Secret<String>>,
pub billing_phone_number: Option<masking::Secret<String>>,
pub billing_phone_country_code: Option<String>,
pub billing_email: Option<pii::Email>,
// Other details
pub line_number: Option<u64>,
pub merchant_id: Option<id_type::MerchantId>,
}
impl ForeignFrom<&CardNetworkTokenizeRecord> for payments_api::CustomerDetails {
fn foreign_from(record: &CardNetworkTokenizeRecord) -> Self {
Self {
id: record.customer_id.clone(),
name: record.customer_name.clone(),
email: record.customer_email.clone(),
phone: record.customer_phone.clone(),
phone_country_code: record.customer_phone_country_code.clone(),
tax_registration_id: record.customer_tax_registration_id.clone(),
}
}
}
impl ForeignFrom<&CardNetworkTokenizeRecord> for payments_api::Address {
fn foreign_from(record: &CardNetworkTokenizeRecord) -> Self {
Self {
address: Some(payments_api::AddressDetails {
first_name: record.billing_address_first_name.clone(),
last_name: record.billing_address_last_name.clone(),
line1: record.billing_address_line1.clone(),
line2: record.billing_address_line2.clone(),
line3: record.billing_address_line3.clone(),
city: record.billing_address_city.clone(),
zip: record.billing_address_zip.clone(),
state: record.billing_address_state.clone(),
country: record.billing_address_country,
origin_zip: None,
}),
phone: Some(payments_api::PhoneDetails {
number: record.billing_phone_number.clone(),
country_code: record.billing_phone_country_code.clone(),
}),
email: record.billing_email.clone(),
}
}
}
impl ForeignTryFrom<CardNetworkTokenizeRecord> for payment_methods_api::CardNetworkTokenizeRequest {
type Error = error_stack::Report<errors::ValidationError>;
fn foreign_try_from(record: CardNetworkTokenizeRecord) -> Result<Self, Self::Error> {
let billing = Some(payments_api::Address::foreign_from(&record));
let customer = payments_api::CustomerDetails::foreign_from(&record);
let merchant_id = record.merchant_id.get_required_value("merchant_id")?;
match (
record.raw_card_number,
record.card_expiry_month,
record.card_expiry_year,
record.payment_method_id,
) {
(Some(raw_card_number), Some(card_expiry_month), Some(card_expiry_year), None) => {
Ok(Self {
merchant_id,
data: payment_methods_api::TokenizeDataRequest::Card(
payment_methods_api::TokenizeCardRequest {
raw_card_number,
card_expiry_month,
card_expiry_year,
card_cvc: record.card_cvc,
card_holder_name: record.card_holder_name,
nick_name: record.nick_name,
card_issuing_country: record.card_issuing_country,
card_network: record.card_network,
card_issuer: record.card_issuer,
card_type: record.card_type.clone(),
},
),
billing,
customer,
metadata: None,
payment_method_issuer: record.payment_method_issuer,
})
}
(None, None, None, Some(payment_method_id)) => Ok(Self {
merchant_id,
data: payment_methods_api::TokenizeDataRequest::ExistingPaymentMethod(
payment_methods_api::TokenizePaymentMethodRequest {
payment_method_id,
card_cvc: record.card_cvc,
},
),
billing,
customer,
metadata: None,
payment_method_issuer: record.payment_method_issuer,
}),
_ => Err(report!(errors::ValidationError::InvalidValue {
message: "Invalid record in bulk tokenization - expected one of card details or payment method details".to_string()
})),
}
}
}
impl ForeignFrom<&TokenizeCardRequest> for payment_methods_api::MigrateCardDetail {
fn foreign_from(card: &TokenizeCardRequest) -> Self {
Self {
card_number: masking::Secret::new(card.raw_card_number.get_card_no()),
card_exp_month: card.card_expiry_month.clone(),
card_exp_year: card.card_expiry_year.clone(),
card_holder_name: card.card_holder_name.clone(),
nick_name: card.nick_name.clone(),
card_issuing_country: card.card_issuing_country.clone(),
card_network: card.card_network.clone(),
card_issuer: card.card_issuer.clone(),
card_type: card
.card_type
.as_ref()
.map(|card_type| card_type.to_string()),
}
}
}
impl ForeignTryFrom<CustomerDetails> for payments_api::CustomerDetails {
type Error = error_stack::Report<errors::ValidationError>;
fn foreign_try_from(customer: CustomerDetails) -> Result<Self, Self::Error> {
Ok(Self {
id: customer.customer_id.get_required_value("customer_id")?,
name: customer.name,
email: customer.email,
phone: customer.phone,
phone_country_code: customer.phone_country_code,
tax_registration_id: customer.tax_registration_id,
})
}
}
impl ForeignFrom<payment_methods_api::CardNetworkTokenizeRequest> for CardNetworkTokenizeRequest {
fn foreign_from(req: payment_methods_api::CardNetworkTokenizeRequest) -> Self {
Self {
data: TokenizeDataRequest::foreign_from(req.data),
customer: CustomerDetails::foreign_from(req.customer),
billing: req.billing.map(ForeignFrom::foreign_from),
metadata: req.metadata,
payment_method_issuer: req.payment_method_issuer,
}
}
}
impl ForeignFrom<payment_methods_api::TokenizeDataRequest> for TokenizeDataRequest {
fn foreign_from(req: payment_methods_api::TokenizeDataRequest) -> Self {
match req {
payment_methods_api::TokenizeDataRequest::Card(card) => {
Self::Card(TokenizeCardRequest {
raw_card_number: card.raw_card_number,
card_expiry_month: card.card_expiry_month,
card_expiry_year: card.card_expiry_year,
card_cvc: card.card_cvc,
card_holder_name: card.card_holder_name,
nick_name: card.nick_name,
card_issuing_country: card.card_issuing_country,
card_network: card.card_network,
card_issuer: card.card_issuer,
card_type: card.card_type,
})
}
payment_methods_api::TokenizeDataRequest::ExistingPaymentMethod(pm) => {
Self::ExistingPaymentMethod(TokenizePaymentMethodRequest {
payment_method_id: pm.payment_method_id,
card_cvc: pm.card_cvc,
})
}
}
}
}
impl ForeignFrom<payments_api::CustomerDetails> for CustomerDetails {
fn foreign_from(req: payments_api::CustomerDetails) -> Self {
Self {
customer_id: Some(req.id),
name: req.name,
email: req.email,
phone: req.phone,
phone_country_code: req.phone_country_code,
tax_registration_id: req.tax_registration_id,
}
}
}
impl ForeignFrom<payments_api::Address> for Address {
fn foreign_from(req: payments_api::Address) -> Self {
Self {
address: req.address.map(ForeignFrom::foreign_from),
phone: req.phone.map(ForeignFrom::foreign_from),
email: req.email,
}
}
}
impl ForeignFrom<payments_api::AddressDetails> for AddressDetails {
fn foreign_from(req: payments_api::AddressDetails) -> Self {
Self {
city: req.city,
country: req.country,
line1: req.line1,
line2: req.line2,
line3: req.line3,
zip: req.zip,
state: req.state,
first_name: req.first_name,
last_name: req.last_name,
origin_zip: req.origin_zip,
}
}
}
impl ForeignFrom<payments_api::PhoneDetails> for PhoneDetails {
fn foreign_from(req: payments_api::PhoneDetails) -> Self {
Self {
number: req.number,
country_code: req.country_code,
}
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/bulk_tokenization.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 4,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-5880454141130917788
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/type_encryption.rs
// Contains: 1 structs, 1 enums
use async_trait::async_trait;
use common_utils::{
crypto,
encryption::Encryption,
errors::{self, CustomResult},
ext_traits::AsyncExt,
metrics::utils::record_operation_time,
types::keymanager::{Identifier, KeyManagerState},
};
use encrypt::TypeEncryption;
use masking::Secret;
use router_env::{instrument, tracing};
use rustc_hash::FxHashMap;
mod encrypt {
use async_trait::async_trait;
use common_utils::{
crypto,
encryption::Encryption,
errors::{self, CustomResult},
ext_traits::ByteSliceExt,
keymanager::call_encryption_service,
transformers::{ForeignFrom, ForeignTryFrom},
types::keymanager::{
BatchDecryptDataResponse, BatchEncryptDataRequest, BatchEncryptDataResponse,
DecryptDataResponse, EncryptDataRequest, EncryptDataResponse, Identifier,
KeyManagerState, TransientBatchDecryptDataRequest, TransientDecryptDataRequest,
},
};
use error_stack::ResultExt;
use http::Method;
use masking::{PeekInterface, Secret};
use router_env::{instrument, logger, tracing};
use rustc_hash::FxHashMap;
use super::{metrics, EncryptedJsonType};
#[async_trait]
pub trait TypeEncryption<
T,
V: crypto::EncodeMessage + crypto::DecodeMessage,
S: masking::Strategy<T>,
>: Sized
{
async fn encrypt_via_api(
state: &KeyManagerState,
masked_data: Secret<T, S>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError>;
async fn decrypt_via_api(
state: &KeyManagerState,
encrypted_data: Encryption,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError>;
async fn encrypt(
masked_data: Secret<T, S>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError>;
async fn decrypt(
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError>;
async fn batch_encrypt_via_api(
state: &KeyManagerState,
masked_data: FxHashMap<String, Secret<T, S>>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>;
async fn batch_decrypt_via_api(
state: &KeyManagerState,
encrypted_data: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>;
async fn batch_encrypt(
masked_data: FxHashMap<String, Secret<T, S>>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>;
async fn batch_decrypt(
encrypted_data: FxHashMap<String, Encryption>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError>;
}
fn is_encryption_service_enabled(_state: &KeyManagerState) -> bool {
#[cfg(feature = "encryption_service")]
{
_state.enabled
}
#[cfg(not(feature = "encryption_service"))]
{
false
}
}
#[async_trait]
impl<
V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static,
S: masking::Strategy<String> + Send + Sync,
> TypeEncryption<String, V, S> for crypto::Encryptable<Secret<String, S>>
{
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt_via_api(
state: &KeyManagerState,
masked_data: Secret<String, S>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
EncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
EncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))),
Err(err) => {
logger::error!("Encryption error {:?}", err);
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Encryption");
Self::encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt_via_api(
state: &KeyManagerState,
encrypted_data: Encryption,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
DecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(decrypted_data) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::DecodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt(
masked_data: Secret<String, S>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
let encrypted_data = crypt_algo.encode_message(key, masked_data.peek().as_bytes())?;
Ok(Self::new(masked_data, encrypted_data.into()))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt(
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
let encrypted = encrypted_data.into_inner();
let data = crypt_algo.decode_message(key, encrypted.clone())?;
let value: String = std::str::from_utf8(&data)
.change_context(errors::CryptoError::DecodingFailed)?
.to_string();
Ok(Self::new(value.into(), encrypted))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt_via_api(
state: &KeyManagerState,
masked_data: FxHashMap<String, Secret<String, S>>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
BatchEncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
BatchEncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))),
Err(err) => {
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::error!("Encryption error {:?}", err);
logger::info!("Fall back to Application Encryption");
Self::batch_encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt_via_api(
state: &KeyManagerState,
encrypted_data: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
BatchDecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(decrypted_data) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::DecodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt(
masked_data: FxHashMap<String, Secret<String, S>>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
masked_data
.into_iter()
.map(|(k, v)| {
Ok((
k,
Self::new(
v.clone(),
crypt_algo.encode_message(key, v.peek().as_bytes())?.into(),
),
))
})
.collect()
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt(
encrypted_data: FxHashMap<String, Encryption>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
encrypted_data
.into_iter()
.map(|(k, v)| {
let data = crypt_algo.decode_message(key, v.clone().into_inner())?;
let value: String = std::str::from_utf8(&data)
.change_context(errors::CryptoError::DecodingFailed)?
.to_string();
Ok((k, Self::new(value.into(), v.into_inner())))
})
.collect()
}
}
#[async_trait]
impl<
V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static,
S: masking::Strategy<serde_json::Value> + Send + Sync,
> TypeEncryption<serde_json::Value, V, S>
for crypto::Encryptable<Secret<serde_json::Value, S>>
{
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt_via_api(
state: &KeyManagerState,
masked_data: Secret<serde_json::Value, S>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
EncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
EncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))),
Err(err) => {
logger::error!("Encryption error {:?}", err);
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Encryption");
Self::encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt_via_api(
state: &KeyManagerState,
encrypted_data: Encryption,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
DecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(decrypted_data) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::EncodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt(
masked_data: Secret<serde_json::Value, S>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
let data = serde_json::to_vec(&masked_data.peek())
.change_context(errors::CryptoError::DecodingFailed)?;
let encrypted_data = crypt_algo.encode_message(key, &data)?;
Ok(Self::new(masked_data, encrypted_data.into()))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt(
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
let encrypted = encrypted_data.into_inner();
let data = crypt_algo.decode_message(key, encrypted.clone())?;
let value: serde_json::Value = serde_json::from_slice(&data)
.change_context(errors::CryptoError::DecodingFailed)?;
Ok(Self::new(value.into(), encrypted))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt_via_api(
state: &KeyManagerState,
masked_data: FxHashMap<String, Secret<serde_json::Value, S>>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
BatchEncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
BatchEncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))),
Err(err) => {
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::error!("Encryption error {:?}", err);
logger::info!("Fall back to Application Encryption");
Self::batch_encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt_via_api(
state: &KeyManagerState,
encrypted_data: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
BatchDecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(decrypted_data) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::DecodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt(
masked_data: FxHashMap<String, Secret<serde_json::Value, S>>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
masked_data
.into_iter()
.map(|(k, v)| {
let data = serde_json::to_vec(v.peek())
.change_context(errors::CryptoError::DecodingFailed)?;
Ok((
k,
Self::new(v, crypt_algo.encode_message(key, &data)?.into()),
))
})
.collect()
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt(
encrypted_data: FxHashMap<String, Encryption>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
encrypted_data
.into_iter()
.map(|(k, v)| {
let data = crypt_algo.decode_message(key, v.clone().into_inner().clone())?;
let value: serde_json::Value = serde_json::from_slice(&data)
.change_context(errors::CryptoError::DecodingFailed)?;
Ok((k, Self::new(value.into(), v.into_inner())))
})
.collect()
}
}
impl<T> EncryptedJsonType<T>
where
T: std::fmt::Debug + Clone + serde::Serialize + serde::de::DeserializeOwned,
{
fn serialize_json_bytes(&self) -> CustomResult<Secret<Vec<u8>>, errors::CryptoError> {
common_utils::ext_traits::Encode::encode_to_vec(self.inner())
.change_context(errors::CryptoError::EncodingFailed)
.attach_printable("Failed to JSON serialize data before encryption")
.map(Secret::new)
}
fn deserialize_json_bytes<S>(
bytes: Secret<Vec<u8>>,
) -> CustomResult<Secret<Self, S>, errors::ParsingError>
where
S: masking::Strategy<Self>,
{
bytes
.peek()
.as_slice()
.parse_struct::<T>(std::any::type_name::<T>())
.map(|result| Secret::new(Self::from(result)))
.attach_printable("Failed to JSON deserialize data after decryption")
}
}
#[async_trait]
impl<
T: std::fmt::Debug + Clone + serde::Serialize + serde::de::DeserializeOwned + Send,
V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static,
S: masking::Strategy<EncryptedJsonType<T>> + Send + Sync,
> TypeEncryption<EncryptedJsonType<T>, V, S>
for crypto::Encryptable<Secret<EncryptedJsonType<T>, S>>
{
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt_via_api(
state: &KeyManagerState,
masked_data: Secret<EncryptedJsonType<T>, S>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
let data_bytes = EncryptedJsonType::serialize_json_bytes(masked_data.peek())?;
let result: crypto::Encryptable<Secret<Vec<u8>>> =
TypeEncryption::encrypt_via_api(state, data_bytes, identifier, key, crypt_algo)
.await?;
Ok(Self::new(masked_data, result.into_encrypted()))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt_via_api(
state: &KeyManagerState,
encrypted_data: Encryption,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
let result: crypto::Encryptable<Secret<Vec<u8>>> =
TypeEncryption::decrypt_via_api(state, encrypted_data, identifier, key, crypt_algo)
.await?;
result
.deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes)
.change_context(errors::CryptoError::DecodingFailed)
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt(
masked_data: Secret<EncryptedJsonType<T>, S>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
let data_bytes = EncryptedJsonType::serialize_json_bytes(masked_data.peek())?;
let result: crypto::Encryptable<Secret<Vec<u8>>> =
TypeEncryption::encrypt(data_bytes, key, crypt_algo).await?;
Ok(Self::new(masked_data, result.into_encrypted()))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt(
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
let result: crypto::Encryptable<Secret<Vec<u8>>> =
TypeEncryption::decrypt(encrypted_data, key, crypt_algo).await?;
result
.deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes)
.change_context(errors::CryptoError::DecodingFailed)
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt_via_api(
state: &KeyManagerState,
masked_data: FxHashMap<String, Secret<EncryptedJsonType<T>, S>>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
let hashmap_capacity = masked_data.len();
let data_bytes = masked_data.iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let value_bytes = EncryptedJsonType::serialize_json_bytes(value.peek())?;
map.insert(key.to_owned(), value_bytes);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> =
TypeEncryption::batch_encrypt_via_api(
state, data_bytes, identifier, key, crypt_algo,
)
.await?;
let result_hashmap = result.into_iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let original_value = masked_data
.get(&key)
.ok_or(errors::CryptoError::EncodingFailed)
.attach_printable_lazy(|| {
format!("Failed to find {key} in input hashmap")
})?;
map.insert(
key,
Self::new(original_value.clone(), value.into_encrypted()),
);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
Ok(result_hashmap)
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt_via_api(
state: &KeyManagerState,
encrypted_data: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> =
TypeEncryption::batch_decrypt_via_api(
state,
encrypted_data,
identifier,
key,
crypt_algo,
)
.await?;
let hashmap_capacity = result.len();
let result_hashmap = result.into_iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let deserialized_value = value
.deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes)
.change_context(errors::CryptoError::DecodingFailed)?;
map.insert(key, deserialized_value);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
Ok(result_hashmap)
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt(
masked_data: FxHashMap<String, Secret<EncryptedJsonType<T>, S>>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
let hashmap_capacity = masked_data.len();
let data_bytes = masked_data.iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let value_bytes = EncryptedJsonType::serialize_json_bytes(value.peek())?;
map.insert(key.to_owned(), value_bytes);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> =
TypeEncryption::batch_encrypt(data_bytes, key, crypt_algo).await?;
let result_hashmap = result.into_iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let original_value = masked_data
.get(&key)
.ok_or(errors::CryptoError::EncodingFailed)
.attach_printable_lazy(|| {
format!("Failed to find {key} in input hashmap")
})?;
map.insert(
key,
Self::new(original_value.clone(), value.into_encrypted()),
);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
Ok(result_hashmap)
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt(
encrypted_data: FxHashMap<String, Encryption>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
let result: FxHashMap<String, crypto::Encryptable<Secret<Vec<u8>>>> =
TypeEncryption::batch_decrypt(encrypted_data, key, crypt_algo).await?;
let hashmap_capacity = result.len();
let result_hashmap = result.into_iter().try_fold(
FxHashMap::with_capacity_and_hasher(hashmap_capacity, Default::default()),
|mut map, (key, value)| {
let deserialized_value = value
.deserialize_inner_value(EncryptedJsonType::deserialize_json_bytes)
.change_context(errors::CryptoError::DecodingFailed)?;
map.insert(key, deserialized_value);
Ok::<_, error_stack::Report<errors::CryptoError>>(map)
},
)?;
Ok(result_hashmap)
}
}
#[async_trait]
impl<
V: crypto::DecodeMessage + crypto::EncodeMessage + Send + 'static,
S: masking::Strategy<Vec<u8>> + Send + Sync,
> TypeEncryption<Vec<u8>, V, S> for crypto::Encryptable<Secret<Vec<u8>, S>>
{
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt_via_api(
state: &KeyManagerState,
masked_data: Secret<Vec<u8>, S>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
EncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
EncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data.clone(), response))),
Err(err) => {
logger::error!("Encryption error {:?}", err);
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Encryption");
Self::encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt_via_api(
state: &KeyManagerState,
encrypted_data: Encryption,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
DecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(decrypted_data) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), decrypted_data))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::DecodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn encrypt(
masked_data: Secret<Vec<u8>, S>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
let encrypted_data = crypt_algo.encode_message(key, masked_data.peek())?;
Ok(Self::new(masked_data, encrypted_data.into()))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn decrypt(
encrypted_data: Encryption,
key: &[u8],
crypt_algo: V,
) -> CustomResult<Self, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
let encrypted = encrypted_data.into_inner();
let data = crypt_algo.decode_message(key, encrypted.clone())?;
Ok(Self::new(data.into(), encrypted))
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt_via_api(
state: &KeyManagerState,
masked_data: FxHashMap<String, Secret<Vec<u8>, S>>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_encrypt(masked_data, key, crypt_algo).await
} else {
let result: Result<
BatchEncryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/encrypt",
BatchEncryptDataRequest::from((masked_data.clone(), identifier)),
)
.await;
match result {
Ok(response) => Ok(ForeignFrom::foreign_from((masked_data, response))),
Err(err) => {
metrics::ENCRYPTION_API_FAILURES.add(1, &[]);
logger::error!("Encryption error {:?}", err);
logger::info!("Fall back to Application Encryption");
Self::batch_encrypt(masked_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt_via_api(
state: &KeyManagerState,
encrypted_data: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
// If encryption service is not enabled, fall back to application encryption or else call encryption service
if !is_encryption_service_enabled(state) {
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
} else {
let result: Result<
BatchDecryptDataResponse,
error_stack::Report<errors::KeyManagerClientError>,
> = call_encryption_service(
state,
Method::POST,
"data/decrypt",
TransientBatchDecryptDataRequest::from((encrypted_data.clone(), identifier)),
)
.await;
let decrypted = match result {
Ok(response) => {
ForeignTryFrom::foreign_try_from((encrypted_data.clone(), response))
}
Err(err) => {
logger::error!("Decryption error {:?}", err);
Err(err.change_context(errors::CryptoError::DecodingFailed))
}
};
match decrypted {
Ok(de) => Ok(de),
Err(_) => {
metrics::DECRYPTION_API_FAILURES.add(1, &[]);
logger::info!("Fall back to Application Decryption");
Self::batch_decrypt(encrypted_data, key, crypt_algo).await
}
}
}
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_encrypt(
masked_data: FxHashMap<String, Secret<Vec<u8>, S>>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_ENCRYPTION_COUNT.add(1, &[]);
masked_data
.into_iter()
.map(|(k, v)| {
Ok((
k,
Self::new(v.clone(), crypt_algo.encode_message(key, v.peek())?.into()),
))
})
.collect()
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all)]
async fn batch_decrypt(
encrypted_data: FxHashMap<String, Encryption>,
key: &[u8],
crypt_algo: V,
) -> CustomResult<FxHashMap<String, Self>, errors::CryptoError> {
metrics::APPLICATION_DECRYPTION_COUNT.add(1, &[]);
encrypted_data
.into_iter()
.map(|(k, v)| {
Ok((
k,
Self::new(
crypt_algo
.decode_message(key, v.clone().into_inner().clone())?
.into(),
v.into_inner(),
),
))
})
.collect()
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct EncryptedJsonType<T>(T);
impl<T> EncryptedJsonType<T> {
pub fn inner(&self) -> &T {
&self.0
}
pub fn into_inner(self) -> T {
self.0
}
}
impl<T> From<T> for EncryptedJsonType<T> {
fn from(value: T) -> Self {
Self(value)
}
}
impl<T> std::ops::Deref for EncryptedJsonType<T> {
type Target = T;
fn deref(&self) -> &Self::Target {
self.inner()
}
}
/// Type alias for `Option<Encryptable<Secret<EncryptedJsonType<T>>>>`
pub type OptionalEncryptableJsonType<T> = Option<crypto::Encryptable<Secret<EncryptedJsonType<T>>>>;
pub trait Lift<U> {
type SelfWrapper<T>;
type OtherWrapper<T, E>;
fn lift<Func, E, V>(self, func: Func) -> Self::OtherWrapper<V, E>
where
Func: Fn(Self::SelfWrapper<U>) -> Self::OtherWrapper<V, E>;
}
impl<U> Lift<U> for Option<U> {
type SelfWrapper<T> = Option<T>;
type OtherWrapper<T, E> = CustomResult<Option<T>, E>;
fn lift<Func, E, V>(self, func: Func) -> Self::OtherWrapper<V, E>
where
Func: Fn(Self::SelfWrapper<U>) -> Self::OtherWrapper<V, E>,
{
func(self)
}
}
#[async_trait]
pub trait AsyncLift<U> {
type SelfWrapper<T>;
type OtherWrapper<T, E>;
async fn async_lift<Func, F, E, V>(self, func: Func) -> Self::OtherWrapper<V, E>
where
Func: Fn(Self::SelfWrapper<U>) -> F + Send + Sync,
F: futures::Future<Output = Self::OtherWrapper<V, E>> + Send;
}
#[async_trait]
impl<U, V: Lift<U> + Lift<U, SelfWrapper<U> = V> + Send> AsyncLift<U> for V {
type SelfWrapper<T> = <V as Lift<U>>::SelfWrapper<T>;
type OtherWrapper<T, E> = <V as Lift<U>>::OtherWrapper<T, E>;
async fn async_lift<Func, F, E, W>(self, func: Func) -> Self::OtherWrapper<W, E>
where
Func: Fn(Self::SelfWrapper<U>) -> F + Send + Sync,
F: futures::Future<Output = Self::OtherWrapper<W, E>> + Send,
{
func(self).await
}
}
#[inline]
async fn encrypt<E: Clone, S>(
state: &KeyManagerState,
inner: Secret<E, S>,
identifier: Identifier,
key: &[u8],
) -> CustomResult<crypto::Encryptable<Secret<E, S>>, CryptoError>
where
S: masking::Strategy<E>,
crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>,
{
record_operation_time(
crypto::Encryptable::encrypt_via_api(state, inner, identifier, key, crypto::GcmAes256),
&metrics::ENCRYPTION_TIME,
&[],
)
.await
}
#[inline]
async fn batch_encrypt<E: Clone, S>(
state: &KeyManagerState,
inner: FxHashMap<String, Secret<E, S>>,
identifier: Identifier,
key: &[u8],
) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, CryptoError>
where
S: masking::Strategy<E>,
crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>,
{
if !inner.is_empty() {
record_operation_time(
crypto::Encryptable::batch_encrypt_via_api(
state,
inner,
identifier,
key,
crypto::GcmAes256,
),
&metrics::ENCRYPTION_TIME,
&[],
)
.await
} else {
Ok(FxHashMap::default())
}
}
#[inline]
async fn encrypt_optional<E: Clone, S>(
state: &KeyManagerState,
inner: Option<Secret<E, S>>,
identifier: Identifier,
key: &[u8],
) -> CustomResult<Option<crypto::Encryptable<Secret<E, S>>>, CryptoError>
where
Secret<E, S>: Send,
S: masking::Strategy<E>,
crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>,
{
inner
.async_map(|f| encrypt(state, f, identifier, key))
.await
.transpose()
}
#[inline]
async fn decrypt_optional<T: Clone, S: masking::Strategy<T>>(
state: &KeyManagerState,
inner: Option<Encryption>,
identifier: Identifier,
key: &[u8],
) -> CustomResult<Option<crypto::Encryptable<Secret<T, S>>>, CryptoError>
where
crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>,
{
inner
.async_map(|item| decrypt(state, item, identifier, key))
.await
.transpose()
}
#[inline]
async fn decrypt<T: Clone, S: masking::Strategy<T>>(
state: &KeyManagerState,
inner: Encryption,
identifier: Identifier,
key: &[u8],
) -> CustomResult<crypto::Encryptable<Secret<T, S>>, CryptoError>
where
crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>,
{
record_operation_time(
crypto::Encryptable::decrypt_via_api(state, inner, identifier, key, crypto::GcmAes256),
&metrics::DECRYPTION_TIME,
&[],
)
.await
}
#[inline]
async fn batch_decrypt<E: Clone, S>(
state: &KeyManagerState,
inner: FxHashMap<String, Encryption>,
identifier: Identifier,
key: &[u8],
) -> CustomResult<FxHashMap<String, crypto::Encryptable<Secret<E, S>>>, CryptoError>
where
S: masking::Strategy<E>,
crypto::Encryptable<Secret<E, S>>: TypeEncryption<E, crypto::GcmAes256, S>,
{
if !inner.is_empty() {
record_operation_time(
crypto::Encryptable::batch_decrypt_via_api(
state,
inner,
identifier,
key,
crypto::GcmAes256,
),
&metrics::ENCRYPTION_TIME,
&[],
)
.await
} else {
Ok(FxHashMap::default())
}
}
pub enum CryptoOperation<T: Clone, S: masking::Strategy<T>> {
Encrypt(Secret<T, S>),
EncryptOptional(Option<Secret<T, S>>),
Decrypt(Encryption),
DecryptOptional(Option<Encryption>),
BatchEncrypt(FxHashMap<String, Secret<T, S>>),
BatchDecrypt(FxHashMap<String, Encryption>),
}
use errors::CryptoError;
#[derive(router_derive::TryGetEnumVariant)]
#[error(CryptoError::EncodingFailed)]
pub enum CryptoOutput<T: Clone, S: masking::Strategy<T>> {
Operation(crypto::Encryptable<Secret<T, S>>),
OptionalOperation(Option<crypto::Encryptable<Secret<T, S>>>),
BatchOperation(FxHashMap<String, crypto::Encryptable<Secret<T, S>>>),
}
// Do not remove the `skip_all` as the key would be logged otherwise
#[instrument(skip_all, fields(table = table_name))]
pub async fn crypto_operation<T: Clone + Send, S: masking::Strategy<T>>(
state: &KeyManagerState,
table_name: &str,
operation: CryptoOperation<T, S>,
identifier: Identifier,
key: &[u8],
) -> CustomResult<CryptoOutput<T, S>, CryptoError>
where
Secret<T, S>: Send,
crypto::Encryptable<Secret<T, S>>: TypeEncryption<T, crypto::GcmAes256, S>,
{
match operation {
CryptoOperation::Encrypt(data) => {
let data = encrypt(state, data, identifier, key).await?;
Ok(CryptoOutput::Operation(data))
}
CryptoOperation::EncryptOptional(data) => {
let data = encrypt_optional(state, data, identifier, key).await?;
Ok(CryptoOutput::OptionalOperation(data))
}
CryptoOperation::Decrypt(data) => {
let data = decrypt(state, data, identifier, key).await?;
Ok(CryptoOutput::Operation(data))
}
CryptoOperation::DecryptOptional(data) => {
let data = decrypt_optional(state, data, identifier, key).await?;
Ok(CryptoOutput::OptionalOperation(data))
}
CryptoOperation::BatchEncrypt(data) => {
let data = batch_encrypt(state, data, identifier, key).await?;
Ok(CryptoOutput::BatchOperation(data))
}
CryptoOperation::BatchDecrypt(data) => {
let data = batch_decrypt(state, data, identifier, key).await?;
Ok(CryptoOutput::BatchOperation(data))
}
}
}
pub(crate) mod metrics {
use router_env::{counter_metric, global_meter, histogram_metric_f64};
global_meter!(GLOBAL_METER, "ROUTER_API");
// Encryption and Decryption metrics
histogram_metric_f64!(ENCRYPTION_TIME, GLOBAL_METER);
histogram_metric_f64!(DECRYPTION_TIME, GLOBAL_METER);
counter_metric!(ENCRYPTION_API_FAILURES, GLOBAL_METER);
counter_metric!(DECRYPTION_API_FAILURES, GLOBAL_METER);
counter_metric!(APPLICATION_ENCRYPTION_COUNT, GLOBAL_METER);
counter_metric!(APPLICATION_DECRYPTION_COUNT, GLOBAL_METER);
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/type_encryption.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_5041368882750483366
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_data.rs
// Contains: 20 structs, 3 enums
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::{self},
types::MinorUnit,
};
use error_stack::ResultExt;
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
address::AddressDetails, 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, Serialize)]
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 payment_method_type: Option<common_enums::enums::PaymentMethodType>,
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>,
// stores the authorized amount in case of partial authorization
pub authorized_amount: 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<Box<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, Serialize, 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 billing_address_city: Option<String>,
pub merchant_tax_registration_id: Option<Secret<String>>,
pub customer_email: Option<common_utils::pii::Email>,
pub customer_name: Option<Secret<String>>,
pub customer_phone_number: Option<Secret<String>>,
pub customer_phone_country_code: Option<String>,
pub shipping_details: Option<AddressDetails>,
}
impl L2L3Data {
pub fn get_shipping_country(&self) -> Option<common_enums::enums::CountryAlpha2> {
self.shipping_details
.as_ref()
.and_then(|address| address.country)
}
pub fn get_shipping_city(&self) -> Option<String> {
self.shipping_details
.as_ref()
.and_then(|address| address.city.clone())
}
pub fn get_shipping_state(&self) -> Option<Secret<String>> {
self.shipping_details
.as_ref()
.and_then(|address| address.state.clone())
}
pub fn get_shipping_origin_zip(&self) -> Option<Secret<String>> {
self.shipping_details
.as_ref()
.and_then(|address| address.origin_zip.clone())
}
pub fn get_shipping_zip(&self) -> Option<Secret<String>> {
self.shipping_details
.as_ref()
.and_then(|address| address.zip.clone())
}
pub fn get_shipping_address_line1(&self) -> Option<Secret<String>> {
self.shipping_details
.as_ref()
.and_then(|address| address.line1.clone())
}
pub fn get_shipping_address_line2(&self) -> Option<Secret<String>> {
self.shipping_details
.as_ref()
.and_then(|address| address.line2.clone())
}
}
// Different patterns of authentication.
#[derive(Default, Debug, Clone, Deserialize, 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(Deserialize, Serialize, Debug, Clone)]
pub struct AccessTokenAuthenticationResponse {
pub code: Secret<String>,
pub expires: i64,
}
#[derive(Deserialize, Serialize, Debug, Clone)]
pub struct AccessToken {
pub token: Secret<String>,
pub expires: i64,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub enum PaymentMethodToken {
Token(Secret<String>),
ApplePayDecrypt(Box<common_payment_types::ApplePayPredecryptData>),
GooglePayDecrypt(Box<common_payment_types::GPayPredecryptData>),
PazeDecrypt(Box<PazeDecryptedData>),
}
#[derive(Debug, Clone, 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, 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, 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, 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, Deserialize, Serialize)]
#[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, Deserialize, Serialize)]
#[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, Deserialize, Serialize)]
#[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, Deserialize, Serialize)]
#[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, Deserialize, Serialize)]
#[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, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PazePhoneNumber {
pub country_code: Secret<String>,
pub phone_number: Secret<String>,
}
#[derive(Debug, Default, Clone, Serialize)]
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, Serialize)]
pub struct PaymentMethodBalance {
pub amount: MinorUnit,
pub currency: common_enums::enums::Currency,
}
#[derive(Debug, Clone, Serialize, 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, Serialize, 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, Serialize, Deserialize)]
pub struct ExtendedAuthorizationResponseData {
pub extended_authentication_applied:
Option<primitive_wrappers::ExtendedAuthorizationAppliedBool>,
pub capture_before: Option<time::PrimitiveDateTime>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct KlarnaSdkResponse {
pub payment_type: Option<String>,
}
#[derive(Clone, Debug, 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(),
}
}
}
}
fn get_attempt_status_for_db_update(
&self,
payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>,
) -> 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::PaymentCaptureData<router_flow_types::Capture>,
) -> Option<MinorUnit> {
// Based on the status of the response, we can determine the amount capturable
let intent_status = common_enums::IntentStatus::from(self.status);
match intent_status {
// If the status is already succeeded / failed we cannot capture any more amount
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 => None,
common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {
let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
// Invalid statues for this flow
common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
}
}
fn get_captured_amount(
&self,
payment_data: &payments::PaymentCaptureData<router_flow_types::Capture>,
) -> Option<MinorUnit> {
// Based on the status of the response, we can determine the amount capturable
let intent_status = common_enums::IntentStatus::from(self.status);
match intent_status {
// If the status is succeeded then we have captured the whole amount
common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => {
let amount_to_capture = payment_data
.payment_attempt
.amount_details
.get_amount_to_capture();
let amount_captured = amount_to_capture
.unwrap_or(payment_data.payment_attempt.amount_details.get_net_amount());
Some(amount_captured)
}
// No amount is captured
common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::CancelledPostCapture
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),
common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {
let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
// 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,
// Invalid statues for this flow
common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => {
todo!()
}
}
}
}
#[cfg(feature = "v2")]
impl
TrackerPostUpdateObjects<
router_flow_types::PSync,
router_request_types::PaymentsSyncData,
payments::PaymentStatusData<router_flow_types::PSync>,
>
for RouterData<
router_flow_types::PSync,
router_request_types::PaymentsSyncData,
router_response_types::PaymentsResponseData,
>
{
fn get_payment_intent_update(
&self,
payment_data: &payments::PaymentStatusData<router_flow_types::PSync>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentIntentUpdate {
let amount_captured = self.get_captured_amount(payment_data);
match self.response {
Ok(ref _response) => PaymentIntentUpdate::SyncUpdate {
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::SyncUpdate {
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 {
200..=299 => common_enums::enums::AttemptStatus::Failure,
_ => self.status,
},
};
common_enums::IntentStatus::from(attempt_status)
},
amount_captured,
updated_by: storage_scheme.to_string(),
},
}
}
fn get_payment_attempt_update(
&self,
payment_data: &payments::PaymentStatusData<router_flow_types::PSync>,
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.get_attempt_status_for_db_update(payment_data);
PaymentAttemptUpdate::SyncUpdate {
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 = 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 {
200..=299 => common_enums::enums::AttemptStatus::Failure,
_ => 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(),
}
}
}
}
fn get_attempt_status_for_db_update(
&self,
payment_data: &payments::PaymentStatusData<router_flow_types::PSync>,
) -> 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::PaymentStatusData<router_flow_types::PSync>,
) -> Option<MinorUnit> {
let payment_attempt = &payment_data.payment_attempt;
// 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
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 => None,
common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
| common_enums::IntentStatus::PartiallyCaptured => {
let total_amount = payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
// Invalid statues for this flow
common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
};
self.minor_amount_capturable
.or(amount_capturable_from_intent_status)
}
fn get_captured_amount(
&self,
payment_data: &payments::PaymentStatusData<router_flow_types::PSync>,
) -> Option<MinorUnit> {
let payment_attempt = &payment_data.payment_attempt;
// Based on the status of the response, we can determine the amount capturable
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 or amount_to_capture
common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => {
let amount_to_capture = payment_attempt.amount_details.get_amount_to_capture();
let amount_captured =
amount_to_capture.unwrap_or(payment_attempt.amount_details.get_net_amount());
Some(amount_captured)
}
// 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,
common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {
let total_amount = payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
// 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::ExternalVaultProxy,
router_request_types::ExternalVaultProxyPaymentsData,
payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>,
>
for RouterData<
router_flow_types::ExternalVaultProxy,
router_request_types::ExternalVaultProxyPaymentsData,
router_response_types::PaymentsResponseData,
>
{
fn get_payment_intent_update(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentIntentUpdate {
let amount_captured = self.get_captured_amount(payment_data);
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: None,
},
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: None,
},
}
}
fn get_payment_attempt_update(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>,
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::ExternalVaultProxy>,
) -> common_enums::AttemptStatus {
// For this step, consider whatever status was given by the connector module
// We do not need to check for amount captured or amount capturable here because we are authorizing the whole amount
self.status
}
fn get_amount_capturable(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>,
) -> Option<MinorUnit> {
// Based on the status of the response, we can determine the amount capturable
let intent_status = common_enums::IntentStatus::from(self.status);
match intent_status {
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()),
common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::Processing => None,
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation => None,
common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {
let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
}
}
fn get_captured_amount(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::ExternalVaultProxy>,
) -> 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);
match intent_status {
common_enums::IntentStatus::Succeeded | common_enums::IntentStatus::Conflicted => {
let total_amount = payment_data.payment_attempt.amount_details.get_net_amount();
Some(total_amount)
}
common_enums::IntentStatus::Cancelled
| common_enums::IntentStatus::Failed
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
| common_enums::IntentStatus::Expired => Some(MinorUnit::zero()),
common_enums::IntentStatus::RequiresCustomerAction
| common_enums::IntentStatus::RequiresMerchantAction
| common_enums::IntentStatus::Processing => None,
common_enums::IntentStatus::RequiresPaymentMethod
| common_enums::IntentStatus::RequiresConfirmation => None,
common_enums::IntentStatus::RequiresCapture
| common_enums::IntentStatus::CancelledPostCapture => Some(MinorUnit::zero()),
common_enums::IntentStatus::PartiallyCaptured
| common_enums::IntentStatus::PartiallyCapturedAndCapturable => None,
}
}
}
#[cfg(feature = "v2")]
impl
TrackerPostUpdateObjects<
router_flow_types::SetupMandate,
router_request_types::SetupMandateRequestData,
payments::PaymentConfirmData<router_flow_types::SetupMandate>,
>
for RouterData<
router_flow_types::SetupMandate,
router_request_types::SetupMandateRequestData,
router_response_types::PaymentsResponseData,
>
{
fn get_payment_intent_update(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentIntentUpdate {
let amount_captured = self.get_captured_amount(payment_data);
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: None,
},
Err(ref error) => PaymentIntentUpdate::ConfirmIntentPostUpdate {
status: error
.attempt_status
.map(common_enums::IntentStatus::from)
.unwrap_or(common_enums::IntentStatus::Failed),
amount_captured,
updated_by: storage_scheme.to_string(),
feature_metadata: None,
},
}
}
fn get_payment_attempt_update(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>,
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,
..
} => {
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: None,
},
))
}
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(),
}
}
}
}
fn get_attempt_status_for_db_update(
&self,
_payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>,
) -> common_enums::AttemptStatus {
// For this step, consider whatever status was given by the connector module
// We do not need to check for amount captured or amount capturable here because we are authorizing the whole amount
self.status
}
fn get_amount_capturable(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>,
) -> Option<MinorUnit> {
// Based on the status of the response, we can determine the amount capturable
let intent_status = common_enums::IntentStatus::from(self.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 => 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
| common_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture => {
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,
}
}
fn get_captured_amount(
&self,
payment_data: &payments::PaymentConfirmData<router_flow_types::SetupMandate>,
) -> 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);
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,
}
}
}
#[cfg(feature = "v2")]
impl
TrackerPostUpdateObjects<
router_flow_types::Void,
router_request_types::PaymentsCancelData,
payments::PaymentCancelData<router_flow_types::Void>,
>
for RouterData<
router_flow_types::Void,
router_request_types::PaymentsCancelData,
router_response_types::PaymentsResponseData,
>
{
fn get_payment_intent_update(
&self,
payment_data: &payments::PaymentCancelData<router_flow_types::Void>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentIntentUpdate {
let intent_status =
common_enums::IntentStatus::from(self.get_attempt_status_for_db_update(payment_data));
PaymentIntentUpdate::VoidUpdate {
status: intent_status,
updated_by: storage_scheme.to_string(),
}
}
fn get_payment_attempt_update(
&self,
payment_data: &payments::PaymentCancelData<router_flow_types::Void>,
storage_scheme: common_enums::MerchantStorageScheme,
) -> PaymentAttemptUpdate {
match &self.response {
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();
// Handle errors exactly
let 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::AttemptStatus::Pending,
_ => common_enums::AttemptStatus::VoidFailed,
},
};
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,
amount_capturable: Some(MinorUnit::zero()),
error: error_details,
updated_by: storage_scheme.to_string(),
connector_payment_id: connector_transaction_id,
}
}
Ok(ref _response) => PaymentAttemptUpdate::VoidUpdate {
status: self.status,
cancellation_reason: payment_data.payment_attempt.cancellation_reason.clone(),
updated_by: storage_scheme.to_string(),
},
}
}
fn get_amount_capturable(
&self,
_payment_data: &payments::PaymentCancelData<router_flow_types::Void>,
) -> Option<MinorUnit> {
// For void operations, no amount is capturable
Some(MinorUnit::zero())
}
fn get_captured_amount(
&self,
_payment_data: &payments::PaymentCancelData<router_flow_types::Void>,
) -> Option<MinorUnit> {
// For void operations, no amount is captured
Some(MinorUnit::zero())
}
fn get_attempt_status_for_db_update(
&self,
_payment_data: &payments::PaymentCancelData<router_flow_types::Void>,
) -> common_enums::AttemptStatus {
// For void operations, determine status based on response
match &self.response {
Err(ref error_response) => match error_response.attempt_status {
Some(status) => status,
None => match error_response.status_code {
500..=511 => common_enums::AttemptStatus::Pending,
_ => common_enums::AttemptStatus::VoidFailed,
},
},
Ok(ref _response) => self.status,
}
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_data.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 3,
"num_structs": 20,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-3900658186851077792
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/business_profile.rs
// Contains: 4 structs, 3 enums
use std::borrow::Cow;
use common_enums::enums as api_enums;
use common_types::{domain::AcquirerConfig, primitive_wrappers};
use common_utils::{
crypto::{OptionalEncryptableName, OptionalEncryptableValue},
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
ext_traits::{OptionExt, ValueExt},
pii, type_name,
types::keymanager,
};
#[cfg(feature = "v2")]
use diesel_models::business_profile::RevenueRecoveryAlgorithmData;
use diesel_models::business_profile::{
self as storage_types, AuthenticationConnectorDetails, BusinessPaymentLinkConfig,
BusinessPayoutLinkConfig, CardTestingGuardConfig, ExternalVaultConnectorDetails,
ProfileUpdateInternal, WebhookDetails,
};
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret};
use crate::{
behaviour::Conversion,
errors::api_error_response,
merchant_key_store::MerchantKeyStore,
type_encryption::{crypto_operation, AsyncLift, CryptoOperation},
};
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub struct Profile {
profile_id: common_utils::id_type::ProfileId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub intent_fulfillment_time: Option<i64>,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub is_recon_enabled: bool,
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: bool,
pub is_l2_l3_enabled: bool,
pub version: common_enums::ApiVersion,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: bool,
pub max_auto_retries_enabled: Option<i16>,
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
pub is_click_to_pay_enabled: bool,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: OptionalEncryptableName,
pub is_clear_pan_retries_enabled: bool,
pub force_3ds_challenge: bool,
pub is_debit_routing_enabled: bool,
pub merchant_business_country: Option<common_enums::CountryAlpha2>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_pre_network_tokenization_enabled: bool,
pub three_ds_decision_rule_algorithm: Option<serde_json::Value>,
pub acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>,
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
pub is_manual_retry_enabled: Option<bool>,
pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
pub external_vault_details: ExternalVaultDetails,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub enum ExternalVaultDetails {
ExternalVaultEnabled(ExternalVaultConnectorDetails),
Skip,
}
#[cfg(feature = "v1")]
impl ExternalVaultDetails {
pub fn is_external_vault_enabled(&self) -> bool {
match self {
Self::ExternalVaultEnabled(_) => true,
Self::Skip => false,
}
}
}
#[cfg(feature = "v1")]
impl
TryFrom<(
Option<common_enums::ExternalVaultEnabled>,
Option<ExternalVaultConnectorDetails>,
)> for ExternalVaultDetails
{
type Error = error_stack::Report<ValidationError>;
fn try_from(
item: (
Option<common_enums::ExternalVaultEnabled>,
Option<ExternalVaultConnectorDetails>,
),
) -> Result<Self, Self::Error> {
match item {
(is_external_vault_enabled, external_vault_connector_details)
if is_external_vault_enabled
.unwrap_or(common_enums::ExternalVaultEnabled::Skip)
== common_enums::ExternalVaultEnabled::Enable =>
{
Ok(Self::ExternalVaultEnabled(
external_vault_connector_details
.get_required_value("ExternalVaultConnectorDetails")?,
))
}
_ => Ok(Self::Skip),
}
}
}
#[cfg(feature = "v1")]
impl TryFrom<(Option<bool>, Option<ExternalVaultConnectorDetails>)> for ExternalVaultDetails {
type Error = error_stack::Report<ValidationError>;
fn try_from(
item: (Option<bool>, Option<ExternalVaultConnectorDetails>),
) -> Result<Self, Self::Error> {
match item {
(is_external_vault_enabled, external_vault_connector_details)
if is_external_vault_enabled.unwrap_or(false) =>
{
Ok(Self::ExternalVaultEnabled(
external_vault_connector_details
.get_required_value("ExternalVaultConnectorDetails")?,
))
}
_ => Ok(Self::Skip),
}
}
}
#[cfg(feature = "v1")]
impl From<ExternalVaultDetails>
for (
Option<common_enums::ExternalVaultEnabled>,
Option<ExternalVaultConnectorDetails>,
)
{
fn from(external_vault_details: ExternalVaultDetails) -> Self {
match external_vault_details {
ExternalVaultDetails::ExternalVaultEnabled(connector_details) => (
Some(common_enums::ExternalVaultEnabled::Enable),
Some(connector_details),
),
ExternalVaultDetails::Skip => (Some(common_enums::ExternalVaultEnabled::Skip), None),
}
}
}
#[cfg(feature = "v1")]
impl From<ExternalVaultDetails> for (Option<bool>, Option<ExternalVaultConnectorDetails>) {
fn from(external_vault_details: ExternalVaultDetails) -> Self {
match external_vault_details {
ExternalVaultDetails::ExternalVaultEnabled(connector_details) => {
(Some(true), Some(connector_details))
}
ExternalVaultDetails::Skip => (Some(false), None),
}
}
}
#[cfg(feature = "v1")]
pub struct ProfileSetter {
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<String>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub intent_fulfillment_time: Option<i64>,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub is_recon_enabled: bool,
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: bool,
pub is_l2_l3_enabled: bool,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: bool,
pub is_auto_retries_enabled: bool,
pub max_auto_retries_enabled: Option<i16>,
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
pub is_click_to_pay_enabled: bool,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: OptionalEncryptableName,
pub is_clear_pan_retries_enabled: bool,
pub force_3ds_challenge: bool,
pub is_debit_routing_enabled: bool,
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_pre_network_tokenization_enabled: bool,
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
pub is_manual_retry_enabled: Option<bool>,
pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
pub external_vault_details: ExternalVaultDetails,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v1")]
impl From<ProfileSetter> for Profile {
fn from(value: ProfileSetter) -> Self {
Self {
profile_id: value.profile_id,
merchant_id: value.merchant_id,
profile_name: value.profile_name,
created_at: value.created_at,
modified_at: value.modified_at,
return_url: value.return_url,
enable_payment_response_hash: value.enable_payment_response_hash,
payment_response_hash_key: value.payment_response_hash_key,
redirect_to_merchant_with_http_post: value.redirect_to_merchant_with_http_post,
webhook_details: value.webhook_details,
metadata: value.metadata,
routing_algorithm: value.routing_algorithm,
intent_fulfillment_time: value.intent_fulfillment_time,
frm_routing_algorithm: value.frm_routing_algorithm,
payout_routing_algorithm: value.payout_routing_algorithm,
is_recon_enabled: value.is_recon_enabled,
applepay_verified_domains: value.applepay_verified_domains,
payment_link_config: value.payment_link_config,
session_expiry: value.session_expiry,
authentication_connector_details: value.authentication_connector_details,
payout_link_config: value.payout_link_config,
is_extended_card_info_enabled: value.is_extended_card_info_enabled,
extended_card_info_config: value.extended_card_info_config,
is_connector_agnostic_mit_enabled: value.is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing: value.use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector: value
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector: value
.collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: value.outgoing_webhook_custom_http_headers,
always_collect_billing_details_from_wallet_connector: value
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: value
.always_collect_shipping_details_from_wallet_connector,
tax_connector_id: value.tax_connector_id,
is_tax_connector_enabled: value.is_tax_connector_enabled,
is_l2_l3_enabled: value.is_l2_l3_enabled,
version: common_types::consts::API_VERSION,
dynamic_routing_algorithm: value.dynamic_routing_algorithm,
is_network_tokenization_enabled: value.is_network_tokenization_enabled,
is_auto_retries_enabled: value.is_auto_retries_enabled,
max_auto_retries_enabled: value.max_auto_retries_enabled,
always_request_extended_authorization: value.always_request_extended_authorization,
is_click_to_pay_enabled: value.is_click_to_pay_enabled,
authentication_product_ids: value.authentication_product_ids,
card_testing_guard_config: value.card_testing_guard_config,
card_testing_secret_key: value.card_testing_secret_key,
is_clear_pan_retries_enabled: value.is_clear_pan_retries_enabled,
force_3ds_challenge: value.force_3ds_challenge,
is_debit_routing_enabled: value.is_debit_routing_enabled,
merchant_business_country: value.merchant_business_country,
is_iframe_redirection_enabled: value.is_iframe_redirection_enabled,
is_pre_network_tokenization_enabled: value.is_pre_network_tokenization_enabled,
three_ds_decision_rule_algorithm: None, // three_ds_decision_rule_algorithm is not yet created during profile creation
acquirer_config_map: None,
merchant_category_code: value.merchant_category_code,
merchant_country_code: value.merchant_country_code,
dispute_polling_interval: value.dispute_polling_interval,
is_manual_retry_enabled: value.is_manual_retry_enabled,
always_enable_overcapture: value.always_enable_overcapture,
external_vault_details: value.external_vault_details,
billing_processor_id: value.billing_processor_id,
}
}
}
impl Profile {
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &common_utils::id_type::ProfileId {
&self.profile_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &common_utils::id_type::ProfileId {
&self.id
}
}
#[cfg(feature = "v1")]
#[derive(Debug)]
pub struct ProfileGeneralUpdate {
pub profile_name: Option<String>,
pub return_url: Option<String>,
pub enable_payment_response_hash: Option<bool>,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: Option<bool>,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub routing_algorithm: Option<serde_json::Value>,
pub intent_fulfillment_time: Option<i64>,
pub frm_routing_algorithm: Option<serde_json::Value>,
pub payout_routing_algorithm: Option<serde_json::Value>,
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: Option<bool>,
pub is_l2_l3_enabled: Option<bool>,
pub dynamic_routing_algorithm: Option<serde_json::Value>,
pub is_network_tokenization_enabled: Option<bool>,
pub is_auto_retries_enabled: Option<bool>,
pub max_auto_retries_enabled: Option<i16>,
pub is_click_to_pay_enabled: Option<bool>,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: OptionalEncryptableName,
pub is_clear_pan_retries_enabled: Option<bool>,
pub force_3ds_challenge: Option<bool>,
pub is_debit_routing_enabled: Option<bool>,
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_pre_network_tokenization_enabled: Option<bool>,
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
pub is_manual_retry_enabled: Option<bool>,
pub always_enable_overcapture: Option<primitive_wrappers::AlwaysEnableOvercaptureBool>,
pub is_external_vault_enabled: Option<common_enums::ExternalVaultEnabled>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v1")]
#[derive(Debug)]
pub enum ProfileUpdate {
Update(Box<ProfileGeneralUpdate>),
RoutingAlgorithmUpdate {
routing_algorithm: Option<serde_json::Value>,
payout_routing_algorithm: Option<serde_json::Value>,
three_ds_decision_rule_algorithm: Option<serde_json::Value>,
},
DynamicRoutingAlgorithmUpdate {
dynamic_routing_algorithm: Option<serde_json::Value>,
},
ExtendedCardInfoUpdate {
is_extended_card_info_enabled: bool,
},
ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled: bool,
},
NetworkTokenizationUpdate {
is_network_tokenization_enabled: bool,
},
CardTestingSecretKeyUpdate {
card_testing_secret_key: OptionalEncryptableName,
},
AcquirerConfigMapUpdate {
acquirer_config_map: Option<common_types::domain::AcquirerConfigMap>,
},
}
#[cfg(feature = "v1")]
impl From<ProfileUpdate> for ProfileUpdateInternal {
fn from(profile_update: ProfileUpdate) -> Self {
let now = date_time::now();
match profile_update {
ProfileUpdate::Update(update) => {
let ProfileGeneralUpdate {
profile_name,
return_url,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
webhook_details,
metadata,
routing_algorithm,
intent_fulfillment_time,
frm_routing_algorithm,
payout_routing_algorithm,
applepay_verified_domains,
payment_link_config,
session_expiry,
authentication_connector_details,
payout_link_config,
extended_card_info_config,
use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector,
is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers,
always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector,
tax_connector_id,
is_tax_connector_enabled,
is_l2_l3_enabled,
dynamic_routing_algorithm,
is_network_tokenization_enabled,
is_auto_retries_enabled,
max_auto_retries_enabled,
is_click_to_pay_enabled,
authentication_product_ids,
card_testing_guard_config,
card_testing_secret_key,
is_clear_pan_retries_enabled,
force_3ds_challenge,
is_debit_routing_enabled,
merchant_business_country,
is_iframe_redirection_enabled,
is_pre_network_tokenization_enabled,
merchant_category_code,
merchant_country_code,
dispute_polling_interval,
always_request_extended_authorization,
is_manual_retry_enabled,
always_enable_overcapture,
is_external_vault_enabled,
external_vault_connector_details,
billing_processor_id,
} = *update;
let is_external_vault_enabled = match is_external_vault_enabled {
Some(external_vault_mode) => match external_vault_mode {
common_enums::ExternalVaultEnabled::Enable => Some(true),
common_enums::ExternalVaultEnabled::Skip => Some(false),
},
None => Some(false),
};
Self {
profile_name,
modified_at: now,
return_url,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
webhook_details,
metadata,
routing_algorithm,
intent_fulfillment_time,
frm_routing_algorithm,
payout_routing_algorithm,
is_recon_enabled: None,
applepay_verified_domains,
payment_link_config,
session_expiry,
authentication_connector_details,
payout_link_config,
is_extended_card_info_enabled: None,
extended_card_info_config,
is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.map(Encryption::from),
always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector,
tax_connector_id,
is_tax_connector_enabled,
is_l2_l3_enabled,
dynamic_routing_algorithm,
is_network_tokenization_enabled,
is_auto_retries_enabled,
max_auto_retries_enabled,
always_request_extended_authorization,
is_click_to_pay_enabled,
authentication_product_ids,
card_testing_guard_config,
card_testing_secret_key: card_testing_secret_key.map(Encryption::from),
is_clear_pan_retries_enabled,
force_3ds_challenge,
is_debit_routing_enabled,
merchant_business_country,
is_iframe_redirection_enabled,
is_pre_network_tokenization_enabled,
three_ds_decision_rule_algorithm: None,
acquirer_config_map: None,
merchant_category_code,
merchant_country_code,
dispute_polling_interval,
is_manual_retry_enabled,
always_enable_overcapture,
is_external_vault_enabled,
external_vault_connector_details,
billing_processor_id,
}
}
ProfileUpdate::RoutingAlgorithmUpdate {
routing_algorithm,
payout_routing_algorithm,
three_ds_decision_rule_algorithm,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
routing_algorithm,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
always_request_extended_authorization: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
card_testing_guard_config: None,
card_testing_secret_key: None,
is_clear_pan_retries_enabled: None,
force_3ds_challenge: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
is_iframe_redirection_enabled: None,
is_pre_network_tokenization_enabled: None,
three_ds_decision_rule_algorithm,
acquirer_config_map: None,
merchant_category_code: None,
merchant_country_code: None,
dispute_polling_interval: None,
is_manual_retry_enabled: None,
always_enable_overcapture: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
billing_processor_id: None,
is_l2_l3_enabled: None,
},
ProfileUpdate::DynamicRoutingAlgorithmUpdate {
dynamic_routing_algorithm,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
routing_algorithm: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
dynamic_routing_algorithm,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
always_request_extended_authorization: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
card_testing_guard_config: None,
card_testing_secret_key: None,
is_clear_pan_retries_enabled: None,
force_3ds_challenge: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
is_iframe_redirection_enabled: None,
is_pre_network_tokenization_enabled: None,
three_ds_decision_rule_algorithm: None,
acquirer_config_map: None,
merchant_category_code: None,
merchant_country_code: None,
dispute_polling_interval: None,
is_manual_retry_enabled: None,
always_enable_overcapture: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
billing_processor_id: None,
is_l2_l3_enabled: None,
},
ProfileUpdate::ExtendedCardInfoUpdate {
is_extended_card_info_enabled,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
routing_algorithm: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: Some(is_extended_card_info_enabled),
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
always_request_extended_authorization: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
card_testing_guard_config: None,
card_testing_secret_key: None,
is_clear_pan_retries_enabled: None,
force_3ds_challenge: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
is_iframe_redirection_enabled: None,
is_pre_network_tokenization_enabled: None,
three_ds_decision_rule_algorithm: None,
acquirer_config_map: None,
merchant_category_code: None,
merchant_country_code: None,
dispute_polling_interval: None,
is_manual_retry_enabled: None,
always_enable_overcapture: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
billing_processor_id: None,
is_l2_l3_enabled: None,
},
ProfileUpdate::ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
routing_algorithm: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: Some(is_connector_agnostic_mit_enabled),
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
always_request_extended_authorization: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
card_testing_guard_config: None,
card_testing_secret_key: None,
is_clear_pan_retries_enabled: None,
force_3ds_challenge: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
is_iframe_redirection_enabled: None,
is_pre_network_tokenization_enabled: None,
three_ds_decision_rule_algorithm: None,
acquirer_config_map: None,
merchant_category_code: None,
merchant_country_code: None,
dispute_polling_interval: None,
is_manual_retry_enabled: None,
always_enable_overcapture: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
billing_processor_id: None,
is_l2_l3_enabled: None,
},
ProfileUpdate::NetworkTokenizationUpdate {
is_network_tokenization_enabled,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
routing_algorithm: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: Some(is_network_tokenization_enabled),
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
always_request_extended_authorization: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
card_testing_guard_config: None,
card_testing_secret_key: None,
is_clear_pan_retries_enabled: None,
force_3ds_challenge: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
is_iframe_redirection_enabled: None,
is_pre_network_tokenization_enabled: None,
three_ds_decision_rule_algorithm: None,
acquirer_config_map: None,
merchant_category_code: None,
merchant_country_code: None,
dispute_polling_interval: None,
is_manual_retry_enabled: None,
always_enable_overcapture: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
billing_processor_id: None,
is_l2_l3_enabled: None,
},
ProfileUpdate::CardTestingSecretKeyUpdate {
card_testing_secret_key,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
routing_algorithm: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
always_request_extended_authorization: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
card_testing_guard_config: None,
card_testing_secret_key: card_testing_secret_key.map(Encryption::from),
is_clear_pan_retries_enabled: None,
force_3ds_challenge: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
is_iframe_redirection_enabled: None,
is_pre_network_tokenization_enabled: None,
three_ds_decision_rule_algorithm: None,
acquirer_config_map: None,
merchant_category_code: None,
merchant_country_code: None,
dispute_polling_interval: None,
is_manual_retry_enabled: None,
always_enable_overcapture: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
billing_processor_id: None,
is_l2_l3_enabled: None,
},
ProfileUpdate::AcquirerConfigMapUpdate {
acquirer_config_map,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
routing_algorithm: None,
intent_fulfillment_time: None,
frm_routing_algorithm: None,
payout_routing_algorithm: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
always_request_extended_authorization: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
card_testing_guard_config: None,
card_testing_secret_key: None,
is_clear_pan_retries_enabled: None,
force_3ds_challenge: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
is_iframe_redirection_enabled: None,
is_pre_network_tokenization_enabled: None,
three_ds_decision_rule_algorithm: None,
acquirer_config_map,
merchant_category_code: None,
merchant_country_code: None,
dispute_polling_interval: None,
is_manual_retry_enabled: None,
always_enable_overcapture: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
billing_processor_id: None,
is_l2_l3_enabled: None,
},
}
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl Conversion for Profile {
type DstType = diesel_models::business_profile::Profile;
type NewDstType = diesel_models::business_profile::ProfileNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let (is_external_vault_enabled, external_vault_connector_details) =
self.external_vault_details.into();
Ok(diesel_models::business_profile::Profile {
profile_id: self.profile_id.clone(),
id: Some(self.profile_id),
merchant_id: self.merchant_id,
profile_name: self.profile_name,
created_at: self.created_at,
modified_at: self.modified_at,
return_url: self.return_url,
enable_payment_response_hash: self.enable_payment_response_hash,
payment_response_hash_key: self.payment_response_hash_key,
redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post,
webhook_details: self.webhook_details,
metadata: self.metadata,
routing_algorithm: self.routing_algorithm,
intent_fulfillment_time: self.intent_fulfillment_time,
frm_routing_algorithm: self.frm_routing_algorithm,
payout_routing_algorithm: self.payout_routing_algorithm,
is_recon_enabled: self.is_recon_enabled,
applepay_verified_domains: self.applepay_verified_domains,
payment_link_config: self.payment_link_config,
session_expiry: self.session_expiry,
authentication_connector_details: self.authentication_connector_details,
payout_link_config: self.payout_link_config,
is_extended_card_info_enabled: self.is_extended_card_info_enabled,
extended_card_info_config: self.extended_card_info_config,
is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector: self
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector: self
.collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: self
.outgoing_webhook_custom_http_headers
.map(Encryption::from),
always_collect_billing_details_from_wallet_connector: self
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: self
.always_collect_shipping_details_from_wallet_connector,
tax_connector_id: self.tax_connector_id,
is_tax_connector_enabled: Some(self.is_tax_connector_enabled),
is_l2_l3_enabled: Some(self.is_l2_l3_enabled),
version: self.version,
dynamic_routing_algorithm: self.dynamic_routing_algorithm,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
is_auto_retries_enabled: Some(self.is_auto_retries_enabled),
max_auto_retries_enabled: self.max_auto_retries_enabled,
always_request_extended_authorization: self.always_request_extended_authorization,
is_click_to_pay_enabled: self.is_click_to_pay_enabled,
authentication_product_ids: self.authentication_product_ids,
card_testing_guard_config: self.card_testing_guard_config,
card_testing_secret_key: self.card_testing_secret_key.map(|name| name.into()),
is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled,
force_3ds_challenge: Some(self.force_3ds_challenge),
is_debit_routing_enabled: self.is_debit_routing_enabled,
merchant_business_country: self.merchant_business_country,
is_iframe_redirection_enabled: self.is_iframe_redirection_enabled,
is_pre_network_tokenization_enabled: Some(self.is_pre_network_tokenization_enabled),
three_ds_decision_rule_algorithm: self.three_ds_decision_rule_algorithm,
acquirer_config_map: self.acquirer_config_map,
merchant_category_code: self.merchant_category_code,
merchant_country_code: self.merchant_country_code,
dispute_polling_interval: self.dispute_polling_interval,
is_manual_retry_enabled: self.is_manual_retry_enabled,
always_enable_overcapture: self.always_enable_overcapture,
is_external_vault_enabled,
external_vault_connector_details,
billing_processor_id: self.billing_processor_id,
})
}
async fn convert_back(
state: &keymanager::KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
// Decrypt encrypted fields first
let (outgoing_webhook_custom_http_headers, card_testing_secret_key) = async {
let outgoing_webhook_custom_http_headers = item
.outgoing_webhook_custom_http_headers
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?;
let card_testing_secret_key = item
.card_testing_secret_key
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?;
Ok::<_, error_stack::Report<common_utils::errors::CryptoError>>((
outgoing_webhook_custom_http_headers,
card_testing_secret_key,
))
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting business profile data".to_string(),
})?;
let external_vault_details = ExternalVaultDetails::try_from((
item.is_external_vault_enabled,
item.external_vault_connector_details,
))?;
// Construct the domain type
Ok(Self {
profile_id: item.profile_id,
merchant_id: item.merchant_id,
profile_name: item.profile_name,
created_at: item.created_at,
modified_at: item.modified_at,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
payment_response_hash_key: item.payment_response_hash_key,
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
webhook_details: item.webhook_details,
metadata: item.metadata,
routing_algorithm: item.routing_algorithm,
intent_fulfillment_time: item.intent_fulfillment_time,
frm_routing_algorithm: item.frm_routing_algorithm,
payout_routing_algorithm: item.payout_routing_algorithm,
is_recon_enabled: item.is_recon_enabled,
applepay_verified_domains: item.applepay_verified_domains,
payment_link_config: item.payment_link_config,
session_expiry: item.session_expiry,
authentication_connector_details: item.authentication_connector_details,
payout_link_config: item.payout_link_config,
is_extended_card_info_enabled: item.is_extended_card_info_enabled,
extended_card_info_config: item.extended_card_info_config,
is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector: item
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector: item
.collect_billing_details_from_wallet_connector,
always_collect_billing_details_from_wallet_connector: item
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: item
.always_collect_shipping_details_from_wallet_connector,
outgoing_webhook_custom_http_headers,
tax_connector_id: item.tax_connector_id,
is_tax_connector_enabled: item.is_tax_connector_enabled.unwrap_or(false),
is_l2_l3_enabled: item.is_l2_l3_enabled.unwrap_or(false),
version: item.version,
dynamic_routing_algorithm: item.dynamic_routing_algorithm,
is_network_tokenization_enabled: item.is_network_tokenization_enabled,
is_auto_retries_enabled: item.is_auto_retries_enabled.unwrap_or(false),
max_auto_retries_enabled: item.max_auto_retries_enabled,
always_request_extended_authorization: item.always_request_extended_authorization,
is_click_to_pay_enabled: item.is_click_to_pay_enabled,
authentication_product_ids: item.authentication_product_ids,
card_testing_guard_config: item.card_testing_guard_config,
card_testing_secret_key,
is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled,
force_3ds_challenge: item.force_3ds_challenge.unwrap_or_default(),
is_debit_routing_enabled: item.is_debit_routing_enabled,
merchant_business_country: item.merchant_business_country,
is_iframe_redirection_enabled: item.is_iframe_redirection_enabled,
is_pre_network_tokenization_enabled: item
.is_pre_network_tokenization_enabled
.unwrap_or(false),
three_ds_decision_rule_algorithm: item.three_ds_decision_rule_algorithm,
acquirer_config_map: item.acquirer_config_map,
merchant_category_code: item.merchant_category_code,
merchant_country_code: item.merchant_country_code,
dispute_polling_interval: item.dispute_polling_interval,
is_manual_retry_enabled: item.is_manual_retry_enabled,
always_enable_overcapture: item.always_enable_overcapture,
external_vault_details,
billing_processor_id: item.billing_processor_id,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let (is_external_vault_enabled, external_vault_connector_details) =
self.external_vault_details.into();
Ok(diesel_models::business_profile::ProfileNew {
profile_id: self.profile_id.clone(),
id: Some(self.profile_id),
merchant_id: self.merchant_id,
profile_name: self.profile_name,
created_at: self.created_at,
modified_at: self.modified_at,
return_url: self.return_url,
enable_payment_response_hash: self.enable_payment_response_hash,
payment_response_hash_key: self.payment_response_hash_key,
redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post,
webhook_details: self.webhook_details,
metadata: self.metadata,
routing_algorithm: self.routing_algorithm,
intent_fulfillment_time: self.intent_fulfillment_time,
frm_routing_algorithm: self.frm_routing_algorithm,
payout_routing_algorithm: self.payout_routing_algorithm,
is_recon_enabled: self.is_recon_enabled,
applepay_verified_domains: self.applepay_verified_domains,
payment_link_config: self.payment_link_config,
session_expiry: self.session_expiry,
authentication_connector_details: self.authentication_connector_details,
payout_link_config: self.payout_link_config,
is_extended_card_info_enabled: self.is_extended_card_info_enabled,
extended_card_info_config: self.extended_card_info_config,
is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector: self
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector: self
.collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: self
.outgoing_webhook_custom_http_headers
.map(Encryption::from),
always_collect_billing_details_from_wallet_connector: self
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: self
.always_collect_shipping_details_from_wallet_connector,
tax_connector_id: self.tax_connector_id,
is_tax_connector_enabled: Some(self.is_tax_connector_enabled),
is_l2_l3_enabled: Some(self.is_l2_l3_enabled),
version: self.version,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
is_auto_retries_enabled: Some(self.is_auto_retries_enabled),
max_auto_retries_enabled: self.max_auto_retries_enabled,
is_click_to_pay_enabled: self.is_click_to_pay_enabled,
authentication_product_ids: self.authentication_product_ids,
card_testing_guard_config: self.card_testing_guard_config,
card_testing_secret_key: self.card_testing_secret_key.map(Encryption::from),
is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled,
force_3ds_challenge: Some(self.force_3ds_challenge),
is_debit_routing_enabled: self.is_debit_routing_enabled,
merchant_business_country: self.merchant_business_country,
is_iframe_redirection_enabled: self.is_iframe_redirection_enabled,
is_pre_network_tokenization_enabled: Some(self.is_pre_network_tokenization_enabled),
merchant_category_code: self.merchant_category_code,
merchant_country_code: self.merchant_country_code,
dispute_polling_interval: self.dispute_polling_interval,
is_manual_retry_enabled: self.is_manual_retry_enabled,
is_external_vault_enabled,
external_vault_connector_details,
billing_processor_id: self.billing_processor_id,
})
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct Profile {
id: common_utils::id_type::ProfileId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<common_utils::types::Url>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub is_recon_enabled: bool,
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub default_fallback_routing: Option<pii::SecretSerdeValue>,
pub should_collect_cvv_during_payment:
Option<primitive_wrappers::ShouldCollectCvvDuringPayment>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: bool,
pub version: common_enums::ApiVersion,
pub is_network_tokenization_enabled: bool,
pub is_click_to_pay_enabled: bool,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: OptionalEncryptableName,
pub is_clear_pan_retries_enabled: bool,
pub is_debit_routing_enabled: bool,
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>,
pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_external_vault_enabled: Option<bool>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub split_txns_enabled: common_enums::SplitTxnsEnabled,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v2")]
pub struct ProfileSetter {
pub id: common_utils::id_type::ProfileId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
pub return_url: Option<common_utils::types::Url>,
pub enable_payment_response_hash: bool,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: bool,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub is_recon_enabled: bool,
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub is_extended_card_info_enabled: Option<bool>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
pub frm_routing_algorithm_id: Option<String>,
pub payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
pub default_fallback_routing: Option<pii::SecretSerdeValue>,
pub should_collect_cvv_during_payment:
Option<primitive_wrappers::ShouldCollectCvvDuringPayment>,
pub tax_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub is_tax_connector_enabled: bool,
pub is_network_tokenization_enabled: bool,
pub is_click_to_pay_enabled: bool,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: OptionalEncryptableName,
pub is_clear_pan_retries_enabled: bool,
pub is_debit_routing_enabled: bool,
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>,
pub revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_external_vault_enabled: Option<bool>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub split_txns_enabled: common_enums::SplitTxnsEnabled,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v2")]
impl From<ProfileSetter> for Profile {
fn from(value: ProfileSetter) -> Self {
Self {
id: value.id,
merchant_id: value.merchant_id,
profile_name: value.profile_name,
created_at: value.created_at,
modified_at: value.modified_at,
return_url: value.return_url,
enable_payment_response_hash: value.enable_payment_response_hash,
payment_response_hash_key: value.payment_response_hash_key,
redirect_to_merchant_with_http_post: value.redirect_to_merchant_with_http_post,
webhook_details: value.webhook_details,
metadata: value.metadata,
is_recon_enabled: value.is_recon_enabled,
applepay_verified_domains: value.applepay_verified_domains,
payment_link_config: value.payment_link_config,
session_expiry: value.session_expiry,
authentication_connector_details: value.authentication_connector_details,
payout_link_config: value.payout_link_config,
is_extended_card_info_enabled: value.is_extended_card_info_enabled,
extended_card_info_config: value.extended_card_info_config,
is_connector_agnostic_mit_enabled: value.is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing: value.use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector: value
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector: value
.collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: value.outgoing_webhook_custom_http_headers,
always_collect_billing_details_from_wallet_connector: value
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: value
.always_collect_shipping_details_from_wallet_connector,
routing_algorithm_id: value.routing_algorithm_id,
order_fulfillment_time: value.order_fulfillment_time,
order_fulfillment_time_origin: value.order_fulfillment_time_origin,
frm_routing_algorithm_id: value.frm_routing_algorithm_id,
payout_routing_algorithm_id: value.payout_routing_algorithm_id,
default_fallback_routing: value.default_fallback_routing,
should_collect_cvv_during_payment: value.should_collect_cvv_during_payment,
tax_connector_id: value.tax_connector_id,
is_tax_connector_enabled: value.is_tax_connector_enabled,
version: common_types::consts::API_VERSION,
is_network_tokenization_enabled: value.is_network_tokenization_enabled,
is_click_to_pay_enabled: value.is_click_to_pay_enabled,
authentication_product_ids: value.authentication_product_ids,
three_ds_decision_manager_config: value.three_ds_decision_manager_config,
card_testing_guard_config: value.card_testing_guard_config,
card_testing_secret_key: value.card_testing_secret_key,
is_clear_pan_retries_enabled: value.is_clear_pan_retries_enabled,
is_debit_routing_enabled: value.is_debit_routing_enabled,
merchant_business_country: value.merchant_business_country,
revenue_recovery_retry_algorithm_type: value.revenue_recovery_retry_algorithm_type,
revenue_recovery_retry_algorithm_data: value.revenue_recovery_retry_algorithm_data,
is_iframe_redirection_enabled: value.is_iframe_redirection_enabled,
is_external_vault_enabled: value.is_external_vault_enabled,
external_vault_connector_details: value.external_vault_connector_details,
merchant_category_code: value.merchant_category_code,
merchant_country_code: value.merchant_country_code,
split_txns_enabled: value.split_txns_enabled,
billing_processor_id: value.billing_processor_id,
}
}
}
impl Profile {
pub fn get_is_tax_connector_enabled(&self) -> bool {
let is_tax_connector_enabled = self.is_tax_connector_enabled;
match &self.tax_connector_id {
Some(_id) => is_tax_connector_enabled,
_ => false,
}
}
#[cfg(feature = "v1")]
pub fn get_order_fulfillment_time(&self) -> Option<i64> {
self.intent_fulfillment_time
}
#[cfg(feature = "v2")]
pub fn get_order_fulfillment_time(&self) -> Option<i64> {
self.order_fulfillment_time
}
pub fn get_webhook_url_from_profile(&self) -> CustomResult<String, ValidationError> {
self.webhook_details
.clone()
.and_then(|details| details.webhook_url)
.get_required_value("webhook_details.webhook_url")
.map(ExposeInterface::expose)
}
#[cfg(feature = "v2")]
pub fn is_external_vault_enabled(&self) -> bool {
self.is_external_vault_enabled.unwrap_or(false)
}
#[cfg(feature = "v2")]
pub fn is_vault_sdk_enabled(&self) -> bool {
self.external_vault_connector_details.is_some()
}
#[cfg(feature = "v1")]
pub fn get_acquirer_details_from_network(
&self,
network: common_enums::CardNetwork,
) -> Option<AcquirerConfig> {
// iterate over acquirer_config_map and find the acquirer config for the given network
self.acquirer_config_map
.as_ref()
.and_then(|acquirer_config_map| {
acquirer_config_map
.0
.iter()
.find(|&(_, acquirer_config)| acquirer_config.network == network)
})
.map(|(_, acquirer_config)| acquirer_config.clone())
}
#[cfg(feature = "v1")]
pub fn get_payment_routing_algorithm(
&self,
) -> CustomResult<
Option<api_models::routing::RoutingAlgorithmRef>,
api_error_response::ApiErrorResponse,
> {
self.routing_algorithm
.clone()
.map(|val| {
val.parse_value::<api_models::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef")
})
.transpose()
.change_context(api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize routing algorithm ref from merchant account")
}
#[cfg(feature = "v1")]
pub fn get_payout_routing_algorithm(
&self,
) -> CustomResult<
Option<api_models::routing::RoutingAlgorithmRef>,
api_error_response::ApiErrorResponse,
> {
self.payout_routing_algorithm
.clone()
.map(|val| {
val.parse_value::<api_models::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef")
})
.transpose()
.change_context(api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize payout routing algorithm ref from merchant account",
)
}
#[cfg(feature = "v1")]
pub fn get_frm_routing_algorithm(
&self,
) -> CustomResult<
Option<api_models::routing::RoutingAlgorithmRef>,
api_error_response::ApiErrorResponse,
> {
self.frm_routing_algorithm
.clone()
.map(|val| {
val.parse_value::<api_models::routing::RoutingAlgorithmRef>("RoutingAlgorithmRef")
})
.transpose()
.change_context(api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize frm routing algorithm ref from merchant account",
)
}
pub fn get_payment_webhook_statuses(&self) -> Cow<'_, [common_enums::IntentStatus]> {
self.webhook_details
.as_ref()
.and_then(|details| details.payment_statuses_enabled.as_ref())
.filter(|statuses_vec| !statuses_vec.is_empty())
.map(|statuses_vec| Cow::Borrowed(statuses_vec.as_slice()))
.unwrap_or_else(|| {
Cow::Borrowed(common_types::consts::DEFAULT_PAYMENT_WEBHOOK_TRIGGER_STATUSES)
})
}
pub fn get_refund_webhook_statuses(&self) -> Cow<'_, [common_enums::RefundStatus]> {
self.webhook_details
.as_ref()
.and_then(|details| details.refund_statuses_enabled.as_ref())
.filter(|statuses_vec| !statuses_vec.is_empty())
.map(|statuses_vec| Cow::Borrowed(statuses_vec.as_slice()))
.unwrap_or_else(|| {
Cow::Borrowed(common_types::consts::DEFAULT_REFUND_WEBHOOK_TRIGGER_STATUSES)
})
}
pub fn get_payout_webhook_statuses(&self) -> Cow<'_, [common_enums::PayoutStatus]> {
self.webhook_details
.as_ref()
.and_then(|details| details.payout_statuses_enabled.as_ref())
.filter(|statuses_vec| !statuses_vec.is_empty())
.map(|statuses_vec| Cow::Borrowed(statuses_vec.as_slice()))
.unwrap_or_else(|| {
Cow::Borrowed(common_types::consts::DEFAULT_PAYOUT_WEBHOOK_TRIGGER_STATUSES)
})
}
pub fn get_billing_processor_id(
&self,
) -> CustomResult<
common_utils::id_type::MerchantConnectorAccountId,
api_error_response::ApiErrorResponse,
> {
self.billing_processor_id
.to_owned()
.ok_or(error_stack::report!(
api_error_response::ApiErrorResponse::MissingRequiredField {
field_name: "billing_processor_id"
}
))
}
}
#[cfg(feature = "v2")]
#[derive(Debug)]
pub struct ProfileGeneralUpdate {
pub profile_name: Option<String>,
pub return_url: Option<common_utils::types::Url>,
pub enable_payment_response_hash: Option<bool>,
pub payment_response_hash_key: Option<String>,
pub redirect_to_merchant_with_http_post: Option<bool>,
pub webhook_details: Option<WebhookDetails>,
pub metadata: Option<pii::SecretSerdeValue>,
pub applepay_verified_domains: Option<Vec<String>>,
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
pub session_expiry: Option<i64>,
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
pub extended_card_info_config: Option<pii::SecretSerdeValue>,
pub use_billing_as_payment_method_billing: Option<bool>,
pub collect_shipping_details_from_wallet_connector: Option<bool>,
pub collect_billing_details_from_wallet_connector: Option<bool>,
pub is_connector_agnostic_mit_enabled: Option<bool>,
pub outgoing_webhook_custom_http_headers: OptionalEncryptableValue,
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
pub order_fulfillment_time: Option<i64>,
pub order_fulfillment_time_origin: Option<common_enums::OrderFulfillmentTimeOrigin>,
pub is_network_tokenization_enabled: Option<bool>,
pub is_click_to_pay_enabled: Option<bool>,
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
pub three_ds_decision_manager_config: Option<common_types::payments::DecisionManagerRecord>,
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
pub card_testing_secret_key: OptionalEncryptableName,
pub is_debit_routing_enabled: Option<bool>,
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
pub is_iframe_redirection_enabled: Option<bool>,
pub is_external_vault_enabled: Option<bool>,
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
pub revenue_recovery_retry_algorithm_type: Option<common_enums::RevenueRecoveryAlgorithmType>,
pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>,
pub billing_processor_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v2")]
#[derive(Debug)]
pub enum ProfileUpdate {
Update(Box<ProfileGeneralUpdate>),
RoutingAlgorithmUpdate {
routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
payout_routing_algorithm_id: Option<common_utils::id_type::RoutingId>,
},
DefaultRoutingFallbackUpdate {
default_fallback_routing: Option<pii::SecretSerdeValue>,
},
ExtendedCardInfoUpdate {
is_extended_card_info_enabled: bool,
},
ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled: bool,
},
NetworkTokenizationUpdate {
is_network_tokenization_enabled: bool,
},
CollectCvvDuringPaymentUpdate {
should_collect_cvv_during_payment: primitive_wrappers::ShouldCollectCvvDuringPayment,
},
DecisionManagerRecordUpdate {
three_ds_decision_manager_config: common_types::payments::DecisionManagerRecord,
},
CardTestingSecretKeyUpdate {
card_testing_secret_key: OptionalEncryptableName,
},
RevenueRecoveryAlgorithmUpdate {
revenue_recovery_retry_algorithm_type: common_enums::RevenueRecoveryAlgorithmType,
revenue_recovery_retry_algorithm_data: Option<RevenueRecoveryAlgorithmData>,
},
}
#[cfg(feature = "v2")]
impl From<ProfileUpdate> for ProfileUpdateInternal {
fn from(profile_update: ProfileUpdate) -> Self {
let now = date_time::now();
match profile_update {
ProfileUpdate::Update(update) => {
let ProfileGeneralUpdate {
profile_name,
return_url,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
webhook_details,
metadata,
applepay_verified_domains,
payment_link_config,
session_expiry,
authentication_connector_details,
payout_link_config,
extended_card_info_config,
use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector,
is_connector_agnostic_mit_enabled,
outgoing_webhook_custom_http_headers,
always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector,
order_fulfillment_time,
order_fulfillment_time_origin,
is_network_tokenization_enabled,
is_click_to_pay_enabled,
authentication_product_ids,
three_ds_decision_manager_config,
card_testing_guard_config,
card_testing_secret_key,
is_debit_routing_enabled,
merchant_business_country,
is_iframe_redirection_enabled,
is_external_vault_enabled,
external_vault_connector_details,
merchant_category_code,
merchant_country_code,
revenue_recovery_retry_algorithm_type,
split_txns_enabled,
billing_processor_id,
} = *update;
Self {
profile_name,
modified_at: now,
return_url,
enable_payment_response_hash,
payment_response_hash_key,
redirect_to_merchant_with_http_post,
webhook_details,
metadata,
is_recon_enabled: None,
applepay_verified_domains,
payment_link_config,
session_expiry,
authentication_connector_details,
payout_link_config,
is_extended_card_info_enabled: None,
extended_card_info_config,
is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: outgoing_webhook_custom_http_headers
.map(Encryption::from),
routing_algorithm_id: None,
always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector,
order_fulfillment_time,
order_fulfillment_time_origin,
frm_routing_algorithm_id: None,
payout_routing_algorithm_id: None,
default_fallback_routing: None,
should_collect_cvv_during_payment: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
is_l2_l3_enabled: None,
is_network_tokenization_enabled,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
is_click_to_pay_enabled,
authentication_product_ids,
three_ds_decision_manager_config,
card_testing_guard_config,
card_testing_secret_key: card_testing_secret_key.map(Encryption::from),
is_clear_pan_retries_enabled: None,
is_debit_routing_enabled,
merchant_business_country,
revenue_recovery_retry_algorithm_type,
revenue_recovery_retry_algorithm_data: None,
is_iframe_redirection_enabled,
is_external_vault_enabled,
external_vault_connector_details,
merchant_category_code,
merchant_country_code,
split_txns_enabled,
billing_processor_id,
}
}
ProfileUpdate::RoutingAlgorithmUpdate {
routing_algorithm_id,
payout_routing_algorithm_id,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
routing_algorithm_id,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
order_fulfillment_time: None,
order_fulfillment_time_origin: None,
frm_routing_algorithm_id: None,
payout_routing_algorithm_id,
default_fallback_routing: None,
should_collect_cvv_during_payment: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
is_l2_l3_enabled: None,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
three_ds_decision_manager_config: None,
card_testing_guard_config: None,
card_testing_secret_key: None,
is_clear_pan_retries_enabled: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
revenue_recovery_retry_algorithm_type: None,
revenue_recovery_retry_algorithm_data: None,
is_iframe_redirection_enabled: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
merchant_category_code: None,
merchant_country_code: None,
split_txns_enabled: None,
billing_processor_id: None,
},
ProfileUpdate::ExtendedCardInfoUpdate {
is_extended_card_info_enabled,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: Some(is_extended_card_info_enabled),
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
routing_algorithm_id: None,
payout_routing_algorithm_id: None,
order_fulfillment_time: None,
order_fulfillment_time_origin: None,
frm_routing_algorithm_id: None,
default_fallback_routing: None,
should_collect_cvv_during_payment: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
is_l2_l3_enabled: None,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
three_ds_decision_manager_config: None,
card_testing_guard_config: None,
card_testing_secret_key: None,
is_clear_pan_retries_enabled: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
revenue_recovery_retry_algorithm_type: None,
revenue_recovery_retry_algorithm_data: None,
is_iframe_redirection_enabled: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
merchant_category_code: None,
merchant_country_code: None,
split_txns_enabled: None,
billing_processor_id: None,
},
ProfileUpdate::ConnectorAgnosticMitUpdate {
is_connector_agnostic_mit_enabled,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
is_l2_l3_enabled: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: Some(is_connector_agnostic_mit_enabled),
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
routing_algorithm_id: None,
payout_routing_algorithm_id: None,
order_fulfillment_time: None,
order_fulfillment_time_origin: None,
frm_routing_algorithm_id: None,
default_fallback_routing: None,
should_collect_cvv_during_payment: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
three_ds_decision_manager_config: None,
card_testing_guard_config: None,
card_testing_secret_key: None,
is_clear_pan_retries_enabled: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
revenue_recovery_retry_algorithm_type: None,
revenue_recovery_retry_algorithm_data: None,
is_iframe_redirection_enabled: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
merchant_category_code: None,
merchant_country_code: None,
split_txns_enabled: None,
billing_processor_id: None,
},
ProfileUpdate::DefaultRoutingFallbackUpdate {
default_fallback_routing,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
is_recon_enabled: None,
applepay_verified_domains: None,
is_l2_l3_enabled: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
routing_algorithm_id: None,
payout_routing_algorithm_id: None,
order_fulfillment_time: None,
order_fulfillment_time_origin: None,
frm_routing_algorithm_id: None,
default_fallback_routing,
should_collect_cvv_during_payment: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
three_ds_decision_manager_config: None,
card_testing_guard_config: None,
card_testing_secret_key: None,
is_clear_pan_retries_enabled: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
revenue_recovery_retry_algorithm_type: None,
revenue_recovery_retry_algorithm_data: None,
is_iframe_redirection_enabled: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
merchant_category_code: None,
merchant_country_code: None,
split_txns_enabled: None,
billing_processor_id: None,
},
ProfileUpdate::NetworkTokenizationUpdate {
is_network_tokenization_enabled,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
is_l2_l3_enabled: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
routing_algorithm_id: None,
payout_routing_algorithm_id: None,
order_fulfillment_time: None,
order_fulfillment_time_origin: None,
frm_routing_algorithm_id: None,
default_fallback_routing: None,
should_collect_cvv_during_payment: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
is_network_tokenization_enabled: Some(is_network_tokenization_enabled),
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
three_ds_decision_manager_config: None,
card_testing_guard_config: None,
card_testing_secret_key: None,
is_clear_pan_retries_enabled: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
revenue_recovery_retry_algorithm_type: None,
revenue_recovery_retry_algorithm_data: None,
is_iframe_redirection_enabled: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
merchant_category_code: None,
merchant_country_code: None,
split_txns_enabled: None,
billing_processor_id: None,
},
ProfileUpdate::CollectCvvDuringPaymentUpdate {
should_collect_cvv_during_payment,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
routing_algorithm_id: None,
payout_routing_algorithm_id: None,
order_fulfillment_time: None,
order_fulfillment_time_origin: None,
frm_routing_algorithm_id: None,
default_fallback_routing: None,
should_collect_cvv_during_payment: Some(should_collect_cvv_during_payment),
tax_connector_id: None,
is_tax_connector_enabled: None,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
is_l2_l3_enabled: None,
three_ds_decision_manager_config: None,
card_testing_guard_config: None,
card_testing_secret_key: None,
is_clear_pan_retries_enabled: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
revenue_recovery_retry_algorithm_type: None,
revenue_recovery_retry_algorithm_data: None,
is_iframe_redirection_enabled: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
merchant_category_code: None,
merchant_country_code: None,
split_txns_enabled: None,
billing_processor_id: None,
},
ProfileUpdate::DecisionManagerRecordUpdate {
three_ds_decision_manager_config,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
routing_algorithm_id: None,
payout_routing_algorithm_id: None,
order_fulfillment_time: None,
order_fulfillment_time_origin: None,
frm_routing_algorithm_id: None,
default_fallback_routing: None,
should_collect_cvv_during_payment: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
three_ds_decision_manager_config: Some(three_ds_decision_manager_config),
card_testing_guard_config: None,
card_testing_secret_key: None,
is_l2_l3_enabled: None,
is_clear_pan_retries_enabled: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
revenue_recovery_retry_algorithm_type: None,
revenue_recovery_retry_algorithm_data: None,
is_iframe_redirection_enabled: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
merchant_category_code: None,
merchant_country_code: None,
split_txns_enabled: None,
billing_processor_id: None,
},
ProfileUpdate::CardTestingSecretKeyUpdate {
card_testing_secret_key,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
routing_algorithm_id: None,
payout_routing_algorithm_id: None,
order_fulfillment_time: None,
order_fulfillment_time_origin: None,
frm_routing_algorithm_id: None,
default_fallback_routing: None,
should_collect_cvv_during_payment: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
three_ds_decision_manager_config: None,
card_testing_guard_config: None,
card_testing_secret_key: card_testing_secret_key.map(Encryption::from),
is_clear_pan_retries_enabled: None,
is_debit_routing_enabled: None,
is_l2_l3_enabled: None,
merchant_business_country: None,
revenue_recovery_retry_algorithm_type: None,
revenue_recovery_retry_algorithm_data: None,
is_iframe_redirection_enabled: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
merchant_category_code: None,
merchant_country_code: None,
split_txns_enabled: None,
billing_processor_id: None,
},
ProfileUpdate::RevenueRecoveryAlgorithmUpdate {
revenue_recovery_retry_algorithm_type,
revenue_recovery_retry_algorithm_data,
} => Self {
profile_name: None,
modified_at: now,
return_url: None,
enable_payment_response_hash: None,
payment_response_hash_key: None,
redirect_to_merchant_with_http_post: None,
webhook_details: None,
metadata: None,
is_recon_enabled: None,
applepay_verified_domains: None,
payment_link_config: None,
session_expiry: None,
authentication_connector_details: None,
payout_link_config: None,
is_extended_card_info_enabled: None,
extended_card_info_config: None,
is_connector_agnostic_mit_enabled: None,
use_billing_as_payment_method_billing: None,
collect_shipping_details_from_wallet_connector: None,
collect_billing_details_from_wallet_connector: None,
outgoing_webhook_custom_http_headers: None,
always_collect_billing_details_from_wallet_connector: None,
always_collect_shipping_details_from_wallet_connector: None,
routing_algorithm_id: None,
is_l2_l3_enabled: None,
payout_routing_algorithm_id: None,
order_fulfillment_time: None,
order_fulfillment_time_origin: None,
frm_routing_algorithm_id: None,
default_fallback_routing: None,
should_collect_cvv_during_payment: None,
tax_connector_id: None,
is_tax_connector_enabled: None,
is_network_tokenization_enabled: None,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
is_click_to_pay_enabled: None,
authentication_product_ids: None,
three_ds_decision_manager_config: None,
card_testing_guard_config: None,
card_testing_secret_key: None,
is_clear_pan_retries_enabled: None,
is_debit_routing_enabled: None,
merchant_business_country: None,
revenue_recovery_retry_algorithm_type: Some(revenue_recovery_retry_algorithm_type),
revenue_recovery_retry_algorithm_data,
is_iframe_redirection_enabled: None,
is_external_vault_enabled: None,
external_vault_connector_details: None,
merchant_category_code: None,
merchant_country_code: None,
split_txns_enabled: None,
billing_processor_id: None,
},
}
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl Conversion for Profile {
type DstType = diesel_models::business_profile::Profile;
type NewDstType = diesel_models::business_profile::ProfileNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::business_profile::Profile {
id: self.id,
merchant_id: self.merchant_id,
profile_name: self.profile_name,
created_at: self.created_at,
modified_at: self.modified_at,
return_url: self.return_url,
enable_payment_response_hash: self.enable_payment_response_hash,
payment_response_hash_key: self.payment_response_hash_key,
redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post,
webhook_details: self.webhook_details,
metadata: self.metadata,
is_recon_enabled: self.is_recon_enabled,
applepay_verified_domains: self.applepay_verified_domains,
payment_link_config: self.payment_link_config,
session_expiry: self.session_expiry,
authentication_connector_details: self.authentication_connector_details,
payout_link_config: self.payout_link_config,
is_extended_card_info_enabled: self.is_extended_card_info_enabled,
extended_card_info_config: self.extended_card_info_config,
is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector: self
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector: self
.collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: self
.outgoing_webhook_custom_http_headers
.map(Encryption::from),
routing_algorithm_id: self.routing_algorithm_id,
always_collect_billing_details_from_wallet_connector: self
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: self
.always_collect_shipping_details_from_wallet_connector,
payout_routing_algorithm_id: self.payout_routing_algorithm_id,
order_fulfillment_time: self.order_fulfillment_time,
order_fulfillment_time_origin: self.order_fulfillment_time_origin,
frm_routing_algorithm_id: self.frm_routing_algorithm_id,
default_fallback_routing: self.default_fallback_routing,
should_collect_cvv_during_payment: self.should_collect_cvv_during_payment,
tax_connector_id: self.tax_connector_id,
is_tax_connector_enabled: Some(self.is_tax_connector_enabled),
version: self.version,
dynamic_routing_algorithm: None,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
always_request_extended_authorization: None,
is_click_to_pay_enabled: self.is_click_to_pay_enabled,
authentication_product_ids: self.authentication_product_ids,
three_ds_decision_manager_config: self.three_ds_decision_manager_config,
card_testing_guard_config: self.card_testing_guard_config,
card_testing_secret_key: self.card_testing_secret_key.map(|name| name.into()),
is_clear_pan_retries_enabled: self.is_clear_pan_retries_enabled,
force_3ds_challenge: None,
is_debit_routing_enabled: self.is_debit_routing_enabled,
merchant_business_country: self.merchant_business_country,
revenue_recovery_retry_algorithm_type: self.revenue_recovery_retry_algorithm_type,
revenue_recovery_retry_algorithm_data: self.revenue_recovery_retry_algorithm_data,
is_iframe_redirection_enabled: self.is_iframe_redirection_enabled,
is_external_vault_enabled: self.is_external_vault_enabled,
external_vault_connector_details: self.external_vault_connector_details,
three_ds_decision_rule_algorithm: None,
acquirer_config_map: None,
merchant_category_code: self.merchant_category_code,
merchant_country_code: self.merchant_country_code,
dispute_polling_interval: None,
split_txns_enabled: Some(self.split_txns_enabled),
is_manual_retry_enabled: None,
is_l2_l3_enabled: None,
always_enable_overcapture: None,
billing_processor_id: self.billing_processor_id,
})
}
async fn convert_back(
state: &keymanager::KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
async {
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
id: item.id,
merchant_id: item.merchant_id,
profile_name: item.profile_name,
created_at: item.created_at,
modified_at: item.modified_at,
return_url: item.return_url,
enable_payment_response_hash: item.enable_payment_response_hash,
payment_response_hash_key: item.payment_response_hash_key,
redirect_to_merchant_with_http_post: item.redirect_to_merchant_with_http_post,
webhook_details: item.webhook_details,
metadata: item.metadata,
is_recon_enabled: item.is_recon_enabled,
applepay_verified_domains: item.applepay_verified_domains,
payment_link_config: item.payment_link_config,
session_expiry: item.session_expiry,
authentication_connector_details: item.authentication_connector_details,
payout_link_config: item.payout_link_config,
is_extended_card_info_enabled: item.is_extended_card_info_enabled,
extended_card_info_config: item.extended_card_info_config,
is_connector_agnostic_mit_enabled: item.is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing: item.use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector: item
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector: item
.collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: item
.outgoing_webhook_custom_http_headers
.async_lift(|inner| async {
crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(inner),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
})
.await?,
routing_algorithm_id: item.routing_algorithm_id,
always_collect_billing_details_from_wallet_connector: item
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: item
.always_collect_shipping_details_from_wallet_connector,
order_fulfillment_time: item.order_fulfillment_time,
order_fulfillment_time_origin: item.order_fulfillment_time_origin,
frm_routing_algorithm_id: item.frm_routing_algorithm_id,
payout_routing_algorithm_id: item.payout_routing_algorithm_id,
default_fallback_routing: item.default_fallback_routing,
should_collect_cvv_during_payment: item.should_collect_cvv_during_payment,
tax_connector_id: item.tax_connector_id,
is_tax_connector_enabled: item.is_tax_connector_enabled.unwrap_or(false),
version: item.version,
is_network_tokenization_enabled: item.is_network_tokenization_enabled,
is_click_to_pay_enabled: item.is_click_to_pay_enabled,
authentication_product_ids: item.authentication_product_ids,
three_ds_decision_manager_config: item.three_ds_decision_manager_config,
card_testing_guard_config: item.card_testing_guard_config,
card_testing_secret_key: match item.card_testing_secret_key {
Some(encrypted_value) => crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::DecryptOptional(Some(encrypted_value)),
key_manager_identifier.clone(),
key.peek(),
)
.await
.and_then(|val| val.try_into_optionaloperation())
.unwrap_or_default(),
None => None,
},
is_clear_pan_retries_enabled: item.is_clear_pan_retries_enabled,
is_debit_routing_enabled: item.is_debit_routing_enabled,
merchant_business_country: item.merchant_business_country,
revenue_recovery_retry_algorithm_type: item.revenue_recovery_retry_algorithm_type,
revenue_recovery_retry_algorithm_data: item.revenue_recovery_retry_algorithm_data,
is_iframe_redirection_enabled: item.is_iframe_redirection_enabled,
is_external_vault_enabled: item.is_external_vault_enabled,
external_vault_connector_details: item.external_vault_connector_details,
merchant_category_code: item.merchant_category_code,
merchant_country_code: item.merchant_country_code,
split_txns_enabled: item.split_txns_enabled.unwrap_or_default(),
billing_processor_id: item.billing_processor_id,
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting business profile data".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::business_profile::ProfileNew {
id: self.id,
merchant_id: self.merchant_id,
profile_name: self.profile_name,
created_at: self.created_at,
modified_at: self.modified_at,
return_url: self.return_url,
enable_payment_response_hash: self.enable_payment_response_hash,
payment_response_hash_key: self.payment_response_hash_key,
redirect_to_merchant_with_http_post: self.redirect_to_merchant_with_http_post,
webhook_details: self.webhook_details,
metadata: self.metadata,
is_recon_enabled: self.is_recon_enabled,
applepay_verified_domains: self.applepay_verified_domains,
payment_link_config: self.payment_link_config,
session_expiry: self.session_expiry,
authentication_connector_details: self.authentication_connector_details,
payout_link_config: self.payout_link_config,
is_extended_card_info_enabled: self.is_extended_card_info_enabled,
extended_card_info_config: self.extended_card_info_config,
is_connector_agnostic_mit_enabled: self.is_connector_agnostic_mit_enabled,
use_billing_as_payment_method_billing: self.use_billing_as_payment_method_billing,
collect_shipping_details_from_wallet_connector: self
.collect_shipping_details_from_wallet_connector,
collect_billing_details_from_wallet_connector: self
.collect_billing_details_from_wallet_connector,
outgoing_webhook_custom_http_headers: self
.outgoing_webhook_custom_http_headers
.map(Encryption::from),
routing_algorithm_id: self.routing_algorithm_id,
always_collect_billing_details_from_wallet_connector: self
.always_collect_billing_details_from_wallet_connector,
always_collect_shipping_details_from_wallet_connector: self
.always_collect_shipping_details_from_wallet_connector,
order_fulfillment_time: self.order_fulfillment_time,
order_fulfillment_time_origin: self.order_fulfillment_time_origin,
frm_routing_algorithm_id: self.frm_routing_algorithm_id,
payout_routing_algorithm_id: self.payout_routing_algorithm_id,
default_fallback_routing: self.default_fallback_routing,
should_collect_cvv_during_payment: self.should_collect_cvv_during_payment,
tax_connector_id: self.tax_connector_id,
is_tax_connector_enabled: Some(self.is_tax_connector_enabled),
version: self.version,
is_network_tokenization_enabled: self.is_network_tokenization_enabled,
is_auto_retries_enabled: None,
max_auto_retries_enabled: None,
is_click_to_pay_enabled: self.is_click_to_pay_enabled,
authentication_product_ids: self.authentication_product_ids,
three_ds_decision_manager_config: self.three_ds_decision_manager_config,
card_testing_guard_config: self.card_testing_guard_config,
card_testing_secret_key: self.card_testing_secret_key.map(Encryption::from),
is_clear_pan_retries_enabled: Some(self.is_clear_pan_retries_enabled),
is_debit_routing_enabled: self.is_debit_routing_enabled,
merchant_business_country: self.merchant_business_country,
revenue_recovery_retry_algorithm_type: self.revenue_recovery_retry_algorithm_type,
revenue_recovery_retry_algorithm_data: self.revenue_recovery_retry_algorithm_data,
is_iframe_redirection_enabled: self.is_iframe_redirection_enabled,
is_external_vault_enabled: self.is_external_vault_enabled,
external_vault_connector_details: self.external_vault_connector_details,
merchant_category_code: self.merchant_category_code,
is_l2_l3_enabled: None,
merchant_country_code: self.merchant_country_code,
split_txns_enabled: Some(self.split_txns_enabled),
billing_processor_id: self.billing_processor_id,
})
}
}
#[async_trait::async_trait]
pub trait ProfileInterface
where
Profile: Conversion<DstType = storage_types::Profile, NewDstType = storage_types::ProfileNew>,
{
type Error;
async fn insert_business_profile(
&self,
key_manager_state: &keymanager::KeyManagerState,
merchant_key_store: &MerchantKeyStore,
business_profile: Profile,
) -> CustomResult<Profile, Self::Error>;
async fn find_business_profile_by_profile_id(
&self,
key_manager_state: &keymanager::KeyManagerState,
merchant_key_store: &MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
) -> CustomResult<Profile, Self::Error>;
async fn find_business_profile_by_merchant_id_profile_id(
&self,
key_manager_state: &keymanager::KeyManagerState,
merchant_key_store: &MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
) -> CustomResult<Profile, Self::Error>;
async fn find_business_profile_by_profile_name_merchant_id(
&self,
key_manager_state: &keymanager::KeyManagerState,
merchant_key_store: &MerchantKeyStore,
profile_name: &str,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Profile, Self::Error>;
async fn update_profile_by_profile_id(
&self,
key_manager_state: &keymanager::KeyManagerState,
merchant_key_store: &MerchantKeyStore,
current_state: Profile,
profile_update: ProfileUpdate,
) -> CustomResult<Profile, Self::Error>;
async fn delete_profile_by_profile_id_merchant_id(
&self,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, Self::Error>;
async fn list_profile_by_merchant_id(
&self,
key_manager_state: &keymanager::KeyManagerState,
merchant_key_store: &MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<Profile>, Self::Error>;
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/business_profile.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 3,
"num_structs": 4,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_4131246301300791890
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/invoice.rs
// Contains: 4 structs, 1 enums
use common_utils::{
errors::{CustomResult, ValidationError},
id_type::GenerateId,
pii::SecretSerdeValue,
types::{
keymanager::{Identifier, KeyManagerState},
MinorUnit,
},
};
use masking::{PeekInterface, Secret};
use utoipa::ToSchema;
use crate::merchant_key_store::MerchantKeyStore;
#[derive(Debug, Clone, serde::Serialize, ToSchema)]
pub struct Invoice {
pub id: common_utils::id_type::InvoiceId,
pub subscription_id: common_utils::id_type::SubscriptionId,
pub merchant_id: common_utils::id_type::MerchantId,
pub profile_id: common_utils::id_type::ProfileId,
pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
pub payment_intent_id: Option<common_utils::id_type::PaymentId>,
pub payment_method_id: Option<String>,
pub customer_id: common_utils::id_type::CustomerId,
pub amount: MinorUnit,
pub currency: String,
pub status: common_enums::connector_enums::InvoiceStatus,
pub provider_name: common_enums::connector_enums::Connector,
pub metadata: Option<SecretSerdeValue>,
pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for Invoice {
type DstType = diesel_models::invoice::Invoice;
type NewDstType = diesel_models::invoice::InvoiceNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let now = common_utils::date_time::now();
Ok(diesel_models::invoice::Invoice {
id: self.id,
subscription_id: self.subscription_id,
merchant_id: self.merchant_id,
profile_id: self.profile_id,
merchant_connector_id: self.merchant_connector_id,
payment_intent_id: self.payment_intent_id,
payment_method_id: self.payment_method_id,
customer_id: self.customer_id,
amount: self.amount,
currency: self.currency.to_string(),
status: self.status,
provider_name: self.provider_name,
metadata: None,
created_at: now,
modified_at: now,
connector_invoice_id: self.connector_invoice_id,
})
}
async fn convert_back(
_state: &KeyManagerState,
item: Self::DstType,
_key: &Secret<Vec<u8>>,
_key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
Ok(Self {
id: item.id,
subscription_id: item.subscription_id,
merchant_id: item.merchant_id,
profile_id: item.profile_id,
merchant_connector_id: item.merchant_connector_id,
payment_intent_id: item.payment_intent_id,
payment_method_id: item.payment_method_id,
customer_id: item.customer_id,
amount: item.amount,
currency: item.currency,
status: item.status,
provider_name: item.provider_name,
metadata: item.metadata,
connector_invoice_id: item.connector_invoice_id,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::invoice::InvoiceNew::new(
self.subscription_id,
self.merchant_id,
self.profile_id,
self.merchant_connector_id,
self.payment_intent_id,
self.payment_method_id,
self.customer_id,
self.amount,
self.currency.to_string(),
self.status,
self.provider_name,
None,
self.connector_invoice_id,
))
}
}
impl Invoice {
#[allow(clippy::too_many_arguments)]
pub fn to_invoice(
subscription_id: common_utils::id_type::SubscriptionId,
merchant_id: common_utils::id_type::MerchantId,
profile_id: common_utils::id_type::ProfileId,
merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId,
payment_intent_id: Option<common_utils::id_type::PaymentId>,
payment_method_id: Option<String>,
customer_id: common_utils::id_type::CustomerId,
amount: MinorUnit,
currency: String,
status: common_enums::connector_enums::InvoiceStatus,
provider_name: common_enums::connector_enums::Connector,
metadata: Option<SecretSerdeValue>,
connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
) -> Self {
Self {
id: common_utils::id_type::InvoiceId::generate(),
subscription_id,
merchant_id,
profile_id,
merchant_connector_id,
payment_intent_id,
payment_method_id,
customer_id,
amount,
currency: currency.to_string(),
status,
provider_name,
metadata,
connector_invoice_id,
}
}
}
#[async_trait::async_trait]
pub trait InvoiceInterface {
type Error;
async fn insert_invoice_entry(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
invoice_new: Invoice,
) -> CustomResult<Invoice, Self::Error>;
async fn find_invoice_by_invoice_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
invoice_id: String,
) -> CustomResult<Invoice, Self::Error>;
async fn update_invoice_entry(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
invoice_id: String,
data: InvoiceUpdate,
) -> CustomResult<Invoice, Self::Error>;
async fn get_latest_invoice_for_subscription(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
subscription_id: String,
) -> CustomResult<Invoice, Self::Error>;
async fn find_invoice_by_subscription_id_connector_invoice_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
subscription_id: String,
connector_invoice_id: common_utils::id_type::InvoiceId,
) -> CustomResult<Option<Invoice>, Self::Error>;
}
pub struct InvoiceUpdate {
pub status: Option<common_enums::connector_enums::InvoiceStatus>,
pub payment_method_id: Option<String>,
pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
pub modified_at: time::PrimitiveDateTime,
pub payment_intent_id: Option<common_utils::id_type::PaymentId>,
pub amount: Option<MinorUnit>,
pub currency: Option<String>,
}
#[derive(Debug, Clone)]
pub struct AmountAndCurrencyUpdate {
pub amount: MinorUnit,
pub currency: String,
}
#[derive(Debug, Clone)]
pub struct ConnectorAndStatusUpdate {
pub connector_invoice_id: common_utils::id_type::InvoiceId,
pub status: common_enums::connector_enums::InvoiceStatus,
}
#[derive(Debug, Clone)]
pub struct PaymentAndStatusUpdate {
pub payment_method_id: Option<Secret<String>>,
pub payment_intent_id: Option<common_utils::id_type::PaymentId>,
pub status: common_enums::connector_enums::InvoiceStatus,
pub connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
}
/// Enum-based invoice update request for different scenarios
#[derive(Debug, Clone)]
pub enum InvoiceUpdateRequest {
/// Update amount and currency
Amount(AmountAndCurrencyUpdate),
/// Update connector invoice ID and status
Connector(ConnectorAndStatusUpdate),
/// Update payment details along with status
PaymentStatus(PaymentAndStatusUpdate),
}
impl InvoiceUpdateRequest {
/// Create an amount and currency update request
pub fn update_amount_and_currency(amount: MinorUnit, currency: String) -> Self {
Self::Amount(AmountAndCurrencyUpdate { amount, currency })
}
/// Create a connector invoice ID and status update request
pub fn update_connector_and_status(
connector_invoice_id: common_utils::id_type::InvoiceId,
status: common_enums::connector_enums::InvoiceStatus,
) -> Self {
Self::Connector(ConnectorAndStatusUpdate {
connector_invoice_id,
status,
})
}
/// Create a combined payment and status update request
pub fn update_payment_and_status(
payment_method_id: Option<Secret<String>>,
payment_intent_id: Option<common_utils::id_type::PaymentId>,
status: common_enums::connector_enums::InvoiceStatus,
connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
) -> Self {
Self::PaymentStatus(PaymentAndStatusUpdate {
payment_method_id,
payment_intent_id,
status,
connector_invoice_id,
})
}
}
impl From<InvoiceUpdateRequest> for InvoiceUpdate {
fn from(request: InvoiceUpdateRequest) -> Self {
let now = common_utils::date_time::now();
match request {
InvoiceUpdateRequest::Amount(update) => Self {
status: None,
payment_method_id: None,
connector_invoice_id: None,
modified_at: now,
payment_intent_id: None,
amount: Some(update.amount),
currency: Some(update.currency),
},
InvoiceUpdateRequest::Connector(update) => Self {
status: Some(update.status),
payment_method_id: None,
connector_invoice_id: Some(update.connector_invoice_id),
modified_at: now,
payment_intent_id: None,
amount: None,
currency: None,
},
InvoiceUpdateRequest::PaymentStatus(update) => Self {
status: Some(update.status),
payment_method_id: update
.payment_method_id
.as_ref()
.map(|id| id.peek())
.cloned(),
connector_invoice_id: update.connector_invoice_id,
modified_at: now,
payment_intent_id: update.payment_intent_id,
amount: None,
currency: None,
},
}
}
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for InvoiceUpdate {
type DstType = diesel_models::invoice::InvoiceUpdate;
type NewDstType = diesel_models::invoice::InvoiceUpdate;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::invoice::InvoiceUpdate {
status: self.status,
payment_method_id: self.payment_method_id,
connector_invoice_id: self.connector_invoice_id,
modified_at: self.modified_at,
payment_intent_id: self.payment_intent_id,
amount: self.amount,
currency: self.currency,
})
}
async fn convert_back(
_state: &KeyManagerState,
item: Self::DstType,
_key: &Secret<Vec<u8>>,
_key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
Ok(Self {
status: item.status,
payment_method_id: item.payment_method_id,
connector_invoice_id: item.connector_invoice_id,
modified_at: item.modified_at,
payment_intent_id: item.payment_intent_id,
amount: item.amount,
currency: item.currency,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::invoice::InvoiceUpdate {
status: self.status,
payment_method_id: self.payment_method_id,
connector_invoice_id: self.connector_invoice_id,
modified_at: self.modified_at,
payment_intent_id: self.payment_intent_id,
amount: self.amount,
currency: self.currency,
})
}
}
impl InvoiceUpdate {
pub fn new(
payment_method_id: Option<String>,
status: Option<common_enums::connector_enums::InvoiceStatus>,
connector_invoice_id: Option<common_utils::id_type::InvoiceId>,
payment_intent_id: Option<common_utils::id_type::PaymentId>,
amount: Option<MinorUnit>,
currency: Option<String>,
) -> Self {
Self {
status,
payment_method_id,
connector_invoice_id,
modified_at: common_utils::date_time::now(),
payment_intent_id,
amount,
currency,
}
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/invoice.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 4,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-9170327251913744442
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/card_testing_guard_data.rs
// Contains: 1 structs, 0 enums
use serde::{self, Deserialize, Serialize};
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct CardTestingGuardData {
pub is_card_ip_blocking_enabled: bool,
pub card_ip_blocking_cache_key: String,
pub is_guest_user_card_blocking_enabled: bool,
pub guest_user_card_blocking_cache_key: String,
pub is_customer_id_blocking_enabled: bool,
pub customer_id_blocking_cache_key: String,
pub card_testing_guard_expiry: i32,
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/card_testing_guard_data.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_507670902330565031
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/customer.rs
// Contains: 3 structs, 2 enums
use common_enums::enums::MerchantStorageScheme;
#[cfg(feature = "v2")]
use common_enums::DeleteStatus;
use common_utils::{
crypto::{self, Encryptable},
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
ext_traits::ValueExt,
id_type, pii,
types::{
keymanager::{self, KeyManagerState, ToEncryptable},
Description,
},
};
use diesel_models::{
customers as storage_types, customers::CustomerUpdateInternal, query::customers as query,
};
use error_stack::ResultExt;
use masking::{ExposeOptionInterface, PeekInterface, Secret, SwitchStrategy};
use router_env::{instrument, tracing};
use rustc_hash::FxHashMap;
use time::PrimitiveDateTime;
#[cfg(feature = "v2")]
use crate::merchant_connector_account::MerchantConnectorAccountTypeDetails;
use crate::{behaviour, merchant_key_store::MerchantKeyStore, type_encryption as types};
#[cfg(feature = "v1")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct Customer {
pub customer_id: id_type::CustomerId,
pub merchant_id: id_type::MerchantId,
#[encrypt]
pub name: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
#[encrypt]
pub phone: Option<Encryptable<Secret<String>>>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: PrimitiveDateTime,
pub connector_customer: Option<pii::SecretSerdeValue>,
pub address_id: Option<String>,
pub default_payment_method_id: Option<String>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
#[encrypt]
pub tax_registration_id: Option<Encryptable<Secret<String>>>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct Customer {
pub merchant_id: id_type::MerchantId,
#[encrypt]
pub name: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
#[encrypt]
pub phone: Option<Encryptable<Secret<String>>>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>,
pub modified_at: PrimitiveDateTime,
pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>,
pub updated_by: Option<String>,
pub merchant_reference_id: Option<id_type::CustomerId>,
pub default_billing_address: Option<Encryption>,
pub default_shipping_address: Option<Encryption>,
pub id: id_type::GlobalCustomerId,
pub version: common_enums::ApiVersion,
pub status: DeleteStatus,
#[encrypt]
pub tax_registration_id: Option<Encryptable<Secret<String>>>,
}
impl Customer {
/// Get the unique identifier of Customer
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &id_type::CustomerId {
&self.customer_id
}
/// Get the global identifier of Customer
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &id_type::GlobalCustomerId {
&self.id
}
/// Get the connector customer ID for the specified connector label, if present
#[cfg(feature = "v1")]
pub fn get_connector_customer_map(
&self,
) -> FxHashMap<id_type::MerchantConnectorAccountId, String> {
use masking::PeekInterface;
if let Some(connector_customer_value) = &self.connector_customer {
connector_customer_value
.peek()
.clone()
.parse_value("ConnectorCustomerMap")
.unwrap_or_default()
} else {
FxHashMap::default()
}
}
/// Get the connector customer ID for the specified connector label, if present
#[cfg(feature = "v1")]
pub fn get_connector_customer_id(&self, connector_label: &str) -> Option<&str> {
use masking::PeekInterface;
self.connector_customer
.as_ref()
.and_then(|connector_customer_value| {
connector_customer_value.peek().get(connector_label)
})
.and_then(|connector_customer| connector_customer.as_str())
}
/// Get the connector customer ID for the specified merchant connector account ID, if present
#[cfg(feature = "v2")]
pub fn get_connector_customer_id(
&self,
merchant_connector_account: &MerchantConnectorAccountTypeDetails,
) -> Option<&str> {
match merchant_connector_account {
MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(account) => {
let connector_account_id = account.get_id();
self.connector_customer
.as_ref()?
.get(&connector_account_id)
.map(|connector_customer_id| connector_customer_id.as_str())
}
MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None,
}
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl behaviour::Conversion for Customer {
type DstType = diesel_models::customers::Customer;
type NewDstType = diesel_models::customers::CustomerNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::customers::Customer {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
phone_country_code: self.phone_country_code,
description: self.description,
created_at: self.created_at,
metadata: self.metadata,
modified_at: self.modified_at,
connector_customer: self.connector_customer,
address_id: self.address_id,
default_payment_method_id: self.default_payment_method_id,
updated_by: self.updated_by,
version: self.version,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
})
}
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
_key_store_ref_id: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let decrypted = types::crypto_operation(
state,
common_utils::type_name!(Self::DstType),
types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable(
EncryptedCustomer {
name: item.name.clone(),
phone: item.phone.clone(),
email: item.email.clone(),
tax_registration_id: item.tax_registration_id.clone(),
},
)),
keymanager::Identifier::Merchant(item.merchant_id.clone()),
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
})?;
let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
},
)?;
Ok(Self {
customer_id: item.customer_id,
merchant_id: item.merchant_id,
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
phone_country_code: item.phone_country_code,
description: item.description,
created_at: item.created_at,
metadata: item.metadata,
modified_at: item.modified_at,
connector_customer: item.connector_customer,
address_id: item.address_id,
default_payment_method_id: item.default_payment_method_id,
updated_by: item.updated_by,
version: item.version,
tax_registration_id: encryptable_customer.tax_registration_id,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(diesel_models::customers::CustomerNew {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
description: self.description,
phone_country_code: self.phone_country_code,
metadata: self.metadata,
created_at: now,
modified_at: now,
connector_customer: self.connector_customer,
address_id: self.address_id,
updated_by: self.updated_by,
version: self.version,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
})
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl behaviour::Conversion for Customer {
type DstType = diesel_models::customers::Customer;
type NewDstType = diesel_models::customers::CustomerNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::customers::Customer {
id: self.id,
merchant_reference_id: self.merchant_reference_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
phone_country_code: self.phone_country_code,
description: self.description,
created_at: self.created_at,
metadata: self.metadata,
modified_at: self.modified_at,
connector_customer: self.connector_customer,
default_payment_method_id: self.default_payment_method_id,
updated_by: self.updated_by,
default_billing_address: self.default_billing_address,
default_shipping_address: self.default_shipping_address,
version: self.version,
status: self.status,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
})
}
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
_key_store_ref_id: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let decrypted = types::crypto_operation(
state,
common_utils::type_name!(Self::DstType),
types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable(
EncryptedCustomer {
name: item.name.clone(),
phone: item.phone.clone(),
email: item.email.clone(),
tax_registration_id: item.tax_registration_id.clone(),
},
)),
keymanager::Identifier::Merchant(item.merchant_id.clone()),
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
})?;
let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
},
)?;
Ok(Self {
id: item.id,
merchant_reference_id: item.merchant_reference_id,
merchant_id: item.merchant_id,
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
phone_country_code: item.phone_country_code,
description: item.description,
created_at: item.created_at,
metadata: item.metadata,
modified_at: item.modified_at,
connector_customer: item.connector_customer,
default_payment_method_id: item.default_payment_method_id,
updated_by: item.updated_by,
default_billing_address: item.default_billing_address,
default_shipping_address: item.default_shipping_address,
version: item.version,
status: item.status,
tax_registration_id: encryptable_customer.tax_registration_id,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(diesel_models::customers::CustomerNew {
id: self.id,
merchant_reference_id: self.merchant_reference_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
description: self.description,
phone_country_code: self.phone_country_code,
metadata: self.metadata,
default_payment_method_id: None,
created_at: now,
modified_at: now,
connector_customer: self.connector_customer,
updated_by: self.updated_by,
default_billing_address: self.default_billing_address,
default_shipping_address: self.default_shipping_address,
version: common_types::consts::API_VERSION,
status: self.status,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
})
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct CustomerGeneralUpdate {
pub name: crypto::OptionalEncryptableName,
pub email: Box<crypto::OptionalEncryptableEmail>,
pub phone: Box<crypto::OptionalEncryptablePhone>,
pub description: Option<Description>,
pub phone_country_code: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Box<Option<common_types::customers::ConnectorCustomerMap>>,
pub default_billing_address: Option<Encryption>,
pub default_shipping_address: Option<Encryption>,
pub default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>,
pub status: Option<DeleteStatus>,
pub tax_registration_id: crypto::OptionalEncryptableSecretString,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub enum CustomerUpdate {
Update(Box<CustomerGeneralUpdate>),
ConnectorCustomer {
connector_customer: Option<common_types::customers::ConnectorCustomerMap>,
},
UpdateDefaultPaymentMethod {
default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>,
},
}
#[cfg(feature = "v2")]
impl From<CustomerUpdate> for CustomerUpdateInternal {
fn from(customer_update: CustomerUpdate) -> Self {
match customer_update {
CustomerUpdate::Update(update) => {
let CustomerGeneralUpdate {
name,
email,
phone,
description,
phone_country_code,
metadata,
connector_customer,
default_billing_address,
default_shipping_address,
default_payment_method_id,
status,
tax_registration_id,
} = *update;
Self {
name: name.map(Encryption::from),
email: email.map(Encryption::from),
phone: phone.map(Encryption::from),
description,
phone_country_code,
metadata,
connector_customer: *connector_customer,
modified_at: date_time::now(),
default_billing_address,
default_shipping_address,
default_payment_method_id,
updated_by: None,
status,
tax_registration_id: tax_registration_id.map(Encryption::from),
}
}
CustomerUpdate::ConnectorCustomer { connector_customer } => Self {
connector_customer,
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
modified_at: date_time::now(),
default_payment_method_id: None,
updated_by: None,
default_billing_address: None,
default_shipping_address: None,
status: None,
tax_registration_id: None,
},
CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id,
} => Self {
default_payment_method_id,
modified_at: date_time::now(),
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
connector_customer: None,
updated_by: None,
default_billing_address: None,
default_shipping_address: None,
status: None,
tax_registration_id: None,
},
}
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub enum CustomerUpdate {
Update {
name: crypto::OptionalEncryptableName,
email: crypto::OptionalEncryptableEmail,
phone: Box<crypto::OptionalEncryptablePhone>,
description: Option<Description>,
phone_country_code: Option<String>,
metadata: Box<Option<pii::SecretSerdeValue>>,
connector_customer: Box<Option<pii::SecretSerdeValue>>,
address_id: Option<String>,
tax_registration_id: crypto::OptionalEncryptableSecretString,
},
ConnectorCustomer {
connector_customer: Option<pii::SecretSerdeValue>,
},
UpdateDefaultPaymentMethod {
default_payment_method_id: Option<Option<String>>,
},
}
#[cfg(feature = "v1")]
impl From<CustomerUpdate> for CustomerUpdateInternal {
fn from(customer_update: CustomerUpdate) -> Self {
match customer_update {
CustomerUpdate::Update {
name,
email,
phone,
description,
phone_country_code,
metadata,
connector_customer,
address_id,
tax_registration_id,
} => Self {
name: name.map(Encryption::from),
email: email.map(Encryption::from),
phone: phone.map(Encryption::from),
description,
phone_country_code,
metadata: *metadata,
connector_customer: *connector_customer,
modified_at: date_time::now(),
address_id,
default_payment_method_id: None,
updated_by: None,
tax_registration_id: tax_registration_id.map(Encryption::from),
},
CustomerUpdate::ConnectorCustomer { connector_customer } => Self {
connector_customer,
modified_at: date_time::now(),
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
default_payment_method_id: None,
updated_by: None,
address_id: None,
tax_registration_id: None,
},
CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id,
} => Self {
default_payment_method_id,
modified_at: date_time::now(),
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
connector_customer: None,
updated_by: None,
address_id: None,
tax_registration_id: None,
},
}
}
}
pub struct CustomerListConstraints {
pub limit: u16,
pub offset: Option<u32>,
pub customer_id: Option<id_type::CustomerId>,
pub time_range: Option<common_utils::types::TimeRange>,
}
impl From<CustomerListConstraints> for query::CustomerListConstraints {
fn from(value: CustomerListConstraints) -> Self {
Self {
limit: i64::from(value.limit),
offset: value.offset.map(i64::from),
customer_id: value.customer_id,
time_range: value.time_range,
}
}
}
#[async_trait::async_trait]
pub trait CustomerInterface
where
Customer: behaviour::Conversion<
DstType = storage_types::Customer,
NewDstType = storage_types::CustomerNew,
>,
{
type Error;
#[cfg(feature = "v1")]
async fn delete_customer_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, Self::Error>;
#[cfg(feature = "v1")]
async fn find_customer_optional_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<Customer>, Self::Error>;
#[cfg(feature = "v1")]
async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<Customer>, Self::Error>;
#[cfg(feature = "v2")]
async fn find_optional_by_merchant_id_merchant_reference_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<Customer>, Self::Error>;
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn update_customer_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
customer: Customer,
customer_update: CustomerUpdate,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
#[cfg(feature = "v1")]
async fn find_customer_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
#[cfg(feature = "v2")]
async fn find_customer_by_merchant_reference_id_merchant_id(
&self,
state: &KeyManagerState,
merchant_reference_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
constraints: CustomerListConstraints,
) -> CustomResult<Vec<Customer>, Self::Error>;
async fn list_customers_by_merchant_id_with_count(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
constraints: CustomerListConstraints,
) -> CustomResult<(Vec<Customer>, usize), Self::Error>;
async fn insert_customer(
&self,
customer_data: Customer,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn update_customer_by_global_id(
&self,
state: &KeyManagerState,
id: &id_type::GlobalCustomerId,
customer: Customer,
customer_update: CustomerUpdate,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
#[cfg(feature = "v2")]
async fn find_customer_by_global_id(
&self,
state: &KeyManagerState,
id: &id_type::GlobalCustomerId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
}
#[cfg(feature = "v1")]
#[instrument]
pub async fn update_connector_customer_in_customers(
connector_label: &str,
customer: Option<&Customer>,
connector_customer_id: Option<String>,
) -> Option<CustomerUpdate> {
let mut connector_customer_map = customer
.and_then(|customer| customer.connector_customer.clone().expose_option())
.and_then(|connector_customer| connector_customer.as_object().cloned())
.unwrap_or_default();
let updated_connector_customer_map = connector_customer_id.map(|connector_customer_id| {
let connector_customer_value = serde_json::Value::String(connector_customer_id);
connector_customer_map.insert(connector_label.to_string(), connector_customer_value);
connector_customer_map
});
updated_connector_customer_map
.map(serde_json::Value::Object)
.map(
|connector_customer_value| CustomerUpdate::ConnectorCustomer {
connector_customer: Some(pii::SecretSerdeValue::new(connector_customer_value)),
},
)
}
#[cfg(feature = "v2")]
#[instrument]
pub async fn update_connector_customer_in_customers(
merchant_connector_account: &MerchantConnectorAccountTypeDetails,
customer: Option<&Customer>,
connector_customer_id: Option<String>,
) -> Option<CustomerUpdate> {
match merchant_connector_account {
MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(account) => {
connector_customer_id.map(|new_conn_cust_id| {
let connector_account_id = account.get_id().clone();
let mut connector_customer_map = customer
.and_then(|customer| customer.connector_customer.clone())
.unwrap_or_default();
connector_customer_map.insert(connector_account_id, new_conn_cust_id);
CustomerUpdate::ConnectorCustomer {
connector_customer: Some(connector_customer_map),
}
})
}
// TODO: Construct connector_customer for MerchantConnectorDetails if required by connector.
MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
todo!("Handle connector_customer construction for MerchantConnectorDetails");
}
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/customer.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 3,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-2473829800454306751
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_response_types.rs
// Contains: 13 structs, 7 enums
pub mod disputes;
pub mod fraud_check;
pub mod revenue_recovery;
pub mod subscriptions;
use std::collections::HashMap;
use api_models::payments::AddressDetails;
use common_utils::{pii, request::Method, types::MinorUnit};
pub use disputes::{
AcceptDisputeResponse, DefendDisputeResponse, DisputeSyncResponse, FetchDisputesResponse,
SubmitEvidenceResponse,
};
use serde::Serialize;
use crate::{
errors::api_error_response::ApiErrorResponse,
router_request_types::{authentication::AuthNFlowType, ResponseId},
vault::PaymentMethodVaultingData,
};
#[derive(Debug, Clone)]
pub struct RefundsResponseData {
pub connector_refund_id: String,
pub refund_status: common_enums::RefundStatus,
// pub amount_received: Option<i32>, // Calculation for amount received not in place yet
}
#[derive(Debug, Clone, Serialize)]
pub struct ConnectorCustomerResponseData {
pub connector_customer_id: String,
pub name: Option<String>,
pub email: Option<String>,
pub billing_address: Option<AddressDetails>,
}
impl ConnectorCustomerResponseData {
pub fn new_with_customer_id(connector_customer_id: String) -> Self {
Self::new(connector_customer_id, None, None, None)
}
pub fn new(
connector_customer_id: String,
name: Option<String>,
email: Option<String>,
billing_address: Option<AddressDetails>,
) -> Self {
Self {
connector_customer_id,
name,
email,
billing_address,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub enum PaymentsResponseData {
TransactionResponse {
resource_id: ResponseId,
redirection_data: Box<Option<RedirectForm>>,
mandate_reference: Box<Option<MandateReference>>,
connector_metadata: Option<serde_json::Value>,
network_txn_id: Option<String>,
connector_response_reference_id: Option<String>,
incremental_authorization_allowed: Option<bool>,
charges: Option<common_types::payments::ConnectorChargeResponseData>,
},
MultipleCaptureResponse {
// pending_capture_id_list: Vec<String>,
capture_sync_response_list: HashMap<String, CaptureSyncResponse>,
},
SessionResponse {
session_token: api_models::payments::SessionToken,
},
SessionTokenResponse {
session_token: String,
},
TransactionUnresolvedResponse {
resource_id: ResponseId,
//to add more info on cypto response, like `unresolved` reason(overpaid, underpaid, delayed)
reason: Option<api_models::enums::UnresolvedResponseReason>,
connector_response_reference_id: Option<String>,
},
TokenizationResponse {
token: String,
},
ConnectorCustomerResponse(ConnectorCustomerResponseData),
ThreeDSEnrollmentResponse {
enrolled_v2: bool,
related_transaction_id: Option<String>,
},
PreProcessingResponse {
pre_processing_id: PreprocessingResponseId,
connector_metadata: Option<serde_json::Value>,
session_token: Option<api_models::payments::SessionToken>,
connector_response_reference_id: Option<String>,
},
IncrementalAuthorizationResponse {
status: common_enums::AuthorizationStatus,
connector_authorization_id: Option<String>,
error_code: Option<String>,
error_message: Option<String>,
},
PostProcessingResponse {
session_token: Option<api_models::payments::OpenBankingSessionToken>,
},
PaymentResourceUpdateResponse {
status: common_enums::PaymentResourceUpdateStatus,
},
PaymentsCreateOrderResponse {
order_id: String,
},
}
#[derive(Debug, Clone)]
pub struct GiftCardBalanceCheckResponseData {
pub balance: MinorUnit,
pub currency: common_enums::Currency,
}
#[derive(Debug, Clone)]
pub struct TaxCalculationResponseData {
pub order_tax_amount: MinorUnit,
}
#[derive(Serialize, Debug, Clone)]
pub struct MandateReference {
pub connector_mandate_id: Option<String>,
pub payment_method_id: Option<String>,
pub mandate_metadata: Option<pii::SecretSerdeValue>,
pub connector_mandate_request_reference_id: Option<String>,
}
#[derive(Debug, Clone, Serialize)]
pub enum CaptureSyncResponse {
Success {
resource_id: ResponseId,
status: common_enums::AttemptStatus,
connector_response_reference_id: Option<String>,
amount: Option<MinorUnit>,
},
Error {
code: String,
message: String,
reason: Option<String>,
status_code: u16,
amount: Option<MinorUnit>,
},
}
impl CaptureSyncResponse {
pub fn get_amount_captured(&self) -> Option<MinorUnit> {
match self {
Self::Success { amount, .. } | Self::Error { amount, .. } => *amount,
}
}
pub fn get_connector_response_reference_id(&self) -> Option<String> {
match self {
Self::Success {
connector_response_reference_id,
..
} => connector_response_reference_id.clone(),
Self::Error { .. } => None,
}
}
}
impl PaymentsResponseData {
pub fn get_connector_metadata(&self) -> Option<masking::Secret<serde_json::Value>> {
match self {
Self::TransactionResponse {
connector_metadata, ..
}
| Self::PreProcessingResponse {
connector_metadata, ..
} => connector_metadata.clone().map(masking::Secret::new),
_ => None,
}
}
pub fn get_network_transaction_id(&self) -> Option<String> {
match self {
Self::TransactionResponse { network_txn_id, .. } => network_txn_id.clone(),
_ => None,
}
}
pub fn get_connector_transaction_id(
&self,
) -> Result<String, error_stack::Report<ApiErrorResponse>> {
match self {
Self::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(txn_id),
..
} => Ok(txn_id.to_string()),
_ => Err(ApiErrorResponse::MissingRequiredField {
field_name: "ConnectorTransactionId",
}
.into()),
}
}
pub fn merge_transaction_responses(
auth_response: &Self,
capture_response: &Self,
) -> Result<Self, error_stack::Report<ApiErrorResponse>> {
match (auth_response, capture_response) {
(
Self::TransactionResponse {
resource_id: _,
redirection_data: auth_redirection_data,
mandate_reference: auth_mandate_reference,
connector_metadata: auth_connector_metadata,
network_txn_id: auth_network_txn_id,
connector_response_reference_id: auth_connector_response_reference_id,
incremental_authorization_allowed: auth_incremental_auth_allowed,
charges: auth_charges,
},
Self::TransactionResponse {
resource_id: capture_resource_id,
redirection_data: capture_redirection_data,
mandate_reference: capture_mandate_reference,
connector_metadata: capture_connector_metadata,
network_txn_id: capture_network_txn_id,
connector_response_reference_id: capture_connector_response_reference_id,
incremental_authorization_allowed: capture_incremental_auth_allowed,
charges: capture_charges,
},
) => Ok(Self::TransactionResponse {
resource_id: capture_resource_id.clone(),
redirection_data: Box::new(
capture_redirection_data
.clone()
.or_else(|| *auth_redirection_data.clone()),
),
mandate_reference: Box::new(
auth_mandate_reference
.clone()
.or_else(|| *capture_mandate_reference.clone()),
),
connector_metadata: capture_connector_metadata
.clone()
.or(auth_connector_metadata.clone()),
network_txn_id: capture_network_txn_id
.clone()
.or(auth_network_txn_id.clone()),
connector_response_reference_id: capture_connector_response_reference_id
.clone()
.or(auth_connector_response_reference_id.clone()),
incremental_authorization_allowed: (*capture_incremental_auth_allowed)
.or(*auth_incremental_auth_allowed),
charges: auth_charges.clone().or(capture_charges.clone()),
}),
_ => Err(ApiErrorResponse::NotSupported {
message: "Invalid Flow ".to_owned(),
}
.into()),
}
}
#[cfg(feature = "v2")]
pub fn get_updated_connector_token_details(
&self,
original_connector_mandate_request_reference_id: Option<String>,
) -> Option<diesel_models::ConnectorTokenDetails> {
if let Self::TransactionResponse {
mandate_reference, ..
} = self
{
mandate_reference.clone().map(|mandate_ref| {
let connector_mandate_id = mandate_ref.connector_mandate_id;
let connector_mandate_request_reference_id = mandate_ref
.connector_mandate_request_reference_id
.or(original_connector_mandate_request_reference_id);
diesel_models::ConnectorTokenDetails {
connector_mandate_id,
connector_token_request_reference_id: connector_mandate_request_reference_id,
}
})
} else {
None
}
}
}
#[derive(Debug, Clone, Serialize)]
pub enum PreprocessingResponseId {
PreProcessingId(String),
ConnectorTransactionId(String),
}
#[derive(Debug, Eq, PartialEq, Clone, Serialize, serde::Deserialize)]
pub enum RedirectForm {
Form {
endpoint: String,
method: Method,
form_fields: HashMap<String, String>,
},
Html {
html_data: String,
},
BarclaycardAuthSetup {
access_token: String,
ddc_url: String,
reference_id: String,
},
BarclaycardConsumerAuth {
access_token: String,
step_up_url: String,
},
BlueSnap {
payment_fields_token: String, // payment-field-token
},
CybersourceAuthSetup {
access_token: String,
ddc_url: String,
reference_id: String,
},
CybersourceConsumerAuth {
access_token: String,
step_up_url: String,
},
DeutschebankThreeDSChallengeFlow {
acs_url: String,
creq: String,
},
Payme,
Braintree {
client_token: String,
card_token: String,
bin: String,
acs_url: String,
},
Nmi {
amount: String,
currency: common_enums::Currency,
public_key: masking::Secret<String>,
customer_vault_id: String,
order_id: String,
},
Mifinity {
initialization_token: String,
},
WorldpayDDCForm {
endpoint: url::Url,
method: Method,
form_fields: HashMap<String, String>,
collection_id: Option<String>,
},
}
impl From<(url::Url, Method)> for RedirectForm {
fn from((mut redirect_url, method): (url::Url, Method)) -> Self {
let form_fields = HashMap::from_iter(
redirect_url
.query_pairs()
.map(|(key, value)| (key.to_string(), value.to_string())),
);
// Do not include query params in the endpoint
redirect_url.set_query(None);
Self::Form {
endpoint: redirect_url.to_string(),
method,
form_fields,
}
}
}
impl From<RedirectForm> for diesel_models::payment_attempt::RedirectForm {
fn from(redirect_form: RedirectForm) -> Self {
match redirect_form {
RedirectForm::Form {
endpoint,
method,
form_fields,
} => Self::Form {
endpoint,
method,
form_fields,
},
RedirectForm::Html { html_data } => Self::Html { html_data },
RedirectForm::BarclaycardAuthSetup {
access_token,
ddc_url,
reference_id,
} => Self::BarclaycardAuthSetup {
access_token,
ddc_url,
reference_id,
},
RedirectForm::BarclaycardConsumerAuth {
access_token,
step_up_url,
} => Self::BarclaycardConsumerAuth {
access_token,
step_up_url,
},
RedirectForm::BlueSnap {
payment_fields_token,
} => Self::BlueSnap {
payment_fields_token,
},
RedirectForm::CybersourceAuthSetup {
access_token,
ddc_url,
reference_id,
} => Self::CybersourceAuthSetup {
access_token,
ddc_url,
reference_id,
},
RedirectForm::CybersourceConsumerAuth {
access_token,
step_up_url,
} => Self::CybersourceConsumerAuth {
access_token,
step_up_url,
},
RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url, creq } => {
Self::DeutschebankThreeDSChallengeFlow { acs_url, creq }
}
RedirectForm::Payme => Self::Payme,
RedirectForm::Braintree {
client_token,
card_token,
bin,
acs_url,
} => Self::Braintree {
client_token,
card_token,
bin,
acs_url,
},
RedirectForm::Nmi {
amount,
currency,
public_key,
customer_vault_id,
order_id,
} => Self::Nmi {
amount,
currency,
public_key,
customer_vault_id,
order_id,
},
RedirectForm::Mifinity {
initialization_token,
} => Self::Mifinity {
initialization_token,
},
RedirectForm::WorldpayDDCForm {
endpoint,
method,
form_fields,
collection_id,
} => Self::WorldpayDDCForm {
endpoint: common_utils::types::Url::wrap(endpoint),
method,
form_fields,
collection_id,
},
}
}
}
impl From<diesel_models::payment_attempt::RedirectForm> for RedirectForm {
fn from(redirect_form: diesel_models::payment_attempt::RedirectForm) -> Self {
match redirect_form {
diesel_models::payment_attempt::RedirectForm::Form {
endpoint,
method,
form_fields,
} => Self::Form {
endpoint,
method,
form_fields,
},
diesel_models::payment_attempt::RedirectForm::Html { html_data } => {
Self::Html { html_data }
}
diesel_models::payment_attempt::RedirectForm::BarclaycardAuthSetup {
access_token,
ddc_url,
reference_id,
} => Self::BarclaycardAuthSetup {
access_token,
ddc_url,
reference_id,
},
diesel_models::payment_attempt::RedirectForm::BarclaycardConsumerAuth {
access_token,
step_up_url,
} => Self::BarclaycardConsumerAuth {
access_token,
step_up_url,
},
diesel_models::payment_attempt::RedirectForm::BlueSnap {
payment_fields_token,
} => Self::BlueSnap {
payment_fields_token,
},
diesel_models::payment_attempt::RedirectForm::CybersourceAuthSetup {
access_token,
ddc_url,
reference_id,
} => Self::CybersourceAuthSetup {
access_token,
ddc_url,
reference_id,
},
diesel_models::payment_attempt::RedirectForm::CybersourceConsumerAuth {
access_token,
step_up_url,
} => Self::CybersourceConsumerAuth {
access_token,
step_up_url,
},
diesel_models::RedirectForm::DeutschebankThreeDSChallengeFlow { acs_url, creq } => {
Self::DeutschebankThreeDSChallengeFlow { acs_url, creq }
}
diesel_models::payment_attempt::RedirectForm::Payme => Self::Payme,
diesel_models::payment_attempt::RedirectForm::Braintree {
client_token,
card_token,
bin,
acs_url,
} => Self::Braintree {
client_token,
card_token,
bin,
acs_url,
},
diesel_models::payment_attempt::RedirectForm::Nmi {
amount,
currency,
public_key,
customer_vault_id,
order_id,
} => Self::Nmi {
amount,
currency,
public_key,
customer_vault_id,
order_id,
},
diesel_models::payment_attempt::RedirectForm::Mifinity {
initialization_token,
} => Self::Mifinity {
initialization_token,
},
diesel_models::payment_attempt::RedirectForm::WorldpayDDCForm {
endpoint,
method,
form_fields,
collection_id,
} => Self::WorldpayDDCForm {
endpoint: endpoint.into_inner(),
method,
form_fields,
collection_id,
},
}
}
}
#[derive(Default, Clone, Debug)]
pub struct UploadFileResponse {
pub provider_file_id: String,
}
#[derive(Clone, Debug)]
pub struct RetrieveFileResponse {
pub file_data: Vec<u8>,
}
#[cfg(feature = "payouts")]
#[derive(Clone, Debug, Default)]
pub struct PayoutsResponseData {
pub status: Option<common_enums::PayoutStatus>,
pub connector_payout_id: Option<String>,
pub payout_eligible: Option<bool>,
pub should_add_next_step_to_process_tracker: bool,
pub error_code: Option<String>,
pub error_message: Option<String>,
pub payout_connector_metadata: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Clone)]
pub struct VerifyWebhookSourceResponseData {
pub verify_webhook_status: VerifyWebhookStatus,
}
#[derive(Debug, Clone)]
pub enum VerifyWebhookStatus {
SourceVerified,
SourceNotVerified,
}
#[derive(Debug, Clone)]
pub struct MandateRevokeResponseData {
pub mandate_status: common_enums::MandateStatus,
}
#[derive(Debug, Clone)]
pub enum AuthenticationResponseData {
PreAuthVersionCallResponse {
maximum_supported_3ds_version: common_utils::types::SemanticVersion,
},
PreAuthThreeDsMethodCallResponse {
threeds_server_transaction_id: String,
three_ds_method_data: Option<String>,
three_ds_method_url: Option<String>,
connector_metadata: Option<serde_json::Value>,
},
PreAuthNResponse {
threeds_server_transaction_id: String,
maximum_supported_3ds_version: common_utils::types::SemanticVersion,
connector_authentication_id: String,
three_ds_method_data: Option<String>,
three_ds_method_url: Option<String>,
message_version: common_utils::types::SemanticVersion,
connector_metadata: Option<serde_json::Value>,
directory_server_id: Option<String>,
},
AuthNResponse {
authn_flow_type: AuthNFlowType,
authentication_value: Option<masking::Secret<String>>,
trans_status: common_enums::TransactionStatus,
connector_metadata: Option<serde_json::Value>,
ds_trans_id: Option<String>,
eci: Option<String>,
challenge_code: Option<String>,
challenge_cancel: Option<String>,
challenge_code_reason: Option<String>,
message_extension: Option<pii::SecretSerdeValue>,
},
PostAuthNResponse {
trans_status: common_enums::TransactionStatus,
authentication_value: Option<masking::Secret<String>>,
eci: Option<String>,
challenge_cancel: Option<String>,
challenge_code_reason: Option<String>,
},
}
#[derive(Debug, Clone)]
pub struct CompleteAuthorizeRedirectResponse {
pub params: Option<masking::Secret<String>>,
pub payload: Option<pii::SecretSerdeValue>,
}
/// Represents details of a payment method.
#[derive(Debug, Clone)]
pub struct PaymentMethodDetails {
/// Indicates whether mandates are supported by this payment method.
pub mandates: common_enums::FeatureStatus,
/// Indicates whether refund is supported by this payment method.
pub refunds: common_enums::FeatureStatus,
/// List of supported capture methods
pub supported_capture_methods: Vec<common_enums::CaptureMethod>,
/// Payment method specific features
pub specific_features: Option<api_models::feature_matrix::PaymentMethodSpecificFeatures>,
}
/// list of payment method types and metadata related to them
pub type PaymentMethodTypeMetadata = HashMap<common_enums::PaymentMethodType, PaymentMethodDetails>;
/// list of payment methods, payment method types and metadata related to them
pub type SupportedPaymentMethods = HashMap<common_enums::PaymentMethod, PaymentMethodTypeMetadata>;
#[derive(Debug, Clone)]
pub struct ConnectorInfo {
/// Display name of the Connector
pub display_name: &'static str,
/// Description of the connector.
pub description: &'static str,
/// Connector Type
pub connector_type: common_enums::HyperswitchConnectorCategory,
/// Integration status of the connector
pub integration_status: common_enums::ConnectorIntegrationStatus,
}
pub trait SupportedPaymentMethodsExt {
fn add(
&mut self,
payment_method: common_enums::PaymentMethod,
payment_method_type: common_enums::PaymentMethodType,
payment_method_details: PaymentMethodDetails,
);
}
impl SupportedPaymentMethodsExt for SupportedPaymentMethods {
fn add(
&mut self,
payment_method: common_enums::PaymentMethod,
payment_method_type: common_enums::PaymentMethodType,
payment_method_details: PaymentMethodDetails,
) {
if let Some(payment_method_data) = self.get_mut(&payment_method) {
payment_method_data.insert(payment_method_type, payment_method_details);
} else {
let mut payment_method_type_metadata = PaymentMethodTypeMetadata::new();
payment_method_type_metadata.insert(payment_method_type, payment_method_details);
self.insert(payment_method, payment_method_type_metadata);
}
}
}
#[derive(Debug, Clone)]
pub enum VaultResponseData {
ExternalVaultCreateResponse {
session_id: masking::Secret<String>,
client_secret: masking::Secret<String>,
},
ExternalVaultInsertResponse {
connector_vault_id: String,
fingerprint_id: String,
},
ExternalVaultRetrieveResponse {
vault_data: PaymentMethodVaultingData,
},
ExternalVaultDeleteResponse {
connector_vault_id: String,
},
}
impl Default for VaultResponseData {
fn default() -> Self {
Self::ExternalVaultInsertResponse {
connector_vault_id: String::new(),
fingerprint_id: String::new(),
}
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_response_types.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 7,
"num_structs": 13,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-2142487716945862170
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/gsm.rs
// Contains: 2 structs, 0 enums
use common_utils::{errors::ValidationError, ext_traits::StringExt};
use serde::{self, Deserialize, Serialize};
#[derive(Debug, Clone, Deserialize, Serialize, PartialEq, Eq)]
pub struct GatewayStatusMap {
pub connector: String,
pub flow: String,
pub sub_flow: String,
pub code: String,
pub message: String,
pub status: String,
pub router_error: Option<String>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub error_category: Option<common_enums::ErrorCategory>,
pub feature_data: common_types::domain::GsmFeatureData,
pub feature: common_enums::GsmFeature,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct GatewayStatusMappingUpdate {
pub status: Option<String>,
pub router_error: Option<Option<String>>,
pub decision: Option<common_enums::GsmDecision>,
pub step_up_possible: Option<bool>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub error_category: Option<common_enums::ErrorCategory>,
pub clear_pan_possible: Option<bool>,
pub feature_data: Option<common_types::domain::GsmFeatureData>,
pub feature: Option<common_enums::GsmFeature>,
}
impl TryFrom<GatewayStatusMap> for diesel_models::gsm::GatewayStatusMappingNew {
type Error = error_stack::Report<ValidationError>;
fn try_from(value: GatewayStatusMap) -> Result<Self, Self::Error> {
Ok(Self {
connector: value.connector.to_string(),
flow: value.flow,
sub_flow: value.sub_flow,
code: value.code,
message: value.message,
status: value.status.clone(),
router_error: value.router_error,
decision: value.feature_data.get_decision().to_string(),
step_up_possible: value
.feature_data
.get_retry_feature_data()
.map(|retry_feature_data| retry_feature_data.is_step_up_possible())
.unwrap_or(false),
unified_code: value.unified_code,
unified_message: value.unified_message,
error_category: value.error_category,
clear_pan_possible: value
.feature_data
.get_retry_feature_data()
.map(|retry_feature_data| retry_feature_data.is_clear_pan_possible())
.unwrap_or(false),
feature_data: Some(value.feature_data),
feature: Some(value.feature),
})
}
}
impl TryFrom<GatewayStatusMappingUpdate> for diesel_models::gsm::GatewayStatusMappingUpdate {
type Error = error_stack::Report<ValidationError>;
fn try_from(value: GatewayStatusMappingUpdate) -> Result<Self, Self::Error> {
Ok(Self {
status: value.status,
router_error: value.router_error,
decision: value.decision.map(|gsm_decision| gsm_decision.to_string()),
step_up_possible: value.step_up_possible,
unified_code: value.unified_code,
unified_message: value.unified_message,
error_category: value.error_category,
clear_pan_possible: value.clear_pan_possible,
feature_data: value.feature_data,
feature: value.feature,
})
}
}
impl TryFrom<diesel_models::gsm::GatewayStatusMap> for GatewayStatusMap {
type Error = ValidationError;
fn try_from(item: diesel_models::gsm::GatewayStatusMap) -> Result<Self, Self::Error> {
let decision =
StringExt::<common_enums::GsmDecision>::parse_enum(item.decision, "GsmDecision")
.map_err(|_| ValidationError::InvalidValue {
message: "Failed to parse GsmDecision".to_string(),
})?;
let db_feature_data = item.feature_data;
// The only case where `FeatureData` can be null is for legacy records
// (i.e., records created before `FeatureData` and related features were introduced).
// At that time, the only supported feature was `Retry`, so it's safe to default to it.
let feature_data = match db_feature_data {
Some(common_types::domain::GsmFeatureData::Retry(data)) => {
common_types::domain::GsmFeatureData::Retry(data)
}
None => common_types::domain::GsmFeatureData::Retry(
common_types::domain::RetryFeatureData {
step_up_possible: item.step_up_possible,
clear_pan_possible: item.clear_pan_possible,
alternate_network_possible: false,
decision,
},
),
};
let feature = item.feature.unwrap_or(common_enums::GsmFeature::Retry);
Ok(Self {
connector: item.connector,
flow: item.flow,
sub_flow: item.sub_flow,
code: item.code,
message: item.message,
status: item.status,
router_error: item.router_error,
unified_code: item.unified_code,
unified_message: item.unified_message,
error_category: item.error_category,
feature_data,
feature,
})
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/gsm.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_1374605185859014502
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/revenue_recovery.rs
// Contains: 4 structs, 0 enums
use api_models::{payments as api_payments, webhooks};
use common_enums::enums as common_enums;
use common_types::primitive_wrappers;
use common_utils::{id_type, pii, types as util_types};
use time::PrimitiveDateTime;
use crate::{
payments,
router_response_types::revenue_recovery::{
BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse,
},
ApiModelToDieselModelConvertor,
};
/// Recovery payload is unified struct constructed from billing connectors
#[derive(Debug)]
pub struct RevenueRecoveryAttemptData {
/// transaction amount against invoice, accepted in minor unit.
pub amount: util_types::MinorUnit,
/// currency of the transaction
pub currency: common_enums::Currency,
/// merchant reference id at billing connector. ex: invoice_id
pub merchant_reference_id: id_type::PaymentReferenceId,
/// transaction id reference at payment connector
pub connector_transaction_id: Option<util_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::AttemptStatus,
/// payment method of payment attempt.
pub payment_method_type: common_enums::PaymentMethod,
/// payment method sub type of the payment attempt.
pub payment_method_sub_type: common_enums::PaymentMethodType,
/// This field can be returned for both approved and refused Mastercard payments.
/// This code provides additional information about the type of transaction or the reason why the payment failed.
/// If the payment failed, the network advice code gives guidance on if and when you can retry the payment.
pub network_advice_code: Option<String>,
/// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed.
pub network_decline_code: Option<String>,
/// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better.
pub network_error_message: Option<String>,
/// Number of attempts made for an invoice
pub retry_count: Option<u16>,
/// Time when next invoice will be generated which will be equal to the end time of the current invoice
pub invoice_next_billing_time: Option<PrimitiveDateTime>,
/// Time at which the invoice created
pub invoice_billing_started_at_time: Option<PrimitiveDateTime>,
/// stripe specific id used to validate duplicate attempts in revenue recovery flow
pub charge_id: Option<String>,
/// Additional card details
pub card_info: api_payments::AdditionalCardInfo,
}
/// This is unified struct for Revenue Recovery Invoice Data and it is constructed from billing connectors
#[derive(Debug, Clone)]
pub struct RevenueRecoveryInvoiceData {
/// invoice amount at billing connector
pub amount: util_types::MinorUnit,
/// currency of the amount.
pub currency: common_enums::Currency,
/// merchant reference id at billing connector. ex: invoice_id
pub merchant_reference_id: id_type::PaymentReferenceId,
/// billing address id of the invoice
pub billing_address: Option<api_payments::Address>,
/// Retry count of the invoice
pub retry_count: Option<u16>,
/// Ending date of the invoice or the Next billing time of the Subscription
pub next_billing_at: Option<PrimitiveDateTime>,
/// Invoice Starting Time
pub billing_started_at: Option<PrimitiveDateTime>,
/// metadata of the merchant
pub metadata: Option<pii::SecretSerdeValue>,
/// Allow partial authorization for this payment
pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,
}
#[derive(Clone, Debug)]
pub struct RecoveryPaymentIntent {
pub payment_id: id_type::GlobalPaymentId,
pub status: common_enums::IntentStatus,
pub feature_metadata: Option<api_payments::FeatureMetadata>,
pub merchant_id: id_type::MerchantId,
pub merchant_reference_id: Option<id_type::PaymentReferenceId>,
pub invoice_amount: util_types::MinorUnit,
pub invoice_currency: common_enums::Currency,
pub created_at: Option<PrimitiveDateTime>,
pub billing_address: Option<api_payments::Address>,
}
#[derive(Clone, Debug)]
pub struct RecoveryPaymentAttempt {
pub attempt_id: id_type::GlobalAttemptId,
pub attempt_status: common_enums::AttemptStatus,
pub feature_metadata: Option<api_payments::PaymentAttemptFeatureMetadata>,
pub amount: util_types::MinorUnit,
pub network_advice_code: Option<String>,
pub network_decline_code: Option<String>,
pub error_code: Option<String>,
pub created_at: PrimitiveDateTime,
}
impl RecoveryPaymentAttempt {
pub fn get_attempt_triggered_by(&self) -> Option<common_enums::TriggeredBy> {
self.feature_metadata.as_ref().and_then(|metadata| {
metadata
.revenue_recovery
.as_ref()
.map(|recovery| recovery.attempt_triggered_by)
})
}
}
impl From<&RevenueRecoveryInvoiceData> for api_payments::AmountDetails {
fn from(data: &RevenueRecoveryInvoiceData) -> Self {
let amount = api_payments::AmountDetailsSetter {
order_amount: data.amount.into(),
currency: data.currency,
shipping_cost: None,
order_tax_amount: None,
skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip,
skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip,
surcharge_amount: None,
tax_on_surcharge: None,
};
Self::new(amount)
}
}
impl From<&RevenueRecoveryInvoiceData> for api_payments::PaymentsCreateIntentRequest {
fn from(data: &RevenueRecoveryInvoiceData) -> Self {
let amount_details = api_payments::AmountDetails::from(data);
Self {
amount_details,
merchant_reference_id: Some(data.merchant_reference_id.clone()),
routing_algorithm_id: None,
// Payments in the revenue recovery flow are always recurring transactions,
// so capture method will be always automatic.
capture_method: Some(common_enums::CaptureMethod::Automatic),
authentication_type: Some(common_enums::AuthenticationType::NoThreeDs),
billing: data.billing_address.clone(),
shipping: None,
customer_id: None,
customer_present: Some(common_enums::PresenceOfCustomerDuringPayment::Absent),
description: None,
return_url: None,
setup_future_usage: None,
apply_mit_exemption: None,
statement_descriptor: None,
order_details: None,
allowed_payment_method_types: None,
metadata: data.metadata.clone(),
connector_metadata: None,
feature_metadata: None,
payment_link_enabled: None,
payment_link_config: None,
request_incremental_authorization: None,
session_expiry: None,
frm_metadata: None,
request_external_three_ds_authentication: None,
force_3ds_challenge: None,
merchant_connector_details: None,
enable_partial_authorization: data.enable_partial_authorization,
}
}
}
impl From<&BillingConnectorInvoiceSyncResponse> for RevenueRecoveryInvoiceData {
fn from(data: &BillingConnectorInvoiceSyncResponse) -> Self {
Self {
amount: data.amount,
currency: data.currency,
merchant_reference_id: data.merchant_reference_id.clone(),
billing_address: data.billing_address.clone(),
retry_count: data.retry_count,
next_billing_at: data.ends_at,
billing_started_at: data.created_at,
metadata: None,
enable_partial_authorization: None,
}
}
}
impl
From<(
&BillingConnectorPaymentsSyncResponse,
&RevenueRecoveryInvoiceData,
)> for RevenueRecoveryAttemptData
{
fn from(
data: (
&BillingConnectorPaymentsSyncResponse,
&RevenueRecoveryInvoiceData,
),
) -> Self {
let billing_connector_payment_details = data.0;
let invoice_details = data.1;
Self {
amount: billing_connector_payment_details.amount,
currency: billing_connector_payment_details.currency,
merchant_reference_id: billing_connector_payment_details
.merchant_reference_id
.clone(),
connector_transaction_id: billing_connector_payment_details
.connector_transaction_id
.clone(),
error_code: billing_connector_payment_details.error_code.clone(),
error_message: billing_connector_payment_details.error_message.clone(),
processor_payment_method_token: billing_connector_payment_details
.processor_payment_method_token
.clone(),
connector_customer_id: billing_connector_payment_details
.connector_customer_id
.clone(),
connector_account_reference_id: billing_connector_payment_details
.connector_account_reference_id
.clone(),
transaction_created_at: billing_connector_payment_details.transaction_created_at,
status: billing_connector_payment_details.status,
payment_method_type: billing_connector_payment_details.payment_method_type,
payment_method_sub_type: billing_connector_payment_details.payment_method_sub_type,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
retry_count: invoice_details.retry_count,
invoice_next_billing_time: invoice_details.next_billing_at,
charge_id: billing_connector_payment_details.charge_id.clone(),
invoice_billing_started_at_time: invoice_details.billing_started_at,
card_info: billing_connector_payment_details.card_info.clone(),
}
}
}
impl From<&RevenueRecoveryAttemptData> for api_payments::PaymentAttemptAmountDetails {
fn from(data: &RevenueRecoveryAttemptData) -> Self {
Self {
net_amount: data.amount,
amount_to_capture: None,
surcharge_amount: None,
tax_on_surcharge: None,
amount_capturable: data.amount,
shipping_cost: None,
order_tax_amount: None,
}
}
}
impl From<&RevenueRecoveryAttemptData> for Option<api_payments::RecordAttemptErrorDetails> {
fn from(data: &RevenueRecoveryAttemptData) -> Self {
data.error_code
.as_ref()
.zip(data.error_message.clone())
.map(|(code, message)| api_payments::RecordAttemptErrorDetails {
code: code.to_string(),
message: message.to_string(),
network_advice_code: data.network_advice_code.clone(),
network_decline_code: data.network_decline_code.clone(),
network_error_message: data.network_error_message.clone(),
})
}
}
impl From<&payments::PaymentIntent> for RecoveryPaymentIntent {
fn from(payment_intent: &payments::PaymentIntent) -> Self {
Self {
payment_id: payment_intent.id.clone(),
status: payment_intent.status,
feature_metadata: payment_intent
.feature_metadata
.clone()
.map(|feature_metadata| feature_metadata.convert_back()),
merchant_reference_id: payment_intent.merchant_reference_id.clone(),
invoice_amount: payment_intent.amount_details.order_amount,
invoice_currency: payment_intent.amount_details.currency,
billing_address: payment_intent
.billing_address
.clone()
.map(|address| api_payments::Address::from(address.into_inner())),
merchant_id: payment_intent.merchant_id.clone(),
created_at: Some(payment_intent.created_at),
}
}
}
impl From<&payments::payment_attempt::PaymentAttempt> for RecoveryPaymentAttempt {
fn from(payment_attempt: &payments::payment_attempt::PaymentAttempt) -> Self {
Self {
attempt_id: payment_attempt.id.clone(),
attempt_status: payment_attempt.status,
feature_metadata: payment_attempt
.feature_metadata
.clone()
.map(
|feature_metadata| api_payments::PaymentAttemptFeatureMetadata {
revenue_recovery: feature_metadata.revenue_recovery.map(|recovery| {
api_payments::PaymentAttemptRevenueRecoveryData {
attempt_triggered_by: recovery.attempt_triggered_by,
charge_id: recovery.charge_id,
}
}),
},
),
amount: payment_attempt.amount_details.get_net_amount(),
network_advice_code: payment_attempt
.error
.clone()
.and_then(|error| error.network_advice_code),
network_decline_code: payment_attempt
.error
.clone()
.and_then(|error| error.network_decline_code),
error_code: payment_attempt
.error
.as_ref()
.map(|error| error.code.clone()),
created_at: payment_attempt.created_at,
}
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/revenue_recovery.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 4,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-5840894648741443313
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/authentication.rs
// Contains: 2 structs, 0 enums
use common_utils::{
crypto::Encryptable, encryption::Encryption, errors::CustomResult, pii,
types::keymanager::ToEncryptable,
};
use masking::Secret;
use rustc_hash::FxHashMap;
use serde_json::Value;
#[cfg(feature = "v1")]
#[derive(Clone, Debug, router_derive::ToEncryption, serde::Serialize)]
pub struct Authentication {
pub authentication_id: common_utils::id_type::AuthenticationId,
pub merchant_id: common_utils::id_type::MerchantId,
pub authentication_connector: Option<String>,
pub connector_authentication_id: Option<String>,
pub authentication_data: Option<Value>,
pub payment_method_id: String,
pub authentication_type: Option<common_enums::DecoupledAuthenticationType>,
pub authentication_status: common_enums::AuthenticationStatus,
pub authentication_lifecycle_status: common_enums::AuthenticationLifecycleStatus,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: time::PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: time::PrimitiveDateTime,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub connector_metadata: Option<Value>,
pub maximum_supported_version: Option<common_utils::types::SemanticVersion>,
pub threeds_server_transaction_id: Option<String>,
pub cavv: Option<String>,
pub authentication_flow_type: Option<String>,
pub message_version: Option<common_utils::types::SemanticVersion>,
pub eci: Option<String>,
pub trans_status: Option<common_enums::TransactionStatus>,
pub acquirer_bin: Option<String>,
pub acquirer_merchant_id: Option<String>,
pub three_ds_method_data: Option<String>,
pub three_ds_method_url: Option<String>,
pub acs_url: Option<String>,
pub challenge_request: Option<String>,
pub acs_reference_number: Option<String>,
pub acs_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
pub profile_id: common_utils::id_type::ProfileId,
pub payment_id: Option<common_utils::id_type::PaymentId>,
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
pub ds_trans_id: Option<String>,
pub directory_server_id: Option<String>,
pub acquirer_country_code: Option<String>,
pub service_details: Option<Value>,
pub organization_id: common_utils::id_type::OrganizationId,
pub authentication_client_secret: Option<String>,
pub force_3ds_challenge: Option<bool>,
pub psd2_sca_exemption_type: Option<common_enums::ScaExemptionType>,
pub return_url: Option<String>,
pub amount: Option<common_utils::types::MinorUnit>,
pub currency: Option<common_enums::Currency>,
#[encrypt(ty = Value)]
pub billing_address: Option<Encryptable<crate::address::Address>>,
#[encrypt(ty = Value)]
pub shipping_address: Option<Encryptable<crate::address::Address>>,
pub browser_info: Option<Value>,
pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct PgRedirectResponseForAuthentication {
pub authentication_id: common_utils::id_type::AuthenticationId,
pub status: common_enums::TransactionStatus,
pub gateway_id: String,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub amount: Option<common_utils::types::MinorUnit>,
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/authentication.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-3581837965281108273
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/payment_method_data.rs
// Contains: 72 structs, 16 enums
#[cfg(feature = "v2")]
use std::str::FromStr;
use api_models::{
mandates,
payment_methods::{self},
payments::{additional_info as payment_additional_types, ExtendedCardInfo},
};
use common_enums::{enums as api_enums, GooglePayCardFundingSource};
use common_utils::{
ext_traits::{OptionExt, StringExt},
id_type,
new_type::{
MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId,
},
payout_method_utils,
pii::{self, Email},
};
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use time::Date;
// We need to derive Serialize and Deserialize because some parts of payment method data are being
// stored in the database as serde_json::Value
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum PaymentMethodData {
Card(Card),
CardDetailsForNetworkTransactionId(CardDetailsForNetworkTransactionId),
CardRedirect(CardRedirectData),
Wallet(WalletData),
PayLater(PayLaterData),
BankRedirect(BankRedirectData),
BankDebit(BankDebitData),
BankTransfer(Box<BankTransferData>),
Crypto(CryptoData),
MandatePayment,
Reward,
RealTimePayment(Box<RealTimePaymentData>),
Upi(UpiData),
Voucher(VoucherData),
GiftCard(Box<GiftCardData>),
CardToken(CardToken),
OpenBanking(OpenBankingData),
NetworkToken(NetworkTokenData),
MobilePayment(MobilePaymentData),
}
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum ExternalVaultPaymentMethodData {
Card(Box<ExternalVaultCard>),
VaultToken(VaultToken),
}
#[derive(Debug, Clone, PartialEq, Eq, serde::Serialize)]
pub enum ApplePayFlow {
Simplified(api_models::payments::PaymentProcessingDetails),
Manual,
}
impl PaymentMethodData {
pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> {
match self {
Self::Card(_) | Self::NetworkToken(_) | Self::CardDetailsForNetworkTransactionId(_) => {
Some(common_enums::PaymentMethod::Card)
}
Self::CardRedirect(_) => Some(common_enums::PaymentMethod::CardRedirect),
Self::Wallet(_) => Some(common_enums::PaymentMethod::Wallet),
Self::PayLater(_) => Some(common_enums::PaymentMethod::PayLater),
Self::BankRedirect(_) => Some(common_enums::PaymentMethod::BankRedirect),
Self::BankDebit(_) => Some(common_enums::PaymentMethod::BankDebit),
Self::BankTransfer(_) => Some(common_enums::PaymentMethod::BankTransfer),
Self::Crypto(_) => Some(common_enums::PaymentMethod::Crypto),
Self::Reward => Some(common_enums::PaymentMethod::Reward),
Self::RealTimePayment(_) => Some(common_enums::PaymentMethod::RealTimePayment),
Self::Upi(_) => Some(common_enums::PaymentMethod::Upi),
Self::Voucher(_) => Some(common_enums::PaymentMethod::Voucher),
Self::GiftCard(_) => Some(common_enums::PaymentMethod::GiftCard),
Self::OpenBanking(_) => Some(common_enums::PaymentMethod::OpenBanking),
Self::MobilePayment(_) => Some(common_enums::PaymentMethod::MobilePayment),
Self::CardToken(_) | Self::MandatePayment => None,
}
}
pub fn get_wallet_data(&self) -> Option<&WalletData> {
if let Self::Wallet(wallet_data) = self {
Some(wallet_data)
} else {
None
}
}
pub fn is_network_token_payment_method_data(&self) -> bool {
matches!(self, Self::NetworkToken(_))
}
pub fn get_co_badged_card_data(&self) -> Option<&payment_methods::CoBadgedCardData> {
if let Self::Card(card) = self {
card.co_badged_card_data.as_ref()
} else {
None
}
}
pub fn get_card_data(&self) -> Option<&Card> {
if let Self::Card(card) = self {
Some(card)
} else {
None
}
}
pub fn extract_debit_routing_saving_percentage(
&self,
network: &common_enums::CardNetwork,
) -> Option<f64> {
self.get_co_badged_card_data()?
.co_badged_card_networks_info
.0
.iter()
.find(|info| &info.network == network)
.map(|info| info.saving_percentage)
}
}
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct Card {
pub card_number: cards::CardNumber,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub card_cvc: Secret<String>,
pub card_issuer: Option<String>,
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>,
}
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct ExternalVaultCard {
pub card_number: Secret<String>,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub card_cvc: Secret<String>,
pub bin_number: Option<String>,
pub last_four: Option<String>,
pub card_issuer: Option<String>,
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>,
}
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct VaultToken {
pub card_cvc: Secret<String>,
pub card_holder_name: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct CardDetailsForNetworkTransactionId {
pub card_number: cards::CardNumber,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub card_issuer: Option<String>,
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
}
#[derive(PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct CardDetail {
pub card_number: cards::CardNumber,
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
pub card_issuer: Option<String>,
pub card_network: Option<api_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>,
}
impl CardDetailsForNetworkTransactionId {
pub fn get_nti_and_card_details_for_mit_flow(
recurring_details: mandates::RecurringDetails,
) -> Option<(api_models::payments::MandateReferenceId, Self)> {
let network_transaction_id_and_card_details = match recurring_details {
mandates::RecurringDetails::NetworkTransactionIdAndCardDetails(
network_transaction_id_and_card_details,
) => Some(network_transaction_id_and_card_details),
mandates::RecurringDetails::MandateId(_)
| mandates::RecurringDetails::PaymentMethodId(_)
| mandates::RecurringDetails::ProcessorPaymentToken(_) => None,
}?;
let mandate_reference_id = api_models::payments::MandateReferenceId::NetworkMandateId(
network_transaction_id_and_card_details
.network_transaction_id
.peek()
.to_string(),
);
Some((
mandate_reference_id,
network_transaction_id_and_card_details.clone().into(),
))
}
}
impl From<&Card> for CardDetail {
fn from(item: &Card) -> Self {
Self {
card_number: item.card_number.to_owned(),
card_exp_month: item.card_exp_month.to_owned(),
card_exp_year: item.card_exp_year.to_owned(),
card_issuer: item.card_issuer.to_owned(),
card_network: item.card_network.to_owned(),
card_type: item.card_type.to_owned(),
card_issuing_country: item.card_issuing_country.to_owned(),
bank_code: item.bank_code.to_owned(),
nick_name: item.nick_name.to_owned(),
card_holder_name: item.card_holder_name.to_owned(),
co_badged_card_data: item.co_badged_card_data.to_owned(),
}
}
}
impl From<mandates::NetworkTransactionIdAndCardDetails> for CardDetailsForNetworkTransactionId {
fn from(card_details_for_nti: mandates::NetworkTransactionIdAndCardDetails) -> Self {
Self {
card_number: card_details_for_nti.card_number,
card_exp_month: card_details_for_nti.card_exp_month,
card_exp_year: card_details_for_nti.card_exp_year,
card_issuer: card_details_for_nti.card_issuer,
card_network: card_details_for_nti.card_network,
card_type: card_details_for_nti.card_type,
card_issuing_country: card_details_for_nti.card_issuing_country,
bank_code: card_details_for_nti.bank_code,
nick_name: card_details_for_nti.nick_name,
card_holder_name: card_details_for_nti.card_holder_name,
}
}
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
pub enum CardRedirectData {
Knet {},
Benefit {},
MomoAtm {},
CardRedirect {},
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub enum PayLaterData {
KlarnaRedirect {},
KlarnaSdk { token: String },
AffirmRedirect {},
AfterpayClearpayRedirect {},
PayBrightRedirect {},
WalleyRedirect {},
FlexitiRedirect {},
AlmaRedirect {},
AtomeRedirect {},
BreadpayRedirect {},
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub enum WalletData {
AliPayQr(Box<AliPayQr>),
AliPayRedirect(AliPayRedirection),
AliPayHkRedirect(AliPayHkRedirection),
AmazonPay(AmazonPayWalletData),
AmazonPayRedirect(Box<AmazonPayRedirect>),
BluecodeRedirect {},
Paysera(Box<PayseraData>),
Skrill(Box<SkrillData>),
MomoRedirect(MomoRedirection),
KakaoPayRedirect(KakaoPayRedirection),
GoPayRedirect(GoPayRedirection),
GcashRedirect(GcashRedirection),
ApplePay(ApplePayWalletData),
ApplePayRedirect(Box<ApplePayRedirectData>),
ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>),
DanaRedirect {},
GooglePay(GooglePayWalletData),
GooglePayRedirect(Box<GooglePayRedirectData>),
GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>),
MbWayRedirect(Box<MbWayRedirection>),
MobilePayRedirect(Box<MobilePayRedirection>),
PaypalRedirect(PaypalRedirection),
PaypalSdk(PayPalWalletData),
Paze(PazeWalletData),
SamsungPay(Box<SamsungPayWalletData>),
TwintRedirect {},
VippsRedirect {},
TouchNGoRedirect(Box<TouchNGoRedirection>),
WeChatPayRedirect(Box<WeChatPayRedirection>),
WeChatPayQr(Box<WeChatPayQr>),
CashappQr(Box<CashappQr>),
SwishQr(SwishQrData),
Mifinity(MifinityData),
RevolutPay(RevolutPayData),
}
impl WalletData {
pub fn get_paze_wallet_data(&self) -> Option<&PazeWalletData> {
if let Self::Paze(paze_wallet_data) = self {
Some(paze_wallet_data)
} else {
None
}
}
pub fn get_apple_pay_wallet_data(&self) -> Option<&ApplePayWalletData> {
if let Self::ApplePay(apple_pay_wallet_data) = self {
Some(apple_pay_wallet_data)
} else {
None
}
}
pub fn get_google_pay_wallet_data(&self) -> Option<&GooglePayWalletData> {
if let Self::GooglePay(google_pay_wallet_data) = self {
Some(google_pay_wallet_data)
} else {
None
}
}
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MifinityData {
pub date_of_birth: Secret<Date>,
pub language_preference: Option<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct PazeWalletData {
pub complete_response: Secret<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayWalletData {
pub payment_credential: SamsungPayWalletCredentials,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayWalletCredentials {
pub method: Option<String>,
pub recurring_payment: Option<bool>,
pub card_brand: common_enums::SamsungPayCardBrand,
pub dpan_last_four_digits: Option<String>,
#[serde(rename = "card_last4digits")]
pub card_last_four_digits: String,
#[serde(rename = "3_d_s")]
pub token_data: SamsungPayTokenData,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct SamsungPayTokenData {
#[serde(rename = "type")]
pub three_ds_type: Option<String>,
pub version: String,
pub data: Secret<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GooglePayWalletData {
/// The type of payment method
pub pm_type: String,
/// User-facing message to describe the payment method that funds this transaction.
pub description: String,
/// The information of the payment method
pub info: GooglePayPaymentMethodInfo,
/// The tokenization data of Google pay
pub tokenization_data: common_types::payments::GpayTokenizationData,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ApplePayRedirectData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RevolutPayData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GooglePayRedirectData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GooglePayThirdPartySdkData {
pub token: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ApplePayThirdPartySdkData {
pub token: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct WeChatPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct WeChatPay {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct WeChatPayQr {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct CashappQr {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct PaypalRedirection {
/// paypal's email address
pub email: Option<Email>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct AliPayQr {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct AliPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct AliPayHkRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct AmazonPayRedirect {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct BluecodeQrRedirect {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct PayseraData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct SkrillData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MomoRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct KakaoPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GoPayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GcashRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MobilePayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct MbWayRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct GooglePayPaymentMethodInfo {
/// The name of the card network
pub card_network: String,
/// The details of the card
pub card_details: String,
/// assurance_details of the card
pub assurance_details: Option<GooglePayAssuranceDetails>,
/// Card funding source for the selected payment method
pub card_funding_source: Option<GooglePayCardFundingSource>,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct GooglePayAssuranceDetails {
///indicates that Cardholder possession validation has been performed
pub card_holder_authenticated: bool,
/// indicates that identification and verifications (ID&V) was performed
pub account_verified: bool,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct PayPalWalletData {
/// Token generated for the Apple pay
pub token: String,
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct TouchNGoRedirection {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct SwishQrData {}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ApplePayWalletData {
/// The payment data of Apple pay
pub payment_data: common_types::payments::ApplePayPaymentData,
/// The payment method of Apple pay
pub payment_method: ApplepayPaymentMethod,
/// The unique identifier for the transaction
pub transaction_identifier: String,
}
impl ApplePayWalletData {
pub fn get_payment_method_type(&self) -> Option<api_enums::PaymentMethodType> {
self.payment_method
.pm_type
.clone()
.parse_enum("ApplePayPaymentMethodType")
.ok()
.and_then(|payment_type| match payment_type {
common_enums::ApplePayPaymentMethodType::Debit => {
Some(api_enums::PaymentMethodType::Debit)
}
common_enums::ApplePayPaymentMethodType::Credit => {
Some(api_enums::PaymentMethodType::Credit)
}
common_enums::ApplePayPaymentMethodType::Prepaid
| common_enums::ApplePayPaymentMethodType::Store => None,
})
}
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ApplepayPaymentMethod {
pub display_name: String,
pub network: String,
pub pm_type: String,
}
#[derive(Eq, PartialEq, Clone, Default, Debug, serde::Deserialize, serde::Serialize)]
pub struct AmazonPayWalletData {
pub checkout_session_id: String,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum RealTimePaymentData {
DuitNow {},
Fps {},
PromptPay {},
VietQr {},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum BankRedirectData {
BancontactCard {
card_number: Option<cards::CardNumber>,
card_exp_month: Option<Secret<String>>,
card_exp_year: Option<Secret<String>>,
card_holder_name: Option<Secret<String>>,
},
Bizum {},
Blik {
blik_code: Option<String>,
},
Eps {
bank_name: Option<common_enums::BankNames>,
country: Option<api_enums::CountryAlpha2>,
},
Giropay {
bank_account_bic: Option<Secret<String>>,
bank_account_iban: Option<Secret<String>>,
country: Option<api_enums::CountryAlpha2>,
},
Ideal {
bank_name: Option<common_enums::BankNames>,
},
Interac {
country: Option<api_enums::CountryAlpha2>,
email: Option<Email>,
},
OnlineBankingCzechRepublic {
issuer: common_enums::BankNames,
},
OnlineBankingFinland {
email: Option<Email>,
},
OnlineBankingPoland {
issuer: common_enums::BankNames,
},
OnlineBankingSlovakia {
issuer: common_enums::BankNames,
},
OpenBankingUk {
issuer: Option<common_enums::BankNames>,
country: Option<api_enums::CountryAlpha2>,
},
Przelewy24 {
bank_name: Option<common_enums::BankNames>,
},
Sofort {
country: Option<api_enums::CountryAlpha2>,
preferred_language: Option<String>,
},
Trustly {
country: Option<api_enums::CountryAlpha2>,
},
OnlineBankingFpx {
issuer: common_enums::BankNames,
},
OnlineBankingThailand {
issuer: common_enums::BankNames,
},
LocalBankRedirect {},
Eft {
provider: String,
},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum OpenBankingData {
OpenBankingPIS {},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct CryptoData {
pub pay_currency: Option<String>,
pub network: Option<String>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum UpiData {
UpiCollect(UpiCollectData),
UpiIntent(UpiIntentData),
UpiQr(UpiQrData),
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub struct UpiCollectData {
pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct UpiIntentData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct UpiQrData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum VoucherData {
Boleto(Box<BoletoVoucherData>),
Efecty,
PagoEfectivo,
RedCompra,
RedPagos,
Alfamart(Box<AlfamartVoucherData>),
Indomaret(Box<IndomaretVoucherData>),
Oxxo,
SevenEleven(Box<JCSVoucherData>),
Lawson(Box<JCSVoucherData>),
MiniStop(Box<JCSVoucherData>),
FamilyMart(Box<JCSVoucherData>),
Seicomart(Box<JCSVoucherData>),
PayEasy(Box<JCSVoucherData>),
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct BoletoVoucherData {
/// The shopper's social security number
pub social_security_number: Option<Secret<String>>,
/// The bank number associated with the boleto
pub bank_number: Option<Secret<String>>,
/// The type of document (e.g., CPF, CNPJ)
pub document_type: Option<common_enums::DocumentKind>,
/// The percentage of fine applied for late payment
pub fine_percentage: Option<String>,
/// The number of days after due date when fine is applied
pub fine_quantity_days: Option<String>,
/// The percentage of interest applied for late payment
pub interest_percentage: Option<String>,
/// Number of days after which the boleto can be written off
pub write_off_quantity_days: Option<String>,
/// Additional messages to display to the shopper
pub messages: Option<Vec<String>>,
/// The date upon which the boleto is due and is of format: "YYYY-MM-DD"
pub due_date: Option<String>,
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct AlfamartVoucherData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct IndomaretVoucherData {}
#[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct JCSVoucherData {}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum GiftCardData {
Givex(GiftCardDetails),
PaySafeCard {},
BhnCardNetwork(BHNGiftCardDetails),
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct GiftCardDetails {
/// The gift card number
pub number: Secret<String>,
/// The card verification code.
pub cvc: Secret<String>,
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub struct BHNGiftCardDetails {
/// The gift card or account number
pub account_number: Secret<String>,
/// The security PIN for gift cards requiring it
pub pin: Option<Secret<String>>,
/// The CVV2 code for Open Loop/VPLN products
pub cvv2: Option<Secret<String>>,
/// The expiration date in MMYYYY format for Open Loop/VPLN products
pub expiration_date: Option<String>,
}
#[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, Default)]
#[serde(rename_all = "snake_case")]
pub struct CardToken {
/// The card holder's name
pub card_holder_name: Option<Secret<String>>,
/// The CVC number for the card
pub card_cvc: Option<Secret<String>>,
}
#[derive(serde::Deserialize, serde::Serialize, Debug, Clone, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum BankDebitData {
AchBankDebit {
account_number: Secret<String>,
routing_number: Secret<String>,
card_holder_name: Option<Secret<String>>,
bank_account_holder_name: Option<Secret<String>>,
bank_name: Option<common_enums::BankNames>,
bank_type: Option<common_enums::BankType>,
bank_holder_type: Option<common_enums::BankHolderType>,
},
SepaBankDebit {
iban: Secret<String>,
bank_account_holder_name: Option<Secret<String>>,
},
SepaGuarenteedBankDebit {
iban: Secret<String>,
bank_account_holder_name: Option<Secret<String>>,
},
BecsBankDebit {
account_number: Secret<String>,
bsb_number: Secret<String>,
bank_account_holder_name: Option<Secret<String>>,
},
BacsBankDebit {
account_number: Secret<String>,
sort_code: Secret<String>,
bank_account_holder_name: Option<Secret<String>>,
},
}
#[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum BankTransferData {
AchBankTransfer {},
SepaBankTransfer {},
BacsBankTransfer {},
MultibancoBankTransfer {},
PermataBankTransfer {},
BcaBankTransfer {},
BniVaBankTransfer {},
BriVaBankTransfer {},
CimbVaBankTransfer {},
DanamonVaBankTransfer {},
MandiriVaBankTransfer {},
Pix {
/// Unique key for pix transfer
pix_key: Option<Secret<String>>,
/// CPF is a Brazilian tax identification number
cpf: Option<Secret<String>>,
/// CNPJ is a Brazilian company tax identification number
cnpj: Option<Secret<String>>,
/// Source bank account UUID
source_bank_account_id: Option<MaskedBankAccount>,
/// Destination bank account UUID.
destination_bank_account_id: Option<MaskedBankAccount>,
/// The expiration date and time for the Pix QR code
expiry_date: Option<time::PrimitiveDateTime>,
},
Pse {},
LocalBankTransfer {
bank_code: Option<String>,
},
InstantBankTransfer {},
InstantBankTransferFinland {},
InstantBankTransferPoland {},
IndonesianBankTransfer {
bank_name: Option<common_enums::BankNames>,
},
}
#[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct SepaAndBacsBillingDetails {
/// The Email ID for SEPA and BACS billing
pub email: Email,
/// The billing name for SEPA and BACS billing
pub name: Secret<String>,
}
#[cfg(feature = "v1")]
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct NetworkTokenData {
pub token_number: cards::CardNumber,
pub token_exp_month: Secret<String>,
pub token_exp_year: Secret<String>,
pub token_cryptogram: Option<Secret<String>>,
pub card_issuer: Option<String>,
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<String>,
pub card_issuing_country: Option<String>,
pub bank_code: Option<String>,
pub nick_name: Option<Secret<String>>,
pub eci: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct NetworkTokenData {
pub network_token: cards::NetworkToken,
pub network_token_exp_month: Secret<String>,
pub network_token_exp_year: Secret<String>,
pub cryptogram: Option<Secret<String>>,
pub card_issuer: Option<String>, //since network token is tied to card, so its issuer will be same as card issuer
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<payment_methods::CardType>,
pub card_issuing_country: Option<common_enums::CountryAlpha2>,
pub bank_code: Option<String>,
pub card_holder_name: Option<Secret<String>>,
pub nick_name: Option<Secret<String>>,
pub eci: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize, Default)]
pub struct NetworkTokenDetails {
pub network_token: cards::NetworkToken,
pub network_token_exp_month: Secret<String>,
pub network_token_exp_year: Secret<String>,
pub card_issuer: Option<String>, //since network token is tied to card, so its issuer will be same as card issuer
pub card_network: Option<common_enums::CardNetwork>,
pub card_type: Option<payment_methods::CardType>,
pub card_issuing_country: Option<api_enums::CountryAlpha2>,
pub card_holder_name: Option<Secret<String>>,
pub nick_name: Option<Secret<String>>,
}
#[derive(Eq, PartialEq, Clone, Debug, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MobilePaymentData {
DirectCarrierBilling {
/// The phone number of the user
msisdn: String,
/// Unique user identifier
client_uid: Option<String>,
},
}
#[cfg(feature = "v2")]
impl TryFrom<payment_methods::PaymentMethodCreateData> for PaymentMethodData {
type Error = error_stack::Report<common_utils::errors::ValidationError>;
fn try_from(value: payment_methods::PaymentMethodCreateData) -> Result<Self, Self::Error> {
match value {
payment_methods::PaymentMethodCreateData::Card(payment_methods::CardDetail {
card_number,
card_exp_month,
card_exp_year,
card_cvc,
card_issuer,
card_network,
card_type,
card_issuing_country,
nick_name,
card_holder_name,
}) => Ok(Self::Card(Card {
card_number,
card_exp_month,
card_exp_year,
card_cvc: card_cvc.get_required_value("card_cvc")?,
card_issuer,
card_network,
card_type: card_type.map(|card_type| card_type.to_string()),
card_issuing_country: card_issuing_country.map(|country| country.to_string()),
bank_code: None,
nick_name,
card_holder_name,
co_badged_card_data: None,
})),
payment_methods::PaymentMethodCreateData::ProxyCard(_) => Err(
common_utils::errors::ValidationError::IncorrectValueProvided {
field_name: "Payment method data",
}
.into(),
),
}
}
}
impl From<api_models::payments::PaymentMethodData> for PaymentMethodData {
fn from(api_model_payment_method_data: api_models::payments::PaymentMethodData) -> Self {
match api_model_payment_method_data {
api_models::payments::PaymentMethodData::Card(card_data) => {
Self::Card(Card::from((card_data, None)))
}
api_models::payments::PaymentMethodData::CardRedirect(card_redirect) => {
Self::CardRedirect(From::from(card_redirect))
}
api_models::payments::PaymentMethodData::Wallet(wallet_data) => {
Self::Wallet(From::from(wallet_data))
}
api_models::payments::PaymentMethodData::PayLater(pay_later_data) => {
Self::PayLater(From::from(pay_later_data))
}
api_models::payments::PaymentMethodData::BankRedirect(bank_redirect_data) => {
Self::BankRedirect(From::from(bank_redirect_data))
}
api_models::payments::PaymentMethodData::BankDebit(bank_debit_data) => {
Self::BankDebit(From::from(bank_debit_data))
}
api_models::payments::PaymentMethodData::BankTransfer(bank_transfer_data) => {
Self::BankTransfer(Box::new(From::from(*bank_transfer_data)))
}
api_models::payments::PaymentMethodData::Crypto(crypto_data) => {
Self::Crypto(From::from(crypto_data))
}
api_models::payments::PaymentMethodData::MandatePayment => Self::MandatePayment,
api_models::payments::PaymentMethodData::Reward => Self::Reward,
api_models::payments::PaymentMethodData::RealTimePayment(real_time_payment_data) => {
Self::RealTimePayment(Box::new(From::from(*real_time_payment_data)))
}
api_models::payments::PaymentMethodData::Upi(upi_data) => {
Self::Upi(From::from(upi_data))
}
api_models::payments::PaymentMethodData::Voucher(voucher_data) => {
Self::Voucher(From::from(voucher_data))
}
api_models::payments::PaymentMethodData::GiftCard(gift_card) => {
Self::GiftCard(Box::new(From::from(*gift_card)))
}
api_models::payments::PaymentMethodData::CardToken(card_token) => {
Self::CardToken(From::from(card_token))
}
api_models::payments::PaymentMethodData::OpenBanking(ob_data) => {
Self::OpenBanking(From::from(ob_data))
}
api_models::payments::PaymentMethodData::MobilePayment(mobile_payment_data) => {
Self::MobilePayment(From::from(mobile_payment_data))
}
}
}
}
impl From<api_models::payments::ProxyPaymentMethodData> for ExternalVaultPaymentMethodData {
fn from(api_model_payment_method_data: api_models::payments::ProxyPaymentMethodData) -> Self {
match api_model_payment_method_data {
api_models::payments::ProxyPaymentMethodData::VaultDataCard(card_data) => {
Self::Card(Box::new(ExternalVaultCard::from(*card_data)))
}
api_models::payments::ProxyPaymentMethodData::VaultToken(vault_data) => {
Self::VaultToken(VaultToken::from(vault_data))
}
}
}
}
impl From<api_models::payments::ProxyCardData> for ExternalVaultCard {
fn from(value: api_models::payments::ProxyCardData) -> Self {
let api_models::payments::ProxyCardData {
card_number,
card_exp_month,
card_exp_year,
card_holder_name,
card_cvc,
bin_number,
last_four,
card_issuer,
card_network,
card_type,
card_issuing_country,
bank_code,
nick_name,
} = value;
Self {
card_number,
card_exp_month,
card_exp_year,
card_cvc,
bin_number,
last_four,
card_issuer,
card_network,
card_type,
card_issuing_country,
bank_code,
nick_name,
card_holder_name,
co_badged_card_data: None,
}
}
}
impl From<api_models::payments::VaultToken> for VaultToken {
fn from(value: api_models::payments::VaultToken) -> Self {
let api_models::payments::VaultToken {
card_cvc,
card_holder_name,
} = value;
Self {
card_cvc,
card_holder_name,
}
}
}
impl
From<(
api_models::payments::Card,
Option<payment_methods::CoBadgedCardData>,
)> for Card
{
fn from(
(value, co_badged_card_data_optional): (
api_models::payments::Card,
Option<payment_methods::CoBadgedCardData>,
),
) -> Self {
let api_models::payments::Card {
card_number,
card_exp_month,
card_exp_year,
card_holder_name,
card_cvc,
card_issuer,
card_network,
card_type,
card_issuing_country,
bank_code,
nick_name,
} = value;
Self {
card_number,
card_exp_month,
card_exp_year,
card_cvc,
card_issuer,
card_network,
card_type,
card_issuing_country,
bank_code,
nick_name,
card_holder_name,
co_badged_card_data: co_badged_card_data_optional,
}
}
}
#[cfg(feature = "v2")]
impl
From<(
payment_methods::CardDetail,
Secret<String>,
Option<Secret<String>>,
)> for Card
{
fn from(
(card_detail, card_cvc, card_holder_name): (
payment_methods::CardDetail,
Secret<String>,
Option<Secret<String>>,
),
) -> Self {
Self {
card_number: card_detail.card_number,
card_exp_month: card_detail.card_exp_month,
card_exp_year: card_detail.card_exp_year,
card_cvc,
card_issuer: card_detail.card_issuer,
card_network: card_detail.card_network,
card_type: card_detail.card_type.map(|val| val.to_string()),
card_issuing_country: card_detail.card_issuing_country.map(|val| val.to_string()),
bank_code: None,
nick_name: card_detail.nick_name,
card_holder_name: card_holder_name.or(card_detail.card_holder_name),
co_badged_card_data: None,
}
}
}
#[cfg(feature = "v2")]
impl From<Card> for payment_methods::CardDetail {
fn from(card: Card) -> Self {
Self {
card_number: card.card_number,
card_exp_month: card.card_exp_month,
card_exp_year: card.card_exp_year,
card_holder_name: card.card_holder_name,
nick_name: card.nick_name,
card_issuing_country: None,
card_network: card.card_network,
card_issuer: card.card_issuer,
card_type: None,
card_cvc: Some(card.card_cvc),
}
}
}
#[cfg(feature = "v2")]
impl From<ExternalVaultCard> for payment_methods::ProxyCardDetails {
fn from(card: ExternalVaultCard) -> Self {
Self {
card_number: card.card_number,
card_exp_month: card.card_exp_month,
card_exp_year: card.card_exp_year,
card_holder_name: card.card_holder_name,
nick_name: card.nick_name,
card_issuing_country: card.card_issuing_country,
card_network: card.card_network,
card_issuer: card.card_issuer,
card_type: card.card_type,
card_cvc: Some(card.card_cvc),
bin_number: card.bin_number,
last_four: card.last_four,
}
}
}
impl From<api_models::payments::CardRedirectData> for CardRedirectData {
fn from(value: api_models::payments::CardRedirectData) -> Self {
match value {
api_models::payments::CardRedirectData::Knet {} => Self::Knet {},
api_models::payments::CardRedirectData::Benefit {} => Self::Benefit {},
api_models::payments::CardRedirectData::MomoAtm {} => Self::MomoAtm {},
api_models::payments::CardRedirectData::CardRedirect {} => Self::CardRedirect {},
}
}
}
impl From<CardRedirectData> for api_models::payments::CardRedirectData {
fn from(value: CardRedirectData) -> Self {
match value {
CardRedirectData::Knet {} => Self::Knet {},
CardRedirectData::Benefit {} => Self::Benefit {},
CardRedirectData::MomoAtm {} => Self::MomoAtm {},
CardRedirectData::CardRedirect {} => Self::CardRedirect {},
}
}
}
impl From<api_models::payments::WalletData> for WalletData {
fn from(value: api_models::payments::WalletData) -> Self {
match value {
api_models::payments::WalletData::AliPayQr(_) => Self::AliPayQr(Box::new(AliPayQr {})),
api_models::payments::WalletData::AliPayRedirect(_) => {
Self::AliPayRedirect(AliPayRedirection {})
}
api_models::payments::WalletData::AliPayHkRedirect(_) => {
Self::AliPayHkRedirect(AliPayHkRedirection {})
}
api_models::payments::WalletData::AmazonPay(amazon_pay_data) => {
Self::AmazonPay(AmazonPayWalletData::from(amazon_pay_data))
}
api_models::payments::WalletData::AmazonPayRedirect(_) => {
Self::AmazonPayRedirect(Box::new(AmazonPayRedirect {}))
}
api_models::payments::WalletData::Skrill(_) => Self::Skrill(Box::new(SkrillData {})),
api_models::payments::WalletData::Paysera(_) => Self::Paysera(Box::new(PayseraData {})),
api_models::payments::WalletData::MomoRedirect(_) => {
Self::MomoRedirect(MomoRedirection {})
}
api_models::payments::WalletData::KakaoPayRedirect(_) => {
Self::KakaoPayRedirect(KakaoPayRedirection {})
}
api_models::payments::WalletData::GoPayRedirect(_) => {
Self::GoPayRedirect(GoPayRedirection {})
}
api_models::payments::WalletData::GcashRedirect(_) => {
Self::GcashRedirect(GcashRedirection {})
}
api_models::payments::WalletData::ApplePay(apple_pay_data) => {
Self::ApplePay(ApplePayWalletData::from(apple_pay_data))
}
api_models::payments::WalletData::ApplePayRedirect(_) => {
Self::ApplePayRedirect(Box::new(ApplePayRedirectData {}))
}
api_models::payments::WalletData::ApplePayThirdPartySdk(apple_pay_sdk_data) => {
Self::ApplePayThirdPartySdk(Box::new(ApplePayThirdPartySdkData {
token: apple_pay_sdk_data.token,
}))
}
api_models::payments::WalletData::DanaRedirect {} => Self::DanaRedirect {},
api_models::payments::WalletData::GooglePay(google_pay_data) => {
Self::GooglePay(GooglePayWalletData::from(google_pay_data))
}
api_models::payments::WalletData::GooglePayRedirect(_) => {
Self::GooglePayRedirect(Box::new(GooglePayRedirectData {}))
}
api_models::payments::WalletData::GooglePayThirdPartySdk(google_pay_sdk_data) => {
Self::GooglePayThirdPartySdk(Box::new(GooglePayThirdPartySdkData {
token: google_pay_sdk_data.token,
}))
}
api_models::payments::WalletData::MbWayRedirect(..) => {
Self::MbWayRedirect(Box::new(MbWayRedirection {}))
}
api_models::payments::WalletData::MobilePayRedirect(_) => {
Self::MobilePayRedirect(Box::new(MobilePayRedirection {}))
}
api_models::payments::WalletData::PaypalRedirect(paypal_redirect_data) => {
Self::PaypalRedirect(PaypalRedirection {
email: paypal_redirect_data.email,
})
}
api_models::payments::WalletData::PaypalSdk(paypal_sdk_data) => {
Self::PaypalSdk(PayPalWalletData {
token: paypal_sdk_data.token,
})
}
api_models::payments::WalletData::Paze(paze_data) => {
Self::Paze(PazeWalletData::from(paze_data))
}
api_models::payments::WalletData::SamsungPay(samsung_pay_data) => {
Self::SamsungPay(Box::new(SamsungPayWalletData::from(samsung_pay_data)))
}
api_models::payments::WalletData::TwintRedirect {} => Self::TwintRedirect {},
api_models::payments::WalletData::VippsRedirect {} => Self::VippsRedirect {},
api_models::payments::WalletData::TouchNGoRedirect(_) => {
Self::TouchNGoRedirect(Box::new(TouchNGoRedirection {}))
}
api_models::payments::WalletData::WeChatPayRedirect(_) => {
Self::WeChatPayRedirect(Box::new(WeChatPayRedirection {}))
}
api_models::payments::WalletData::WeChatPayQr(_) => {
Self::WeChatPayQr(Box::new(WeChatPayQr {}))
}
api_models::payments::WalletData::CashappQr(_) => {
Self::CashappQr(Box::new(CashappQr {}))
}
api_models::payments::WalletData::SwishQr(_) => Self::SwishQr(SwishQrData {}),
api_models::payments::WalletData::Mifinity(mifinity_data) => {
Self::Mifinity(MifinityData {
date_of_birth: mifinity_data.date_of_birth,
language_preference: mifinity_data.language_preference,
})
}
api_models::payments::WalletData::BluecodeRedirect {} => Self::BluecodeRedirect {},
api_models::payments::WalletData::RevolutPay(_) => Self::RevolutPay(RevolutPayData {}),
}
}
}
impl From<api_models::payments::GooglePayWalletData> for GooglePayWalletData {
fn from(value: api_models::payments::GooglePayWalletData) -> Self {
Self {
pm_type: value.pm_type,
description: value.description,
info: GooglePayPaymentMethodInfo {
card_network: value.info.card_network,
card_details: value.info.card_details,
assurance_details: value.info.assurance_details.map(|info| {
GooglePayAssuranceDetails {
card_holder_authenticated: info.card_holder_authenticated,
account_verified: info.account_verified,
}
}),
card_funding_source: value.info.card_funding_source,
},
tokenization_data: value.tokenization_data,
}
}
}
impl From<api_models::payments::ApplePayWalletData> for ApplePayWalletData {
fn from(value: api_models::payments::ApplePayWalletData) -> Self {
Self {
payment_data: value.payment_data,
payment_method: ApplepayPaymentMethod {
display_name: value.payment_method.display_name,
network: value.payment_method.network,
pm_type: value.payment_method.pm_type,
},
transaction_identifier: value.transaction_identifier,
}
}
}
impl From<api_models::payments::AmazonPayWalletData> for AmazonPayWalletData {
fn from(value: api_models::payments::AmazonPayWalletData) -> Self {
Self {
checkout_session_id: value.checkout_session_id,
}
}
}
impl From<api_models::payments::SamsungPayTokenData> for SamsungPayTokenData {
fn from(samsung_pay_token_data: api_models::payments::SamsungPayTokenData) -> Self {
Self {
three_ds_type: samsung_pay_token_data.three_ds_type,
version: samsung_pay_token_data.version,
data: samsung_pay_token_data.data,
}
}
}
impl From<api_models::payments::PazeWalletData> for PazeWalletData {
fn from(value: api_models::payments::PazeWalletData) -> Self {
Self {
complete_response: value.complete_response,
}
}
}
impl From<Box<api_models::payments::SamsungPayWalletData>> for SamsungPayWalletData {
fn from(value: Box<api_models::payments::SamsungPayWalletData>) -> Self {
match value.payment_credential {
api_models::payments::SamsungPayWalletCredentials::SamsungPayWalletDataForApp(
samsung_pay_app_wallet_data,
) => Self {
payment_credential: SamsungPayWalletCredentials {
method: samsung_pay_app_wallet_data.method,
recurring_payment: samsung_pay_app_wallet_data.recurring_payment,
card_brand: samsung_pay_app_wallet_data.payment_card_brand.into(),
dpan_last_four_digits: samsung_pay_app_wallet_data.payment_last4_dpan,
card_last_four_digits: samsung_pay_app_wallet_data.payment_last4_fpan,
token_data: samsung_pay_app_wallet_data.token_data.into(),
},
},
api_models::payments::SamsungPayWalletCredentials::SamsungPayWalletDataForWeb(
samsung_pay_web_wallet_data,
) => Self {
payment_credential: SamsungPayWalletCredentials {
method: samsung_pay_web_wallet_data.method,
recurring_payment: samsung_pay_web_wallet_data.recurring_payment,
card_brand: samsung_pay_web_wallet_data.card_brand.into(),
dpan_last_four_digits: None,
card_last_four_digits: samsung_pay_web_wallet_data.card_last_four_digits,
token_data: samsung_pay_web_wallet_data.token_data.into(),
},
},
}
}
}
impl From<api_models::payments::PayLaterData> for PayLaterData {
fn from(value: api_models::payments::PayLaterData) -> Self {
match value {
api_models::payments::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect {},
api_models::payments::PayLaterData::KlarnaSdk { token } => Self::KlarnaSdk { token },
api_models::payments::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect {},
api_models::payments::PayLaterData::FlexitiRedirect {} => Self::FlexitiRedirect {},
api_models::payments::PayLaterData::AfterpayClearpayRedirect { .. } => {
Self::AfterpayClearpayRedirect {}
}
api_models::payments::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect {},
api_models::payments::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect {},
api_models::payments::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect {},
api_models::payments::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect {},
api_models::payments::PayLaterData::BreadpayRedirect {} => Self::BreadpayRedirect {},
}
}
}
impl From<api_models::payments::BankRedirectData> for BankRedirectData {
fn from(value: api_models::payments::BankRedirectData) -> Self {
match value {
api_models::payments::BankRedirectData::BancontactCard {
card_number,
card_exp_month,
card_exp_year,
card_holder_name,
..
} => Self::BancontactCard {
card_number,
card_exp_month,
card_exp_year,
card_holder_name,
},
api_models::payments::BankRedirectData::Bizum {} => Self::Bizum {},
api_models::payments::BankRedirectData::Blik { blik_code } => Self::Blik { blik_code },
api_models::payments::BankRedirectData::Eps {
bank_name, country, ..
} => Self::Eps { bank_name, country },
api_models::payments::BankRedirectData::Giropay {
bank_account_bic,
bank_account_iban,
country,
..
} => Self::Giropay {
bank_account_bic,
bank_account_iban,
country,
},
api_models::payments::BankRedirectData::Ideal { bank_name, .. } => {
Self::Ideal { bank_name }
}
api_models::payments::BankRedirectData::Interac { country, email } => {
Self::Interac { country, email }
}
api_models::payments::BankRedirectData::OnlineBankingCzechRepublic { issuer } => {
Self::OnlineBankingCzechRepublic { issuer }
}
api_models::payments::BankRedirectData::OnlineBankingFinland { email } => {
Self::OnlineBankingFinland { email }
}
api_models::payments::BankRedirectData::OnlineBankingPoland { issuer } => {
Self::OnlineBankingPoland { issuer }
}
api_models::payments::BankRedirectData::OnlineBankingSlovakia { issuer } => {
Self::OnlineBankingSlovakia { issuer }
}
api_models::payments::BankRedirectData::OpenBankingUk {
country, issuer, ..
} => Self::OpenBankingUk { country, issuer },
api_models::payments::BankRedirectData::Przelewy24 { bank_name, .. } => {
Self::Przelewy24 { bank_name }
}
api_models::payments::BankRedirectData::Sofort {
preferred_language,
country,
..
} => Self::Sofort {
country,
preferred_language,
},
api_models::payments::BankRedirectData::Trustly { country } => Self::Trustly {
country: Some(country),
},
api_models::payments::BankRedirectData::OnlineBankingFpx { issuer } => {
Self::OnlineBankingFpx { issuer }
}
api_models::payments::BankRedirectData::OnlineBankingThailand { issuer } => {
Self::OnlineBankingThailand { issuer }
}
api_models::payments::BankRedirectData::LocalBankRedirect { .. } => {
Self::LocalBankRedirect {}
}
api_models::payments::BankRedirectData::Eft { provider } => Self::Eft { provider },
}
}
}
impl From<api_models::payments::CryptoData> for CryptoData {
fn from(value: api_models::payments::CryptoData) -> Self {
let api_models::payments::CryptoData {
pay_currency,
network,
} = value;
Self {
pay_currency,
network,
}
}
}
impl From<CryptoData> for api_models::payments::CryptoData {
fn from(value: CryptoData) -> Self {
let CryptoData {
pay_currency,
network,
} = value;
Self {
pay_currency,
network,
}
}
}
impl From<api_models::payments::UpiData> for UpiData {
fn from(value: api_models::payments::UpiData) -> Self {
match value {
api_models::payments::UpiData::UpiCollect(upi) => {
Self::UpiCollect(UpiCollectData { vpa_id: upi.vpa_id })
}
api_models::payments::UpiData::UpiIntent(_) => Self::UpiIntent(UpiIntentData {}),
api_models::payments::UpiData::UpiQr(_) => Self::UpiQr(UpiQrData {}),
}
}
}
impl From<UpiData> for api_models::payments::additional_info::UpiAdditionalData {
fn from(value: UpiData) -> Self {
match value {
UpiData::UpiCollect(upi) => Self::UpiCollect(Box::new(
payment_additional_types::UpiCollectAdditionalData {
vpa_id: upi.vpa_id.map(MaskedUpiVpaId::from),
},
)),
UpiData::UpiIntent(_) => {
Self::UpiIntent(Box::new(api_models::payments::UpiIntentData {}))
}
UpiData::UpiQr(_) => Self::UpiQr(Box::new(api_models::payments::UpiQrData {})),
}
}
}
impl From<api_models::payments::VoucherData> for VoucherData {
fn from(value: api_models::payments::VoucherData) -> Self {
match value {
api_models::payments::VoucherData::Boleto(boleto_data) => {
Self::Boleto(Box::new(BoletoVoucherData {
social_security_number: boleto_data.social_security_number,
bank_number: boleto_data.bank_number,
document_type: boleto_data.document_type,
fine_percentage: boleto_data.fine_percentage,
fine_quantity_days: boleto_data.fine_quantity_days,
interest_percentage: boleto_data.interest_percentage,
write_off_quantity_days: boleto_data.write_off_quantity_days,
messages: boleto_data.messages,
due_date: boleto_data.due_date,
}))
}
api_models::payments::VoucherData::Alfamart(_) => {
Self::Alfamart(Box::new(AlfamartVoucherData {}))
}
api_models::payments::VoucherData::Indomaret(_) => {
Self::Indomaret(Box::new(IndomaretVoucherData {}))
}
api_models::payments::VoucherData::SevenEleven(_)
| api_models::payments::VoucherData::Lawson(_)
| api_models::payments::VoucherData::MiniStop(_)
| api_models::payments::VoucherData::FamilyMart(_)
| api_models::payments::VoucherData::Seicomart(_)
| api_models::payments::VoucherData::PayEasy(_) => {
Self::SevenEleven(Box::new(JCSVoucherData {}))
}
api_models::payments::VoucherData::Efecty => Self::Efecty,
api_models::payments::VoucherData::PagoEfectivo => Self::PagoEfectivo,
api_models::payments::VoucherData::RedCompra => Self::RedCompra,
api_models::payments::VoucherData::RedPagos => Self::RedPagos,
api_models::payments::VoucherData::Oxxo => Self::Oxxo,
}
}
}
impl From<Box<BoletoVoucherData>> for Box<api_models::payments::BoletoVoucherData> {
fn from(value: Box<BoletoVoucherData>) -> Self {
Self::new(api_models::payments::BoletoVoucherData {
social_security_number: value.social_security_number,
bank_number: value.bank_number,
document_type: value.document_type,
fine_percentage: value.fine_percentage,
fine_quantity_days: value.fine_quantity_days,
interest_percentage: value.interest_percentage,
write_off_quantity_days: value.write_off_quantity_days,
messages: value.messages,
due_date: value.due_date,
})
}
}
impl From<Box<AlfamartVoucherData>> for Box<api_models::payments::AlfamartVoucherData> {
fn from(_value: Box<AlfamartVoucherData>) -> Self {
Self::new(api_models::payments::AlfamartVoucherData {
first_name: None,
last_name: None,
email: None,
})
}
}
impl From<Box<IndomaretVoucherData>> for Box<api_models::payments::IndomaretVoucherData> {
fn from(_value: Box<IndomaretVoucherData>) -> Self {
Self::new(api_models::payments::IndomaretVoucherData {
first_name: None,
last_name: None,
email: None,
})
}
}
impl From<Box<JCSVoucherData>> for Box<api_models::payments::JCSVoucherData> {
fn from(_value: Box<JCSVoucherData>) -> Self {
Self::new(api_models::payments::JCSVoucherData {
first_name: None,
last_name: None,
email: None,
phone_number: None,
})
}
}
impl From<VoucherData> for api_models::payments::VoucherData {
fn from(value: VoucherData) -> Self {
match value {
VoucherData::Boleto(boleto_data) => Self::Boleto(boleto_data.into()),
VoucherData::Alfamart(alfa_mart) => Self::Alfamart(alfa_mart.into()),
VoucherData::Indomaret(info_maret) => Self::Indomaret(info_maret.into()),
VoucherData::SevenEleven(jcs_data)
| VoucherData::Lawson(jcs_data)
| VoucherData::MiniStop(jcs_data)
| VoucherData::FamilyMart(jcs_data)
| VoucherData::Seicomart(jcs_data)
| VoucherData::PayEasy(jcs_data) => Self::SevenEleven(jcs_data.into()),
VoucherData::Efecty => Self::Efecty,
VoucherData::PagoEfectivo => Self::PagoEfectivo,
VoucherData::RedCompra => Self::RedCompra,
VoucherData::RedPagos => Self::RedPagos,
VoucherData::Oxxo => Self::Oxxo,
}
}
}
impl From<api_models::payments::GiftCardData> for GiftCardData {
fn from(value: api_models::payments::GiftCardData) -> Self {
match value {
api_models::payments::GiftCardData::Givex(details) => Self::Givex(GiftCardDetails {
number: details.number,
cvc: details.cvc,
}),
api_models::payments::GiftCardData::PaySafeCard {} => Self::PaySafeCard {},
api_models::payments::GiftCardData::BhnCardNetwork(details) => {
Self::BhnCardNetwork(BHNGiftCardDetails {
account_number: details.account_number,
pin: details.pin,
cvv2: details.cvv2,
expiration_date: details.expiration_date,
})
}
}
}
}
impl From<GiftCardData> for payment_additional_types::GiftCardAdditionalData {
fn from(value: GiftCardData) -> Self {
match value {
GiftCardData::Givex(details) => Self::Givex(Box::new(
payment_additional_types::GivexGiftCardAdditionalData {
last4: details
.number
.peek()
.chars()
.rev()
.take(4)
.collect::<String>()
.chars()
.rev()
.collect::<String>()
.into(),
},
)),
GiftCardData::PaySafeCard {} => Self::PaySafeCard {},
GiftCardData::BhnCardNetwork(_) => Self::BhnCardNetwork {},
}
}
}
impl From<api_models::payments::CardToken> for CardToken {
fn from(value: api_models::payments::CardToken) -> Self {
let api_models::payments::CardToken {
card_holder_name,
card_cvc,
} = value;
Self {
card_holder_name,
card_cvc,
}
}
}
impl From<CardToken> for payment_additional_types::CardTokenAdditionalData {
fn from(value: CardToken) -> Self {
let CardToken {
card_holder_name, ..
} = value;
Self { card_holder_name }
}
}
impl From<api_models::payments::BankDebitData> for BankDebitData {
fn from(value: api_models::payments::BankDebitData) -> Self {
match value {
api_models::payments::BankDebitData::AchBankDebit {
account_number,
routing_number,
card_holder_name,
bank_account_holder_name,
bank_name,
bank_type,
bank_holder_type,
..
} => Self::AchBankDebit {
account_number,
routing_number,
card_holder_name,
bank_account_holder_name,
bank_name,
bank_type,
bank_holder_type,
},
api_models::payments::BankDebitData::SepaBankDebit {
iban,
bank_account_holder_name,
..
} => Self::SepaBankDebit {
iban,
bank_account_holder_name,
},
api_models::payments::BankDebitData::SepaGuarenteedBankDebit {
iban,
bank_account_holder_name,
..
} => Self::SepaBankDebit {
iban,
bank_account_holder_name,
},
api_models::payments::BankDebitData::BecsBankDebit {
account_number,
bsb_number,
bank_account_holder_name,
..
} => Self::BecsBankDebit {
account_number,
bsb_number,
bank_account_holder_name,
},
api_models::payments::BankDebitData::BacsBankDebit {
account_number,
sort_code,
bank_account_holder_name,
..
} => Self::BacsBankDebit {
account_number,
sort_code,
bank_account_holder_name,
},
}
}
}
impl From<BankDebitData> for api_models::payments::additional_info::BankDebitAdditionalData {
fn from(value: BankDebitData) -> Self {
match value {
BankDebitData::AchBankDebit {
account_number,
routing_number,
bank_name,
bank_type,
bank_holder_type,
card_holder_name,
bank_account_holder_name,
} => Self::Ach(Box::new(
payment_additional_types::AchBankDebitAdditionalData {
account_number: MaskedBankAccount::from(account_number),
routing_number: MaskedRoutingNumber::from(routing_number),
bank_name,
bank_type,
bank_holder_type,
card_holder_name,
bank_account_holder_name,
},
)),
BankDebitData::SepaBankDebit {
iban,
bank_account_holder_name,
} => Self::Sepa(Box::new(
payment_additional_types::SepaBankDebitAdditionalData {
iban: MaskedIban::from(iban),
bank_account_holder_name,
},
)),
BankDebitData::SepaGuarenteedBankDebit {
iban,
bank_account_holder_name,
} => Self::SepaGuarenteedDebit(Box::new(
payment_additional_types::SepaBankDebitAdditionalData {
iban: MaskedIban::from(iban),
bank_account_holder_name,
},
)),
BankDebitData::BecsBankDebit {
account_number,
bsb_number,
bank_account_holder_name,
} => Self::Becs(Box::new(
payment_additional_types::BecsBankDebitAdditionalData {
account_number: MaskedBankAccount::from(account_number),
bsb_number,
bank_account_holder_name,
},
)),
BankDebitData::BacsBankDebit {
account_number,
sort_code,
bank_account_holder_name,
} => Self::Bacs(Box::new(
payment_additional_types::BacsBankDebitAdditionalData {
account_number: MaskedBankAccount::from(account_number),
sort_code: MaskedSortCode::from(sort_code),
bank_account_holder_name,
},
)),
}
}
}
impl From<api_models::payments::BankTransferData> for BankTransferData {
fn from(value: api_models::payments::BankTransferData) -> Self {
match value {
api_models::payments::BankTransferData::AchBankTransfer { .. } => {
Self::AchBankTransfer {}
}
api_models::payments::BankTransferData::SepaBankTransfer { .. } => {
Self::SepaBankTransfer {}
}
api_models::payments::BankTransferData::BacsBankTransfer { .. } => {
Self::BacsBankTransfer {}
}
api_models::payments::BankTransferData::MultibancoBankTransfer { .. } => {
Self::MultibancoBankTransfer {}
}
api_models::payments::BankTransferData::PermataBankTransfer { .. } => {
Self::PermataBankTransfer {}
}
api_models::payments::BankTransferData::BcaBankTransfer { .. } => {
Self::BcaBankTransfer {}
}
api_models::payments::BankTransferData::BniVaBankTransfer { .. } => {
Self::BniVaBankTransfer {}
}
api_models::payments::BankTransferData::BriVaBankTransfer { .. } => {
Self::BriVaBankTransfer {}
}
api_models::payments::BankTransferData::CimbVaBankTransfer { .. } => {
Self::CimbVaBankTransfer {}
}
api_models::payments::BankTransferData::DanamonVaBankTransfer { .. } => {
Self::DanamonVaBankTransfer {}
}
api_models::payments::BankTransferData::MandiriVaBankTransfer { .. } => {
Self::MandiriVaBankTransfer {}
}
api_models::payments::BankTransferData::Pix {
pix_key,
cpf,
cnpj,
source_bank_account_id,
destination_bank_account_id,
expiry_date,
} => Self::Pix {
pix_key,
cpf,
cnpj,
source_bank_account_id,
destination_bank_account_id,
expiry_date,
},
api_models::payments::BankTransferData::Pse {} => Self::Pse {},
api_models::payments::BankTransferData::LocalBankTransfer { bank_code } => {
Self::LocalBankTransfer { bank_code }
}
api_models::payments::BankTransferData::InstantBankTransfer {} => {
Self::InstantBankTransfer {}
}
api_models::payments::BankTransferData::InstantBankTransferFinland {} => {
Self::InstantBankTransferFinland {}
}
api_models::payments::BankTransferData::InstantBankTransferPoland {} => {
Self::InstantBankTransferPoland {}
}
api_models::payments::BankTransferData::IndonesianBankTransfer { bank_name } => {
Self::IndonesianBankTransfer { bank_name }
}
}
}
}
impl From<BankTransferData> for api_models::payments::additional_info::BankTransferAdditionalData {
fn from(value: BankTransferData) -> Self {
match value {
BankTransferData::AchBankTransfer {} => Self::Ach {},
BankTransferData::SepaBankTransfer {} => Self::Sepa {},
BankTransferData::BacsBankTransfer {} => Self::Bacs {},
BankTransferData::MultibancoBankTransfer {} => Self::Multibanco {},
BankTransferData::PermataBankTransfer {} => Self::Permata {},
BankTransferData::BcaBankTransfer {} => Self::Bca {},
BankTransferData::BniVaBankTransfer {} => Self::BniVa {},
BankTransferData::BriVaBankTransfer {} => Self::BriVa {},
BankTransferData::CimbVaBankTransfer {} => Self::CimbVa {},
BankTransferData::DanamonVaBankTransfer {} => Self::DanamonVa {},
BankTransferData::MandiriVaBankTransfer {} => Self::MandiriVa {},
BankTransferData::Pix {
pix_key,
cpf,
cnpj,
source_bank_account_id,
destination_bank_account_id,
expiry_date,
} => Self::Pix(Box::new(
api_models::payments::additional_info::PixBankTransferAdditionalData {
pix_key: pix_key.map(MaskedBankAccount::from),
cpf: cpf.map(MaskedBankAccount::from),
cnpj: cnpj.map(MaskedBankAccount::from),
source_bank_account_id,
destination_bank_account_id,
expiry_date,
},
)),
BankTransferData::Pse {} => Self::Pse {},
BankTransferData::LocalBankTransfer { bank_code } => Self::LocalBankTransfer(Box::new(
api_models::payments::additional_info::LocalBankTransferAdditionalData {
bank_code: bank_code.map(MaskedBankAccount::from),
},
)),
BankTransferData::InstantBankTransfer {} => Self::InstantBankTransfer {},
BankTransferData::InstantBankTransferFinland {} => Self::InstantBankTransferFinland {},
BankTransferData::InstantBankTransferPoland {} => Self::InstantBankTransferPoland {},
BankTransferData::IndonesianBankTransfer { bank_name } => {
Self::IndonesianBankTransfer { bank_name }
}
}
}
}
impl From<api_models::payments::RealTimePaymentData> for RealTimePaymentData {
fn from(value: api_models::payments::RealTimePaymentData) -> Self {
match value {
api_models::payments::RealTimePaymentData::Fps {} => Self::Fps {},
api_models::payments::RealTimePaymentData::DuitNow {} => Self::DuitNow {},
api_models::payments::RealTimePaymentData::PromptPay {} => Self::PromptPay {},
api_models::payments::RealTimePaymentData::VietQr {} => Self::VietQr {},
}
}
}
impl From<RealTimePaymentData> for api_models::payments::RealTimePaymentData {
fn from(value: RealTimePaymentData) -> Self {
match value {
RealTimePaymentData::Fps {} => Self::Fps {},
RealTimePaymentData::DuitNow {} => Self::DuitNow {},
RealTimePaymentData::PromptPay {} => Self::PromptPay {},
RealTimePaymentData::VietQr {} => Self::VietQr {},
}
}
}
impl From<api_models::payments::OpenBankingData> for OpenBankingData {
fn from(value: api_models::payments::OpenBankingData) -> Self {
match value {
api_models::payments::OpenBankingData::OpenBankingPIS {} => Self::OpenBankingPIS {},
}
}
}
impl From<OpenBankingData> for api_models::payments::OpenBankingData {
fn from(value: OpenBankingData) -> Self {
match value {
OpenBankingData::OpenBankingPIS {} => Self::OpenBankingPIS {},
}
}
}
impl From<api_models::payments::MobilePaymentData> for MobilePaymentData {
fn from(value: api_models::payments::MobilePaymentData) -> Self {
match value {
api_models::payments::MobilePaymentData::DirectCarrierBilling {
msisdn,
client_uid,
} => Self::DirectCarrierBilling { msisdn, client_uid },
}
}
}
impl From<MobilePaymentData> for api_models::payments::MobilePaymentData {
fn from(value: MobilePaymentData) -> Self {
match value {
MobilePaymentData::DirectCarrierBilling { msisdn, client_uid } => {
Self::DirectCarrierBilling { msisdn, client_uid }
}
}
}
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCardValue1 {
pub card_number: String,
pub exp_year: String,
pub exp_month: String,
pub nickname: Option<String>,
pub card_last_four: Option<String>,
pub card_token: Option<String>,
pub card_holder_name: Option<Secret<String>>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCardValue2 {
pub card_security_code: Option<String>,
pub card_fingerprint: Option<String>,
pub external_id: Option<String>,
pub customer_id: Option<id_type::CustomerId>,
pub payment_method_id: Option<String>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedWalletValue1 {
pub data: WalletData,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedWalletValue2 {
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankTransferValue1 {
pub data: BankTransferData,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankTransferValue2 {
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankRedirectValue1 {
pub data: BankRedirectData,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankRedirectValue2 {
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankDebitValue2 {
pub customer_id: Option<id_type::CustomerId>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
pub struct TokenizedBankDebitValue1 {
pub data: BankDebitData,
}
pub trait GetPaymentMethodType {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType;
}
impl GetPaymentMethodType for CardRedirectData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::Knet {} => api_enums::PaymentMethodType::Knet,
Self::Benefit {} => api_enums::PaymentMethodType::Benefit,
Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm,
Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect,
}
}
}
impl GetPaymentMethodType for WalletData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay,
Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk,
Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay,
Self::Skrill(_) => api_enums::PaymentMethodType::Skrill,
Self::Paysera(_) => api_enums::PaymentMethodType::Paysera,
Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo,
Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay,
Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay,
Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash,
Self::AmazonPay(_) => api_enums::PaymentMethodType::AmazonPay,
Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => {
api_enums::PaymentMethodType::ApplePay
}
Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana,
Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => {
api_enums::PaymentMethodType::GooglePay
}
Self::BluecodeRedirect {} => api_enums::PaymentMethodType::Bluecode,
Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay,
Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay,
Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal,
Self::Paze(_) => api_enums::PaymentMethodType::Paze,
Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay,
Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint,
Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps,
Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo,
Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => {
api_enums::PaymentMethodType::WeChatPay
}
Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp,
Self::SwishQr(_) => api_enums::PaymentMethodType::Swish,
Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity,
Self::RevolutPay(_) => api_enums::PaymentMethodType::RevolutPay,
}
}
}
impl GetPaymentMethodType for PayLaterData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna,
Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna,
Self::FlexitiRedirect { .. } => api_enums::PaymentMethodType::Flexiti,
Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm,
Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay,
Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright,
Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley,
Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma,
Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome,
Self::BreadpayRedirect {} => api_enums::PaymentMethodType::Breadpay,
}
}
}
impl GetPaymentMethodType for BankRedirectData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard,
Self::Bizum {} => api_enums::PaymentMethodType::Bizum,
Self::Blik { .. } => api_enums::PaymentMethodType::Blik,
Self::Eft { .. } => api_enums::PaymentMethodType::Eft,
Self::Eps { .. } => api_enums::PaymentMethodType::Eps,
Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay,
Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal,
Self::Interac { .. } => api_enums::PaymentMethodType::Interac,
Self::OnlineBankingCzechRepublic { .. } => {
api_enums::PaymentMethodType::OnlineBankingCzechRepublic
}
Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland,
Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland,
Self::OnlineBankingSlovakia { .. } => {
api_enums::PaymentMethodType::OnlineBankingSlovakia
}
Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk,
Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24,
Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort,
Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly,
Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx,
Self::OnlineBankingThailand { .. } => {
api_enums::PaymentMethodType::OnlineBankingThailand
}
Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect,
}
}
}
impl GetPaymentMethodType for BankDebitData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach,
Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa,
Self::SepaGuarenteedBankDebit { .. } => {
api_enums::PaymentMethodType::SepaGuarenteedDebit
}
Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs,
Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs,
}
}
}
impl GetPaymentMethodType for BankTransferData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach,
Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::Sepa,
Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs,
Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco,
Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer,
Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer,
Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa,
Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa,
Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa,
Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa,
Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa,
Self::Pix { .. } => api_enums::PaymentMethodType::Pix,
Self::Pse {} => api_enums::PaymentMethodType::Pse,
Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer,
Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer,
Self::InstantBankTransferFinland {} => {
api_enums::PaymentMethodType::InstantBankTransferFinland
}
Self::InstantBankTransferPoland {} => {
api_enums::PaymentMethodType::InstantBankTransferPoland
}
Self::IndonesianBankTransfer { .. } => {
api_enums::PaymentMethodType::IndonesianBankTransfer
}
}
}
}
impl GetPaymentMethodType for CryptoData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
api_enums::PaymentMethodType::CryptoCurrency
}
}
impl GetPaymentMethodType for RealTimePaymentData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::Fps {} => api_enums::PaymentMethodType::Fps,
Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow,
Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay,
Self::VietQr {} => api_enums::PaymentMethodType::VietQr,
}
}
}
impl GetPaymentMethodType for UpiData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect,
Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent,
Self::UpiQr(_) => api_enums::PaymentMethodType::UpiQr,
}
}
}
impl GetPaymentMethodType for VoucherData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::Boleto(_) => api_enums::PaymentMethodType::Boleto,
Self::Efecty => api_enums::PaymentMethodType::Efecty,
Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo,
Self::RedCompra => api_enums::PaymentMethodType::RedCompra,
Self::RedPagos => api_enums::PaymentMethodType::RedPagos,
Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart,
Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret,
Self::Oxxo => api_enums::PaymentMethodType::Oxxo,
Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven,
Self::Lawson(_) => api_enums::PaymentMethodType::Lawson,
Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop,
Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart,
Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart,
Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy,
}
}
}
impl GetPaymentMethodType for GiftCardData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::Givex(_) => api_enums::PaymentMethodType::Givex,
Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard,
Self::BhnCardNetwork(_) => api_enums::PaymentMethodType::BhnCardNetwork,
}
}
}
impl GetPaymentMethodType for OpenBankingData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS,
}
}
}
impl GetPaymentMethodType for MobilePaymentData {
fn get_payment_method_type(&self) -> api_enums::PaymentMethodType {
match self {
Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling,
}
}
}
impl From<Card> for ExtendedCardInfo {
fn from(value: Card) -> Self {
Self {
card_number: value.card_number,
card_exp_month: value.card_exp_month,
card_exp_year: value.card_exp_year,
card_holder_name: None,
card_cvc: value.card_cvc,
card_issuer: value.card_issuer,
card_network: value.card_network,
card_type: value.card_type,
card_issuing_country: value.card_issuing_country,
bank_code: value.bank_code,
}
}
}
impl From<ApplePayWalletData> for payment_methods::PaymentMethodDataWalletInfo {
fn from(item: ApplePayWalletData) -> Self {
Self {
last4: item
.payment_method
.display_name
.chars()
.rev()
.take(4)
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect(),
card_network: item.payment_method.network,
card_type: Some(item.payment_method.pm_type),
}
}
}
impl From<GooglePayWalletData> for payment_methods::PaymentMethodDataWalletInfo {
fn from(item: GooglePayWalletData) -> Self {
Self {
last4: item.info.card_details,
card_network: item.info.card_network,
card_type: Some(item.pm_type),
}
}
}
#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
pub enum PaymentMethodsData {
Card(CardDetailsPaymentMethod),
BankDetails(payment_methods::PaymentMethodDataBankCreds), //PaymentMethodDataBankCreds and its transformations should be moved to the domain models
WalletDetails(payment_methods::PaymentMethodDataWalletInfo), //PaymentMethodDataWalletInfo and its transformations should be moved to the domain models
NetworkToken(NetworkTokenDetailsPaymentMethod),
}
impl PaymentMethodsData {
#[cfg(feature = "v1")]
pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData> {
if let Self::Card(card) = self {
card.co_badged_card_data.clone()
} else {
None
}
}
#[cfg(feature = "v2")]
pub fn get_co_badged_card_data(&self) -> Option<payment_methods::CoBadgedCardData> {
todo!()
}
#[cfg(feature = "v1")]
pub fn get_additional_payout_method_data(
&self,
) -> Option<payout_method_utils::AdditionalPayoutMethodData> {
match self {
Self::Card(card_details) => {
router_env::logger::info!("Populating AdditionalPayoutMethodData from Card payment method data for recurring payout");
Some(payout_method_utils::AdditionalPayoutMethodData::Card(
Box::new(payout_method_utils::CardAdditionalData {
card_issuer: card_details.card_issuer.clone(),
card_network: card_details.card_network.clone(),
bank_code: None,
card_type: card_details.card_type.clone(),
card_issuing_country: card_details.issuer_country.clone(),
last4: card_details.last4_digits.clone(),
card_isin: card_details.card_isin.clone(),
card_extended_bin: None,
card_exp_month: card_details.expiry_month.clone(),
card_exp_year: card_details.expiry_year.clone(),
card_holder_name: card_details.card_holder_name.clone(),
}),
))
}
Self::BankDetails(_) | Self::WalletDetails(_) | Self::NetworkToken(_) => None,
}
}
pub fn get_card_details(&self) -> Option<CardDetailsPaymentMethod> {
if let Self::Card(card) = self {
Some(card.clone())
} else {
None
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct NetworkTokenDetailsPaymentMethod {
pub last4_digits: Option<String>,
pub issuer_country: Option<common_enums::CountryAlpha2>,
pub network_token_expiry_month: Option<Secret<String>>,
pub network_token_expiry_year: Option<Secret<String>>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub card_isin: Option<String>,
pub card_issuer: Option<String>,
pub card_network: Option<api_enums::CardNetwork>,
pub card_type: Option<String>,
#[serde(default = "saved_in_locker_default")]
pub saved_to_locker: bool,
}
fn saved_in_locker_default() -> bool {
true
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct CardDetailsPaymentMethod {
pub last4_digits: Option<String>,
pub issuer_country: Option<String>,
pub expiry_month: Option<Secret<String>>,
pub expiry_year: Option<Secret<String>>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub card_isin: Option<String>,
pub card_issuer: Option<String>,
pub card_network: Option<api_enums::CardNetwork>,
pub card_type: Option<String>,
#[serde(default = "saved_in_locker_default")]
pub saved_to_locker: bool,
pub co_badged_card_data: Option<payment_methods::CoBadgedCardData>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct CardDetailsPaymentMethod {
pub last4_digits: Option<String>,
pub issuer_country: Option<String>,
pub expiry_month: Option<Secret<String>>,
pub expiry_year: Option<Secret<String>>,
pub nick_name: Option<Secret<String>>,
pub card_holder_name: Option<Secret<String>>,
pub card_isin: Option<String>,
pub card_issuer: Option<String>,
pub card_network: Option<api_enums::CardNetwork>,
pub card_type: Option<String>,
#[serde(default = "saved_in_locker_default")]
pub saved_to_locker: bool,
}
#[cfg(feature = "v2")]
impl CardDetailsPaymentMethod {
pub fn to_card_details_from_locker(self) -> payment_methods::CardDetailFromLocker {
payment_methods::CardDetailFromLocker {
card_number: None,
card_holder_name: self.card_holder_name.clone(),
card_issuer: self.card_issuer.clone(),
card_network: self.card_network.clone(),
card_type: self.card_type.clone(),
issuer_country: self.clone().get_issuer_country_alpha2(),
last4_digits: self.last4_digits,
expiry_month: self.expiry_month,
expiry_year: self.expiry_year,
card_fingerprint: None,
nick_name: self.nick_name,
card_isin: self.card_isin,
saved_to_locker: self.saved_to_locker,
}
}
pub fn get_issuer_country_alpha2(self) -> Option<common_enums::CountryAlpha2> {
self.issuer_country
.as_ref()
.map(|c| api_enums::CountryAlpha2::from_str(c))
.transpose()
.ok()
.flatten()
}
}
#[cfg(feature = "v1")]
impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod {
fn from(item: payment_methods::CardDetail) -> Self {
Self {
issuer_country: item.card_issuing_country.map(|c| c.to_string()),
last4_digits: Some(item.card_number.get_last4()),
expiry_month: Some(item.card_exp_month),
expiry_year: Some(item.card_exp_year),
card_holder_name: item.card_holder_name,
nick_name: item.nick_name,
card_isin: None,
card_issuer: item.card_issuer,
card_network: item.card_network,
card_type: item.card_type.map(|card| card.to_string()),
saved_to_locker: true,
co_badged_card_data: None,
}
}
}
#[cfg(feature = "v2")]
impl From<payment_methods::CardDetail> for CardDetailsPaymentMethod {
fn from(item: payment_methods::CardDetail) -> Self {
Self {
issuer_country: item.card_issuing_country.map(|c| c.to_string()),
last4_digits: Some(item.card_number.get_last4()),
expiry_month: Some(item.card_exp_month),
expiry_year: Some(item.card_exp_year),
card_holder_name: item.card_holder_name,
nick_name: item.nick_name,
card_isin: None,
card_issuer: item.card_issuer,
card_network: item.card_network,
card_type: item.card_type.map(|card| card.to_string()),
saved_to_locker: true,
}
}
}
#[cfg(feature = "v2")]
impl From<NetworkTokenDetails> for NetworkTokenDetailsPaymentMethod {
fn from(item: NetworkTokenDetails) -> Self {
Self {
issuer_country: item.card_issuing_country,
last4_digits: Some(item.network_token.get_last4()),
network_token_expiry_month: Some(item.network_token_exp_month),
network_token_expiry_year: Some(item.network_token_exp_year),
card_holder_name: item.card_holder_name,
nick_name: item.nick_name,
card_isin: None,
card_issuer: item.card_issuer,
card_network: item.card_network,
card_type: item.card_type.map(|card| card.to_string()),
saved_to_locker: true,
}
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)]
pub struct SingleUsePaymentMethodToken {
pub token: Secret<String>,
pub merchant_connector_id: id_type::MerchantConnectorAccountId,
}
#[cfg(feature = "v2")]
impl SingleUsePaymentMethodToken {
pub fn get_single_use_token_from_payment_method_token(
token: Secret<String>,
mca_id: id_type::MerchantConnectorAccountId,
) -> Self {
Self {
token,
merchant_connector_id: mca_id,
}
}
}
impl From<NetworkTokenDetailsPaymentMethod> for payment_methods::NetworkTokenDetailsPaymentMethod {
fn from(item: NetworkTokenDetailsPaymentMethod) -> Self {
Self {
last4_digits: item.last4_digits,
issuer_country: item.issuer_country,
network_token_expiry_month: item.network_token_expiry_month,
network_token_expiry_year: item.network_token_expiry_year,
nick_name: item.nick_name,
card_holder_name: item.card_holder_name,
card_isin: item.card_isin,
card_issuer: item.card_issuer,
card_network: item.card_network,
card_type: item.card_type,
saved_to_locker: item.saved_to_locker,
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize)]
pub struct SingleUseTokenKey(String);
#[cfg(feature = "v2")]
impl SingleUseTokenKey {
pub fn store_key(payment_method_id: &id_type::GlobalPaymentMethodId) -> Self {
let new_token = format!("single_use_token_{}", payment_method_id.get_string_repr());
Self(new_token)
}
pub fn get_store_key(&self) -> &str {
&self.0
}
}
#[cfg(feature = "v1")]
impl From<Card> for payment_methods::CardDetail {
fn from(card_data: Card) -> Self {
Self {
card_number: card_data.card_number.clone(),
card_exp_month: card_data.card_exp_month.clone(),
card_exp_year: card_data.card_exp_year.clone(),
card_holder_name: None,
nick_name: None,
card_issuing_country: None,
card_network: card_data.card_network.clone(),
card_issuer: None,
card_type: None,
}
}
}
#[cfg(feature = "v1")]
impl From<NetworkTokenData> for payment_methods::CardDetail {
fn from(network_token_data: NetworkTokenData) -> Self {
Self {
card_number: network_token_data.token_number.clone(),
card_exp_month: network_token_data.token_exp_month.clone(),
card_exp_year: network_token_data.token_exp_year.clone(),
card_holder_name: None,
nick_name: None,
card_issuing_country: None,
card_network: network_token_data.card_network.clone(),
card_issuer: None,
card_type: None,
}
}
}
#[cfg(feature = "v1")]
impl
From<(
payment_methods::CardDetail,
Option<&CardToken>,
Option<payment_methods::CoBadgedCardData>,
)> for Card
{
fn from(
value: (
payment_methods::CardDetail,
Option<&CardToken>,
Option<payment_methods::CoBadgedCardData>,
),
) -> Self {
let (
payment_methods::CardDetail {
card_number,
card_exp_month,
card_exp_year,
card_holder_name,
nick_name,
card_network,
card_issuer,
card_issuing_country,
card_type,
},
card_token_data,
co_badged_card_data,
) = value;
// The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
let name_on_card = if let Some(name) = card_holder_name.clone() {
if name.clone().expose().is_empty() {
card_token_data
.and_then(|token_data| token_data.card_holder_name.clone())
.or(Some(name))
} else {
card_holder_name
}
} else {
card_token_data.and_then(|token_data| token_data.card_holder_name.clone())
};
Self {
card_number,
card_exp_month,
card_exp_year,
card_holder_name: name_on_card,
card_cvc: card_token_data
.cloned()
.unwrap_or_default()
.card_cvc
.unwrap_or_default(),
card_issuer,
card_network,
card_type,
card_issuing_country,
bank_code: None,
nick_name,
co_badged_card_data,
}
}
}
#[cfg(feature = "v1")]
impl
TryFrom<(
cards::CardNumber,
Option<&CardToken>,
Option<payment_methods::CoBadgedCardData>,
CardDetailsPaymentMethod,
)> for Card
{
type Error = error_stack::Report<common_utils::errors::ValidationError>;
fn try_from(
value: (
cards::CardNumber,
Option<&CardToken>,
Option<payment_methods::CoBadgedCardData>,
CardDetailsPaymentMethod,
),
) -> Result<Self, Self::Error> {
let (card_number, card_token_data, co_badged_card_data, card_details) = value;
// The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
let name_on_card = if let Some(name) = card_details.card_holder_name.clone() {
if name.clone().expose().is_empty() {
card_token_data
.and_then(|token_data| token_data.card_holder_name.clone())
.or(Some(name))
} else {
Some(name)
}
} else {
card_token_data.and_then(|token_data| token_data.card_holder_name.clone())
};
Ok(Self {
card_number,
card_exp_month: card_details
.expiry_month
.get_required_value("expiry_month")?
.clone(),
card_exp_year: card_details
.expiry_year
.get_required_value("expiry_year")?
.clone(),
card_holder_name: name_on_card,
card_cvc: card_token_data
.cloned()
.unwrap_or_default()
.card_cvc
.unwrap_or_default(),
card_issuer: card_details.card_issuer,
card_network: card_details.card_network,
card_type: card_details.card_type,
card_issuing_country: card_details.issuer_country,
bank_code: None,
nick_name: card_details.nick_name,
co_badged_card_data,
})
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/payment_method_data.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 16,
"num_structs": 72,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_715126147985192618
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/merchant_key_store.rs
// Contains: 1 structs, 0 enums
use common_utils::{
crypto::Encryptable,
custom_serde, date_time,
errors::{CustomResult, ValidationError},
type_name,
types::keymanager::{self, KeyManagerState},
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret};
use time::PrimitiveDateTime;
use crate::type_encryption::{crypto_operation, CryptoOperation};
#[derive(Clone, Debug, serde::Serialize)]
pub struct MerchantKeyStore {
pub merchant_id: common_utils::id_type::MerchantId,
pub key: Encryptable<Secret<Vec<u8>>>,
#[serde(with = "custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for MerchantKeyStore {
type DstType = diesel_models::merchant_key_store::MerchantKeyStore;
type NewDstType = diesel_models::merchant_key_store::MerchantKeyStoreNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::merchant_key_store::MerchantKeyStore {
key: self.key.into(),
merchant_id: self.merchant_id,
created_at: self.created_at,
})
}
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
_key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let identifier = keymanager::Identifier::Merchant(item.merchant_id.clone());
Ok(Self {
key: crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::Decrypt(item.key),
identifier,
key.peek(),
)
.await
.and_then(|val| val.try_into_operation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
})?,
merchant_id: item.merchant_id,
created_at: item.created_at,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::merchant_key_store::MerchantKeyStoreNew {
merchant_id: self.merchant_id,
key: self.key.into(),
created_at: date_time::now(),
})
}
}
#[async_trait::async_trait]
pub trait MerchantKeyStoreInterface {
type Error;
async fn insert_merchant_key_store(
&self,
state: &KeyManagerState,
merchant_key_store: MerchantKeyStore,
key: &Secret<Vec<u8>>,
) -> CustomResult<MerchantKeyStore, Self::Error>;
async fn get_merchant_key_store_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
key: &Secret<Vec<u8>>,
) -> CustomResult<MerchantKeyStore, Self::Error>;
async fn delete_merchant_key_store_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, Self::Error>;
#[cfg(feature = "olap")]
async fn list_multiple_key_stores(
&self,
state: &KeyManagerState,
merchant_ids: Vec<common_utils::id_type::MerchantId>,
key: &Secret<Vec<u8>>,
) -> CustomResult<Vec<MerchantKeyStore>, Self::Error>;
async fn get_all_key_stores(
&self,
state: &KeyManagerState,
key: &Secret<Vec<u8>>,
from: u32,
to: u32,
) -> CustomResult<Vec<MerchantKeyStore>, Self::Error>;
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/merchant_key_store.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_6594958965765316437
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/routing.rs
// Contains: 4 structs, 2 enums
use std::collections::HashMap;
use api_models::{enums as api_enums, routing};
use common_utils::id_type;
use serde;
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingData {
pub routed_through: Option<String>,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub routing_info: PaymentRoutingInfo,
pub algorithm: Option<routing::StraightThroughAlgorithm>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingData {
// TODO: change this to RoutableConnectors enum
pub routed_through: Option<String>,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub pre_routing_connector_choice: Option<PreRoutingConnectorChoice>,
pub algorithm_requested: Option<id_type::RoutingId>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
#[serde(from = "PaymentRoutingInfoSerde", into = "PaymentRoutingInfoSerde")]
pub struct PaymentRoutingInfo {
pub algorithm: Option<routing::StraightThroughAlgorithm>,
pub pre_routing_results:
Option<HashMap<api_enums::PaymentMethodType, PreRoutingConnectorChoice>>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq)]
#[serde(untagged)]
pub enum PreRoutingConnectorChoice {
Single(routing::RoutableConnectorChoice),
Multiple(Vec<routing::RoutableConnectorChoice>),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentRoutingInfoInner {
pub algorithm: Option<routing::StraightThroughAlgorithm>,
pub pre_routing_results:
Option<HashMap<api_enums::PaymentMethodType, PreRoutingConnectorChoice>>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum PaymentRoutingInfoSerde {
OnlyAlgorithm(Box<routing::StraightThroughAlgorithm>),
WithDetails(Box<PaymentRoutingInfoInner>),
}
impl From<PaymentRoutingInfoSerde> for PaymentRoutingInfo {
fn from(value: PaymentRoutingInfoSerde) -> Self {
match value {
PaymentRoutingInfoSerde::OnlyAlgorithm(algo) => Self {
algorithm: Some(*algo),
pre_routing_results: None,
},
PaymentRoutingInfoSerde::WithDetails(details) => Self {
algorithm: details.algorithm,
pre_routing_results: details.pre_routing_results,
},
}
}
}
impl From<PaymentRoutingInfo> for PaymentRoutingInfoSerde {
fn from(value: PaymentRoutingInfo) -> Self {
Self::WithDetails(Box::new(PaymentRoutingInfoInner {
algorithm: value.algorithm,
pre_routing_results: value.pre_routing_results,
}))
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/routing.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 4,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-1477336632470821225
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/mandates.rs
// Contains: 11 structs, 1 enums
use std::collections::HashMap;
use api_models::payments::{
MandateAmountData as ApiMandateAmountData, MandateData as ApiMandateData, MandateType,
};
use common_enums::Currency;
use common_types::payments as common_payments_types;
use common_utils::{
date_time,
errors::{CustomResult, ParsingError},
pii,
types::MinorUnit,
};
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use crate::router_data::RecurringMandatePaymentData;
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub struct MandateDetails {
pub update_mandate_id: Option<String>,
}
impl From<MandateDetails> for diesel_models::enums::MandateDetails {
fn from(value: MandateDetails) -> Self {
Self {
update_mandate_id: value.update_mandate_id,
}
}
}
impl From<diesel_models::enums::MandateDetails> for MandateDetails {
fn from(value: diesel_models::enums::MandateDetails) -> Self {
Self {
update_mandate_id: value.update_mandate_id,
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, PartialEq, Eq)]
#[serde(rename_all = "snake_case")]
pub enum MandateDataType {
SingleUse(MandateAmountData),
MultiUse(Option<MandateAmountData>),
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq)]
pub struct MandateAmountData {
pub amount: MinorUnit,
pub currency: Currency,
pub start_date: Option<PrimitiveDateTime>,
pub end_date: Option<PrimitiveDateTime>,
pub metadata: Option<pii::SecretSerdeValue>,
}
// The fields on this struct are optional, as we want to allow the merchant to provide partial
// information about creating mandates
#[derive(Default, Eq, PartialEq, Debug, Clone, serde::Serialize)]
pub struct MandateData {
/// A way to update the mandate's payment method details
pub update_mandate_id: Option<String>,
/// A consent from the customer to store the payment method
pub customer_acceptance: Option<common_payments_types::CustomerAcceptance>,
/// A way to select the type of mandate used
pub mandate_type: Option<MandateDataType>,
}
impl From<MandateType> for MandateDataType {
fn from(mandate_type: MandateType) -> Self {
match mandate_type {
MandateType::SingleUse(mandate_amount_data) => {
Self::SingleUse(mandate_amount_data.into())
}
MandateType::MultiUse(mandate_amount_data) => {
Self::MultiUse(mandate_amount_data.map(|d| d.into()))
}
}
}
}
impl From<MandateDataType> for diesel_models::enums::MandateDataType {
fn from(value: MandateDataType) -> Self {
match value {
MandateDataType::SingleUse(data) => Self::SingleUse(data.into()),
MandateDataType::MultiUse(None) => Self::MultiUse(None),
MandateDataType::MultiUse(Some(data)) => Self::MultiUse(Some(data.into())),
}
}
}
impl From<diesel_models::enums::MandateDataType> for MandateDataType {
fn from(value: diesel_models::enums::MandateDataType) -> Self {
use diesel_models::enums::MandateDataType as DieselMandateDataType;
match value {
DieselMandateDataType::SingleUse(data) => Self::SingleUse(data.into()),
DieselMandateDataType::MultiUse(None) => Self::MultiUse(None),
DieselMandateDataType::MultiUse(Some(data)) => Self::MultiUse(Some(data.into())),
}
}
}
impl From<ApiMandateAmountData> for MandateAmountData {
fn from(value: ApiMandateAmountData) -> Self {
Self {
amount: value.amount,
currency: value.currency,
start_date: value.start_date,
end_date: value.end_date,
metadata: value.metadata,
}
}
}
impl From<MandateAmountData> for diesel_models::enums::MandateAmountData {
fn from(value: MandateAmountData) -> Self {
Self {
amount: value.amount,
currency: value.currency,
start_date: value.start_date,
end_date: value.end_date,
metadata: value.metadata,
}
}
}
impl From<diesel_models::enums::MandateAmountData> for MandateAmountData {
fn from(value: diesel_models::enums::MandateAmountData) -> Self {
Self {
amount: value.amount,
currency: value.currency,
start_date: value.start_date,
end_date: value.end_date,
metadata: value.metadata,
}
}
}
impl From<ApiMandateData> for MandateData {
fn from(value: ApiMandateData) -> Self {
Self {
customer_acceptance: value.customer_acceptance,
mandate_type: value.mandate_type.map(|d| d.into()),
update_mandate_id: value.update_mandate_id,
}
}
}
impl MandateAmountData {
pub fn get_end_date(
&self,
format: date_time::DateFormat,
) -> error_stack::Result<Option<String>, ParsingError> {
self.end_date
.map(|date| {
date_time::format_date(date, format)
.change_context(ParsingError::DateTimeParsingError)
})
.transpose()
}
pub fn get_metadata(&self) -> Option<pii::SecretSerdeValue> {
self.metadata.clone()
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentsMandateReferenceRecord {
pub connector_mandate_id: String,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub original_payment_authorized_amount: Option<i64>,
pub original_payment_authorized_currency: Option<Currency>,
pub mandate_metadata: Option<pii::SecretSerdeValue>,
pub connector_mandate_status: Option<common_enums::ConnectorMandateStatus>,
pub connector_mandate_request_reference_id: Option<String>,
}
#[cfg(feature = "v1")]
impl From<&PaymentsMandateReferenceRecord> for RecurringMandatePaymentData {
fn from(mandate_reference_record: &PaymentsMandateReferenceRecord) -> Self {
Self {
payment_method_type: mandate_reference_record.payment_method_type,
original_payment_authorized_amount: mandate_reference_record
.original_payment_authorized_amount,
original_payment_authorized_currency: mandate_reference_record
.original_payment_authorized_currency,
mandate_metadata: mandate_reference_record.mandate_metadata.clone(),
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConnectorTokenReferenceRecord {
pub connector_token: String,
pub payment_method_subtype: Option<common_enums::PaymentMethodType>,
pub original_payment_authorized_amount: Option<MinorUnit>,
pub original_payment_authorized_currency: Option<Currency>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_token_status: common_enums::ConnectorTokenStatus,
pub connector_token_request_reference_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PayoutsMandateReferenceRecord {
pub transfer_method_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PayoutsMandateReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>,
);
impl std::ops::Deref for PayoutsMandateReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl std::ops::DerefMut for PayoutsMandateReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentsTokenReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>,
);
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentsMandateReference(
pub HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>,
);
#[cfg(feature = "v1")]
impl std::ops::Deref for PaymentsMandateReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "v1")]
impl std::ops::DerefMut for PaymentsMandateReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v2")]
impl std::ops::Deref for PaymentsTokenReference {
type Target =
HashMap<common_utils::id_type::MerchantConnectorAccountId, ConnectorTokenReferenceRecord>;
fn deref(&self) -> &Self::Target {
&self.0
}
}
#[cfg(feature = "v2")]
impl std::ops::DerefMut for PaymentsTokenReference {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CommonMandateReference {
pub payments: Option<PaymentsMandateReference>,
pub payouts: Option<PayoutsMandateReference>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct CommonMandateReference {
pub payments: Option<PaymentsTokenReference>,
pub payouts: Option<PayoutsMandateReference>,
}
impl CommonMandateReference {
pub fn get_mandate_details_value(&self) -> CustomResult<serde_json::Value, ParsingError> {
let mut payments = self
.payments
.as_ref()
.map_or_else(|| Ok(serde_json::json!({})), serde_json::to_value)
.change_context(ParsingError::StructParseFailure("payment mandate details"))?;
self.payouts
.as_ref()
.map(|payouts_mandate| {
serde_json::to_value(payouts_mandate).map(|payouts_mandate_value| {
payments.as_object_mut().map(|payments_object| {
payments_object.insert("payouts".to_string(), payouts_mandate_value);
})
})
})
.transpose()
.change_context(ParsingError::StructParseFailure("payout mandate details"))?;
Ok(payments)
}
#[cfg(feature = "v2")]
/// Insert a new payment token reference for the given connector_id
pub fn insert_payment_token_reference_record(
&mut self,
connector_id: &common_utils::id_type::MerchantConnectorAccountId,
record: ConnectorTokenReferenceRecord,
) {
match self.payments {
Some(ref mut payments_reference) => {
payments_reference.insert(connector_id.clone(), record);
}
None => {
let mut payments_reference = HashMap::new();
payments_reference.insert(connector_id.clone(), record);
self.payments = Some(PaymentsTokenReference(payments_reference));
}
}
}
}
impl From<diesel_models::CommonMandateReference> for CommonMandateReference {
fn from(value: diesel_models::CommonMandateReference) -> Self {
Self {
payments: value.payments.map(|payments| payments.into()),
payouts: value.payouts.map(|payouts| payouts.into()),
}
}
}
impl From<CommonMandateReference> for diesel_models::CommonMandateReference {
fn from(value: CommonMandateReference) -> Self {
Self {
payments: value.payments.map(|payments| payments.into()),
payouts: value.payouts.map(|payouts| payouts.into()),
}
}
}
impl From<diesel_models::PayoutsMandateReference> for PayoutsMandateReference {
fn from(value: diesel_models::PayoutsMandateReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
impl From<PayoutsMandateReference> for diesel_models::PayoutsMandateReference {
fn from(value: PayoutsMandateReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
#[cfg(feature = "v1")]
impl From<diesel_models::PaymentsMandateReference> for PaymentsMandateReference {
fn from(value: diesel_models::PaymentsMandateReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
#[cfg(feature = "v1")]
impl From<PaymentsMandateReference> for diesel_models::PaymentsMandateReference {
fn from(value: PaymentsMandateReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
#[cfg(feature = "v2")]
impl From<diesel_models::PaymentsTokenReference> for PaymentsTokenReference {
fn from(value: diesel_models::PaymentsTokenReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
#[cfg(feature = "v2")]
impl From<PaymentsTokenReference> for diesel_models::PaymentsTokenReference {
fn from(value: PaymentsTokenReference) -> Self {
Self(
value
.0
.into_iter()
.map(|(key, record)| (key, record.into()))
.collect(),
)
}
}
impl From<diesel_models::PayoutsMandateReferenceRecord> for PayoutsMandateReferenceRecord {
fn from(value: diesel_models::PayoutsMandateReferenceRecord) -> Self {
Self {
transfer_method_id: value.transfer_method_id,
}
}
}
impl From<PayoutsMandateReferenceRecord> for diesel_models::PayoutsMandateReferenceRecord {
fn from(value: PayoutsMandateReferenceRecord) -> Self {
Self {
transfer_method_id: value.transfer_method_id,
}
}
}
#[cfg(feature = "v2")]
impl From<diesel_models::ConnectorTokenReferenceRecord> for ConnectorTokenReferenceRecord {
fn from(value: diesel_models::ConnectorTokenReferenceRecord) -> Self {
let diesel_models::ConnectorTokenReferenceRecord {
connector_token,
payment_method_subtype,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token_status,
connector_token_request_reference_id,
} = value;
Self {
connector_token,
payment_method_subtype,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token_status,
connector_token_request_reference_id,
}
}
}
#[cfg(feature = "v1")]
impl From<diesel_models::PaymentsMandateReferenceRecord> for PaymentsMandateReferenceRecord {
fn from(value: diesel_models::PaymentsMandateReferenceRecord) -> Self {
Self {
connector_mandate_id: value.connector_mandate_id,
payment_method_type: value.payment_method_type,
original_payment_authorized_amount: value.original_payment_authorized_amount,
original_payment_authorized_currency: value.original_payment_authorized_currency,
mandate_metadata: value.mandate_metadata,
connector_mandate_status: value.connector_mandate_status,
connector_mandate_request_reference_id: value.connector_mandate_request_reference_id,
}
}
}
#[cfg(feature = "v2")]
impl From<ConnectorTokenReferenceRecord> for diesel_models::ConnectorTokenReferenceRecord {
fn from(value: ConnectorTokenReferenceRecord) -> Self {
let ConnectorTokenReferenceRecord {
connector_token,
payment_method_subtype,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token_status,
connector_token_request_reference_id,
} = value;
Self {
connector_token,
payment_method_subtype,
original_payment_authorized_amount,
original_payment_authorized_currency,
metadata,
connector_token_status,
connector_token_request_reference_id,
}
}
}
#[cfg(feature = "v1")]
impl From<PaymentsMandateReferenceRecord> for diesel_models::PaymentsMandateReferenceRecord {
fn from(value: PaymentsMandateReferenceRecord) -> Self {
Self {
connector_mandate_id: value.connector_mandate_id,
payment_method_type: value.payment_method_type,
original_payment_authorized_amount: value.original_payment_authorized_amount,
original_payment_authorized_currency: value.original_payment_authorized_currency,
mandate_metadata: value.mandate_metadata,
connector_mandate_status: value.connector_mandate_status,
connector_mandate_request_reference_id: value.connector_mandate_request_reference_id,
}
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/mandates.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 11,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-3322940821507888033
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/api.rs
// Contains: 7 structs, 3 enums
use std::{collections::HashSet, fmt::Display};
use common_utils::{
events::{ApiEventMetric, ApiEventsType},
impl_api_event_type,
};
use super::payment_method_data::PaymentMethodData;
#[derive(Debug, PartialEq)]
pub enum ApplicationResponse<R> {
Json(R),
StatusOk,
TextPlain(String),
JsonForRedirection(api_models::payments::RedirectionResponse),
Form(Box<RedirectionFormData>),
PaymentLinkForm(Box<PaymentLinkAction>),
FileData((Vec<u8>, mime::Mime)),
JsonWithHeaders((R, Vec<(String, masking::Maskable<String>)>)),
GenericLinkForm(Box<GenericLinks>),
}
impl<R> ApplicationResponse<R> {
/// Get the json response from response
#[inline]
pub fn get_json_body(
self,
) -> common_utils::errors::CustomResult<R, common_utils::errors::ValidationError> {
match self {
Self::Json(body) | Self::JsonWithHeaders((body, _)) => Ok(body),
Self::TextPlain(_)
| Self::JsonForRedirection(_)
| Self::Form(_)
| Self::PaymentLinkForm(_)
| Self::FileData(_)
| Self::GenericLinkForm(_)
| Self::StatusOk => Err(common_utils::errors::ValidationError::InvalidValue {
message: "expected either Json or JsonWithHeaders Response".to_string(),
}
.into()),
}
}
}
impl<T: ApiEventMetric> ApiEventMetric for ApplicationResponse<T> {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
match self {
Self::Json(r) => r.get_api_event_type(),
Self::JsonWithHeaders((r, _)) => r.get_api_event_type(),
_ => None,
}
}
}
impl_api_event_type!(Miscellaneous, (PaymentLinkFormData, GenericLinkFormData));
#[derive(Debug, PartialEq)]
pub struct RedirectionFormData {
pub redirect_form: crate::router_response_types::RedirectForm,
pub payment_method_data: Option<PaymentMethodData>,
pub amount: String,
pub currency: String,
}
#[derive(Debug, Eq, PartialEq)]
pub enum PaymentLinkAction {
PaymentLinkFormData(PaymentLinkFormData),
PaymentLinkStatus(PaymentLinkStatusData),
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentLinkFormData {
pub js_script: String,
pub css_script: String,
pub sdk_url: url::Url,
pub html_meta_tags: String,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct PaymentLinkStatusData {
pub js_script: String,
pub css_script: String,
}
#[derive(Debug, Eq, PartialEq)]
pub struct GenericLinks {
pub allowed_domains: HashSet<String>,
pub data: GenericLinksData,
pub locale: String,
}
#[derive(Debug, Eq, PartialEq)]
pub enum GenericLinksData {
ExpiredLink(GenericExpiredLinkData),
PaymentMethodCollect(GenericLinkFormData),
PayoutLink(GenericLinkFormData),
PayoutLinkStatus(GenericLinkStatusData),
PaymentMethodCollectStatus(GenericLinkStatusData),
SecurePaymentLink(PaymentLinkFormData),
}
impl Display for GenericLinksData {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
"{}",
match *self {
Self::ExpiredLink(_) => "ExpiredLink",
Self::PaymentMethodCollect(_) => "PaymentMethodCollect",
Self::PayoutLink(_) => "PayoutLink",
Self::PayoutLinkStatus(_) => "PayoutLinkStatus",
Self::PaymentMethodCollectStatus(_) => "PaymentMethodCollectStatus",
Self::SecurePaymentLink(_) => "SecurePaymentLink",
}
)
}
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericExpiredLinkData {
pub title: String,
pub message: String,
pub theme: String,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericLinkFormData {
pub js_data: String,
pub css_data: String,
pub sdk_url: url::Url,
pub html_meta_tags: String,
}
#[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)]
pub struct GenericLinkStatusData {
pub js_data: String,
pub css_data: String,
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/api.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 3,
"num_structs": 7,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-2597158958520288136
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/relay.rs
// Contains: 2 structs, 2 enums
use common_enums::enums;
use common_utils::{
self,
errors::{CustomResult, ValidationError},
id_type::{self, GenerateId},
pii,
types::{keymanager, MinorUnit},
};
use diesel_models::relay::RelayUpdateInternal;
use error_stack::ResultExt;
use masking::{ExposeInterface, Secret};
use serde::{self, Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::{router_data::ErrorResponse, router_response_types};
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct Relay {
pub id: id_type::RelayId,
pub connector_resource_id: String,
pub connector_id: id_type::MerchantConnectorAccountId,
pub profile_id: id_type::ProfileId,
pub merchant_id: id_type::MerchantId,
pub relay_type: enums::RelayType,
pub request_data: Option<RelayData>,
pub status: enums::RelayStatus,
pub connector_reference_id: Option<String>,
pub error_code: Option<String>,
pub error_message: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub response_data: Option<pii::SecretSerdeValue>,
}
impl Relay {
pub fn new(
relay_request: &api_models::relay::RelayRequest,
merchant_id: &id_type::MerchantId,
profile_id: &id_type::ProfileId,
) -> Self {
let relay_id = id_type::RelayId::generate();
Self {
id: relay_id.clone(),
connector_resource_id: relay_request.connector_resource_id.clone(),
connector_id: relay_request.connector_id.clone(),
profile_id: profile_id.clone(),
merchant_id: merchant_id.clone(),
relay_type: common_enums::RelayType::Refund,
request_data: relay_request.data.clone().map(From::from),
status: common_enums::RelayStatus::Created,
connector_reference_id: None,
error_code: None,
error_message: None,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
response_data: None,
}
}
}
impl From<api_models::relay::RelayData> for RelayData {
fn from(relay: api_models::relay::RelayData) -> Self {
match relay {
api_models::relay::RelayData::Refund(relay_refund_request) => {
Self::Refund(RelayRefundData {
amount: relay_refund_request.amount,
currency: relay_refund_request.currency,
reason: relay_refund_request.reason,
})
}
}
}
}
impl From<api_models::relay::RelayRefundRequestData> for RelayRefundData {
fn from(relay: api_models::relay::RelayRefundRequestData) -> Self {
Self {
amount: relay.amount,
currency: relay.currency,
reason: relay.reason,
}
}
}
impl RelayUpdate {
pub fn from(
response: Result<router_response_types::RefundsResponseData, ErrorResponse>,
) -> Self {
match response {
Err(error) => Self::ErrorUpdate {
error_code: error.code,
error_message: error.reason.unwrap_or(error.message),
status: common_enums::RelayStatus::Failure,
},
Ok(response) => Self::StatusUpdate {
connector_reference_id: Some(response.connector_refund_id),
status: common_enums::RelayStatus::from(response.refund_status),
},
}
}
}
impl From<RelayData> for api_models::relay::RelayData {
fn from(relay: RelayData) -> Self {
match relay {
RelayData::Refund(relay_refund_request) => {
Self::Refund(api_models::relay::RelayRefundRequestData {
amount: relay_refund_request.amount,
currency: relay_refund_request.currency,
reason: relay_refund_request.reason,
})
}
}
}
}
impl From<Relay> for api_models::relay::RelayResponse {
fn from(value: Relay) -> Self {
let error = value
.error_code
.zip(value.error_message)
.map(
|(error_code, error_message)| api_models::relay::RelayError {
code: error_code,
message: error_message,
},
);
let data = value.request_data.map(|relay_data| match relay_data {
RelayData::Refund(relay_refund_request) => {
api_models::relay::RelayData::Refund(api_models::relay::RelayRefundRequestData {
amount: relay_refund_request.amount,
currency: relay_refund_request.currency,
reason: relay_refund_request.reason,
})
}
});
Self {
id: value.id,
status: value.status,
error,
connector_resource_id: value.connector_resource_id,
connector_id: value.connector_id,
profile_id: value.profile_id,
relay_type: value.relay_type,
data,
connector_reference_id: value.connector_reference_id,
}
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "snake_case", untagged)]
pub enum RelayData {
Refund(RelayRefundData),
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct RelayRefundData {
pub amount: MinorUnit,
pub currency: enums::Currency,
pub reason: Option<String>,
}
#[derive(Debug)]
pub enum RelayUpdate {
ErrorUpdate {
error_code: String,
error_message: String,
status: enums::RelayStatus,
},
StatusUpdate {
connector_reference_id: Option<String>,
status: common_enums::RelayStatus,
},
}
impl From<RelayUpdate> for RelayUpdateInternal {
fn from(value: RelayUpdate) -> Self {
match value {
RelayUpdate::ErrorUpdate {
error_code,
error_message,
status,
} => Self {
error_code: Some(error_code),
error_message: Some(error_message),
connector_reference_id: None,
status: Some(status),
modified_at: common_utils::date_time::now(),
},
RelayUpdate::StatusUpdate {
connector_reference_id,
status,
} => Self {
connector_reference_id,
status: Some(status),
error_code: None,
error_message: None,
modified_at: common_utils::date_time::now(),
},
}
}
}
#[async_trait::async_trait]
impl super::behaviour::Conversion for Relay {
type DstType = diesel_models::relay::Relay;
type NewDstType = diesel_models::relay::RelayNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::relay::Relay {
id: self.id,
connector_resource_id: self.connector_resource_id,
connector_id: self.connector_id,
profile_id: self.profile_id,
merchant_id: self.merchant_id,
relay_type: self.relay_type,
request_data: self
.request_data
.map(|data| {
serde_json::to_value(data).change_context(ValidationError::InvalidValue {
message: "Failed while decrypting business profile data".to_string(),
})
})
.transpose()?
.map(Secret::new),
status: self.status,
connector_reference_id: self.connector_reference_id,
error_code: self.error_code,
error_message: self.error_message,
created_at: self.created_at,
modified_at: self.modified_at,
response_data: self.response_data,
})
}
async fn convert_back(
_state: &keymanager::KeyManagerState,
item: Self::DstType,
_key: &Secret<Vec<u8>>,
_key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError> {
Ok(Self {
id: item.id,
connector_resource_id: item.connector_resource_id,
connector_id: item.connector_id,
profile_id: item.profile_id,
merchant_id: item.merchant_id,
relay_type: enums::RelayType::Refund,
request_data: item
.request_data
.map(|data| {
serde_json::from_value(data.expose()).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting business profile data".to_string(),
},
)
})
.transpose()?,
status: item.status,
connector_reference_id: item.connector_reference_id,
error_code: item.error_code,
error_message: item.error_message,
created_at: item.created_at,
modified_at: item.modified_at,
response_data: item.response_data,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(diesel_models::relay::RelayNew {
id: self.id,
connector_resource_id: self.connector_resource_id,
connector_id: self.connector_id,
profile_id: self.profile_id,
merchant_id: self.merchant_id,
relay_type: self.relay_type,
request_data: self
.request_data
.map(|data| {
serde_json::to_value(data).change_context(ValidationError::InvalidValue {
message: "Failed while decrypting business profile data".to_string(),
})
})
.transpose()?
.map(Secret::new),
status: self.status,
connector_reference_id: self.connector_reference_id,
error_code: self.error_code,
error_message: self.error_message,
created_at: self.created_at,
modified_at: self.modified_at,
response_data: self.response_data,
})
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/relay.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_3786539258130852148
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/chat.rs
// Contains: 2 structs, 0 enums
use common_utils::id_type;
use masking::Secret;
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct GetDataMessage {
pub message: Secret<String>,
}
#[derive(Debug, serde::Deserialize, serde::Serialize, Clone)]
pub struct HyperswitchAiDataRequest {
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
pub org_id: id_type::OrganizationId,
pub query: GetDataMessage,
pub entity_type: common_enums::EntityType,
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/chat.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-3171203478715366794
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
// Contains: 11 structs, 2 enums
#[cfg(all(feature = "v1", feature = "olap"))]
use api_models::enums::Connector;
use common_enums as storage_enums;
#[cfg(feature = "v2")]
use common_types::payments as common_payments_types;
#[cfg(feature = "v1")]
use common_types::primitive_wrappers::{
ExtendedAuthorizationAppliedBool, OvercaptureEnabledBool, RequestExtendedAuthorizationBool,
};
#[cfg(feature = "v2")]
use common_utils::{
crypto::Encryptable, encryption::Encryption, ext_traits::Encode,
types::keymanager::ToEncryptable,
};
use common_utils::{
errors::{CustomResult, ValidationError},
ext_traits::{OptionExt, ValueExt},
id_type, pii,
types::{
keymanager::{self, KeyManagerState},
ConnectorTransactionId, ConnectorTransactionIdTrait, CreatedBy, MinorUnit,
},
};
#[cfg(feature = "v1")]
use diesel_models::{
ConnectorMandateReferenceId, NetworkDetails, PaymentAttemptUpdate as DieselPaymentAttemptUpdate,
};
use diesel_models::{
PaymentAttempt as DieselPaymentAttempt, PaymentAttemptNew as DieselPaymentAttemptNew,
};
#[cfg(feature = "v2")]
use diesel_models::{
PaymentAttemptFeatureMetadata as DieselPaymentAttemptFeatureMetadata,
PaymentAttemptRecoveryData as DieselPassiveChurnRecoveryData,
};
use error_stack::ResultExt;
#[cfg(feature = "v2")]
use masking::PeekInterface;
use masking::Secret;
#[cfg(feature = "v1")]
use router_env::logger;
#[cfg(feature = "v2")]
use rustc_hash::FxHashMap;
#[cfg(feature = "v1")]
use serde::Deserialize;
use serde::Serialize;
#[cfg(feature = "v2")]
use serde_json::Value;
use time::PrimitiveDateTime;
#[cfg(all(feature = "v1", feature = "olap"))]
use super::PaymentIntent;
#[cfg(feature = "v2")]
use crate::{
address::Address,
consts,
merchant_key_store::MerchantKeyStore,
router_response_types,
type_encryption::{crypto_operation, CryptoOperation},
};
use crate::{behaviour, errors, ForeignIDRef};
#[cfg(feature = "v1")]
use crate::{
mandates::{MandateDataType, MandateDetails},
router_request_types,
};
#[async_trait::async_trait]
pub trait PaymentAttemptInterface {
type Error;
#[cfg(feature = "v1")]
async fn insert_payment_attempt(
&self,
payment_attempt: PaymentAttemptNew,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v2")]
async fn insert_payment_attempt(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
payment_attempt: PaymentAttempt,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v1")]
async fn update_payment_attempt_with_attempt_id(
&self,
this: PaymentAttempt,
payment_attempt: PaymentAttemptUpdate,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v2")]
async fn update_payment_attempt(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
this: PaymentAttempt,
payment_attempt: PaymentAttemptUpdate,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
&self,
connector_transaction_id: &ConnectorTransactionId,
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v1")]
async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
&self,
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v1")]
async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
&self,
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v2")]
async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
payment_id: &id_type::GlobalPaymentId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_merchant_id_connector_txn_id(
&self,
merchant_id: &id_type::MerchantId,
connector_txn_id: &str,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v2")]
async fn find_payment_attempt_by_profile_id_connector_transaction_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
profile_id: &id_type::ProfileId,
connector_transaction_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, Self::Error>;
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&self,
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
attempt_id: &str,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_attempt_id_merchant_id(
&self,
attempt_id: &str,
merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v2")]
async fn find_payment_attempt_by_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
attempt_id: &id_type::GlobalAttemptId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v2")]
async fn find_payment_attempts_by_payment_intent_id(
&self,
state: &KeyManagerState,
payment_id: &id_type::GlobalPaymentId,
merchant_key_store: &MerchantKeyStore,
storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentAttempt>, Self::Error>;
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_preprocessing_id_merchant_id(
&self,
preprocessing_id: &str,
merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentAttempt, Self::Error>;
#[cfg(feature = "v1")]
async fn find_attempts_by_merchant_id_payment_id(
&self,
merchant_id: &id_type::MerchantId,
payment_id: &id_type::PaymentId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentAttempt>, Self::Error>;
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_filters_for_payments(
&self,
pi: &[PaymentIntent],
merchant_id: &id_type::MerchantId,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentListFilters, Self::Error>;
#[cfg(all(feature = "v1", feature = "olap"))]
#[allow(clippy::too_many_arguments)]
async fn get_total_count_of_filtered_payment_attempts(
&self,
merchant_id: &id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<Vec<Connector>>,
payment_method: Option<Vec<storage_enums::PaymentMethod>>,
payment_method_type: Option<Vec<storage_enums::PaymentMethodType>>,
authentication_type: Option<Vec<storage_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
card_network: Option<Vec<storage_enums::CardNetwork>>,
card_discovery: Option<Vec<storage_enums::CardDiscovery>>,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<i64, Self::Error>;
#[cfg(all(feature = "v2", feature = "olap"))]
#[allow(clippy::too_many_arguments)]
async fn get_total_count_of_filtered_payment_attempts(
&self,
merchant_id: &id_type::MerchantId,
active_attempt_ids: &[String],
connector: Option<Vec<api_models::enums::Connector>>,
payment_method_type: Option<Vec<storage_enums::PaymentMethod>>,
payment_method_subtype: Option<Vec<storage_enums::PaymentMethodType>>,
authentication_type: Option<Vec<storage_enums::AuthenticationType>>,
merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
card_network: Option<Vec<storage_enums::CardNetwork>>,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<i64, Self::Error>;
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
pub struct AttemptAmountDetails {
/// The total amount for this payment attempt. This includes all the surcharge and tax amounts.
net_amount: MinorUnit,
/// The amount that has to be captured,
amount_to_capture: Option<MinorUnit>,
/// Surcharge amount for the payment attempt.
/// This is either derived by surcharge rules, or sent by the merchant
surcharge_amount: Option<MinorUnit>,
/// Tax amount for the payment attempt
/// This is either derived by surcharge rules, or sent by the merchant
tax_on_surcharge: Option<MinorUnit>,
/// The total amount that can be captured for this payment attempt.
amount_capturable: MinorUnit,
/// Shipping cost for the payment attempt.
shipping_cost: Option<MinorUnit>,
/// Tax amount for the order.
/// This is either derived by calling an external tax processor, or sent by the merchant
order_tax_amount: Option<MinorUnit>,
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
pub struct AttemptAmountDetailsSetter {
/// The total amount for this payment attempt. This includes all the surcharge and tax amounts.
pub net_amount: MinorUnit,
/// The amount that has to be captured,
pub amount_to_capture: Option<MinorUnit>,
/// Surcharge amount for the payment attempt.
/// This is either derived by surcharge rules, or sent by the merchant
pub surcharge_amount: Option<MinorUnit>,
/// Tax amount for the payment attempt
/// This is either derived by surcharge rules, or sent by the merchant
pub tax_on_surcharge: Option<MinorUnit>,
/// The total amount that can be captured for this payment attempt.
pub amount_capturable: MinorUnit,
/// Shipping cost for the payment attempt.
pub shipping_cost: Option<MinorUnit>,
/// Tax amount for the order.
/// This is either derived by calling an external tax processor, or sent by the merchant
pub order_tax_amount: Option<MinorUnit>,
}
/// Set the fields of amount details, since the fields are not public
impl From<AttemptAmountDetailsSetter> for AttemptAmountDetails {
fn from(setter: AttemptAmountDetailsSetter) -> Self {
Self {
net_amount: setter.net_amount,
amount_to_capture: setter.amount_to_capture,
surcharge_amount: setter.surcharge_amount,
tax_on_surcharge: setter.tax_on_surcharge,
amount_capturable: setter.amount_capturable,
shipping_cost: setter.shipping_cost,
order_tax_amount: setter.order_tax_amount,
}
}
}
impl AttemptAmountDetails {
pub fn get_net_amount(&self) -> MinorUnit {
self.net_amount
}
pub fn get_amount_to_capture(&self) -> Option<MinorUnit> {
self.amount_to_capture
}
pub fn get_surcharge_amount(&self) -> Option<MinorUnit> {
self.surcharge_amount
}
pub fn get_tax_on_surcharge(&self) -> Option<MinorUnit> {
self.tax_on_surcharge
}
pub fn get_amount_capturable(&self) -> MinorUnit {
self.amount_capturable
}
pub fn get_shipping_cost(&self) -> Option<MinorUnit> {
self.shipping_cost
}
pub fn get_order_tax_amount(&self) -> Option<MinorUnit> {
self.order_tax_amount
}
pub fn set_amount_to_capture(&mut self, amount_to_capture: MinorUnit) {
self.amount_to_capture = Some(amount_to_capture);
}
/// Validate the amount to capture that is sent in the request
pub fn validate_amount_to_capture(
&self,
request_amount_to_capture: MinorUnit,
) -> Result<(), ValidationError> {
common_utils::fp_utils::when(request_amount_to_capture > self.get_net_amount(), || {
Err(ValidationError::IncorrectValueProvided {
field_name: "amount_to_capture",
})
})
}
}
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
pub struct ErrorDetails {
/// The error code that was returned by the connector.
/// This is a mandatory field. This is used to lookup the global status map record for unified code and retries
pub code: String,
/// The error message that was returned by the connector.
/// This is a mandatory field. This is used to lookup the global status map record for unified message and retries
pub message: String,
/// The detailed error reason that was returned by the connector.
pub reason: Option<String>,
/// The unified code that is generated by the application based on the global status map record.
/// This can be relied upon for common error code across all connectors
pub unified_code: Option<String>,
/// The unified message that is generated by the application based on the global status map record.
/// This can be relied upon for common error code across all connectors
/// If there is translation available, message will be translated to the requested language
pub unified_message: Option<String>,
/// This field can be returned for both approved and refused Mastercard payments.
/// This code provides additional information about the type of transaction or the reason why the payment failed.
/// If the payment failed, the network advice code gives guidance on if and when you can retry the payment.
pub network_advice_code: Option<String>,
/// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed.
pub network_decline_code: Option<String>,
/// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better.
pub network_error_message: Option<String>,
}
#[cfg(feature = "v2")]
impl From<ErrorDetails> for api_models::payments::RecordAttemptErrorDetails {
fn from(error_details: ErrorDetails) -> Self {
Self {
code: error_details.code,
message: error_details.message,
network_decline_code: error_details.network_decline_code,
network_advice_code: error_details.network_advice_code,
network_error_message: error_details.network_error_message,
}
}
}
/// Domain model for the payment attempt.
/// Few fields which are related are grouped together for better readability and understandability.
/// These fields will be flattened and stored in the database in individual columns
#[cfg(feature = "v2")]
#[derive(Clone, Debug, PartialEq, serde::Serialize, router_derive::ToEncryption)]
pub struct PaymentAttempt {
/// Payment id for the payment attempt
pub payment_id: id_type::GlobalPaymentId,
/// Merchant id for the payment attempt
pub merchant_id: id_type::MerchantId,
/// Group id for the payment attempt
pub attempts_group_id: Option<String>,
/// Amount details for the payment attempt
pub amount_details: AttemptAmountDetails,
/// Status of the payment attempt. This is the status that is updated by the connector.
/// The intent status is updated by the AttemptStatus.
pub status: storage_enums::AttemptStatus,
/// Name of the connector that was used for the payment attempt. The connector is either decided by
/// either running the routing algorithm or by straight through processing request.
/// This will be updated before calling the connector
// TODO: use connector enum, this should be done in v1 as well as a part of moving to domain types wherever possible
pub connector: Option<String>,
/// Error details in case the payment attempt failed
pub error: Option<ErrorDetails>,
/// The authentication type that was requested for the payment attempt.
/// This authentication type maybe decided by step up 3ds or by running the decision engine.
pub authentication_type: storage_enums::AuthenticationType,
/// The time at which the payment attempt was created
pub created_at: PrimitiveDateTime,
/// The time at which the payment attempt was last modified
pub modified_at: PrimitiveDateTime,
pub last_synced: Option<PrimitiveDateTime>,
/// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have
/// Cancellation reason will be validated at the connector level when building the request
pub cancellation_reason: Option<String>,
/// Browser information required for 3DS authentication
pub browser_info: Option<common_utils::types::BrowserInformation>,
/// Payment token is the token used for temporary use in case the payment method is stored in vault
pub payment_token: Option<String>,
/// Metadata that is returned by the connector.
pub connector_metadata: Option<pii::SecretSerdeValue>,
pub payment_experience: Option<storage_enums::PaymentExperience>,
/// The insensitive data of the payment method data is stored here
pub payment_method_data: Option<pii::SecretSerdeValue>,
/// The result of the routing algorithm.
/// This will store the list of connectors and other related information that was used to route the payment.
// TODO: change this to type instead of serde_json::Value
pub routing_result: Option<Value>,
pub preprocessing_step_id: Option<String>,
/// Number of captures that have happened for the payment attempt
pub multiple_capture_count: Option<i16>,
/// A reference to the payment at connector side. This is returned by the connector
pub connector_response_reference_id: Option<String>,
/// Whether the payment was updated by postgres or redis
pub updated_by: String,
/// The authentication data which is used for external authentication
pub redirection_data: Option<router_response_types::RedirectForm>,
pub encoded_data: Option<Secret<String>>,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
/// Whether external 3DS authentication was attempted for this payment.
/// This is based on the configuration of the merchant in the business profile
pub external_three_ds_authentication_attempted: Option<bool>,
/// The connector that was used for external authentication
pub authentication_connector: Option<String>,
/// The foreign key reference to the authentication details
pub authentication_id: Option<id_type::AuthenticationId>,
pub fingerprint_id: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<Secret<common_payments_types::CustomerAcceptance>>,
/// The profile id for the payment attempt. This will be derived from payment intent.
pub profile_id: id_type::ProfileId,
/// The organization id for the payment attempt. This will be derived from payment intent.
pub organization_id: id_type::OrganizationId,
/// Payment method type for the payment attempt
pub payment_method_type: storage_enums::PaymentMethod,
/// Foreig key reference of Payment method id in case the payment instrument was stored
pub payment_method_id: Option<id_type::GlobalPaymentMethodId>,
/// The reference to the payment at the connector side
pub connector_payment_id: Option<String>,
/// The payment method subtype for the payment attempt.
pub payment_method_subtype: storage_enums::PaymentMethodType,
/// The authentication type that was applied for the payment attempt.
pub authentication_applied: Option<common_enums::AuthenticationType>,
/// A reference to the payment at connector side. This is returned by the connector
pub external_reference_id: Option<String>,
/// The billing address for the payment method
#[encrypt(ty = Value)]
pub payment_method_billing_address: Option<Encryptable<Address>>,
/// The global identifier for the payment attempt
pub id: id_type::GlobalAttemptId,
/// Connector token information that can be used to make payments directly by the merchant.
pub connector_token_details: Option<diesel_models::ConnectorTokenDetails>,
/// Indicates the method by which a card is discovered during a payment
pub card_discovery: Option<common_enums::CardDiscovery>,
/// Split payment data
pub charges: Option<common_types::payments::ConnectorChargeResponseData>,
/// Additional data that might be required by hyperswitch, to enable some specific features.
pub feature_metadata: Option<PaymentAttemptFeatureMetadata>,
/// merchant who owns the credentials of the processor, i.e. processor owner
pub processor_merchant_id: id_type::MerchantId,
/// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard))
pub created_by: Option<CreatedBy>,
pub connector_request_reference_id: Option<String>,
pub network_transaction_id: Option<String>,
/// stores the authorized amount in case of partial authorization
pub authorized_amount: Option<MinorUnit>,
}
impl PaymentAttempt {
#[cfg(feature = "v1")]
pub fn get_payment_method(&self) -> Option<storage_enums::PaymentMethod> {
self.payment_method
}
#[cfg(feature = "v2")]
pub fn get_payment_method(&self) -> Option<storage_enums::PaymentMethod> {
// TODO: check if we can fix this
Some(self.payment_method_type)
}
#[cfg(feature = "v1")]
pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethodType> {
self.payment_method_type
}
#[cfg(feature = "v2")]
pub fn get_payment_method_type(&self) -> Option<storage_enums::PaymentMethodType> {
// TODO: check if we can fix this
Some(self.payment_method_subtype)
}
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &str {
&self.attempt_id
}
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &id_type::GlobalAttemptId {
&self.id
}
#[cfg(feature = "v1")]
pub fn get_connector_payment_id(&self) -> Option<&str> {
self.connector_transaction_id.as_deref()
}
#[cfg(feature = "v2")]
pub fn get_connector_payment_id(&self) -> Option<&str> {
self.connector_payment_id.as_deref()
}
/// Construct the domain model from the ConfirmIntentRequest and PaymentIntent
#[cfg(feature = "v2")]
pub async fn create_domain_model(
payment_intent: &super::PaymentIntent,
cell_id: id_type::CellId,
storage_scheme: storage_enums::MerchantStorageScheme,
request: &api_models::payments::PaymentsConfirmIntentRequest,
encrypted_data: DecryptedPaymentAttempt,
) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> {
let id = id_type::GlobalAttemptId::generate(&cell_id);
let intent_amount_details = payment_intent.amount_details.clone();
let attempt_amount_details = intent_amount_details.create_attempt_amount_details(request);
let now = common_utils::date_time::now();
let payment_method_billing_address = encrypted_data
.payment_method_billing_address
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode billing address")?;
let connector_token = Some(diesel_models::ConnectorTokenDetails {
connector_mandate_id: None,
connector_token_request_reference_id: Some(common_utils::generate_id_with_len(
consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
)),
});
let authentication_type = payment_intent.authentication_type.unwrap_or_default();
Ok(Self {
payment_id: payment_intent.id.clone(),
merchant_id: payment_intent.merchant_id.clone(),
attempts_group_id: None,
amount_details: attempt_amount_details,
status: common_enums::AttemptStatus::Started,
// This will be decided by the routing algorithm and updated in update trackers
// right before calling the connector
connector: None,
authentication_type,
created_at: now,
modified_at: now,
last_synced: None,
cancellation_reason: None,
browser_info: request.browser_info.clone(),
payment_token: request.payment_token.clone(),
connector_metadata: None,
payment_experience: None,
payment_method_data: None,
routing_result: None,
preprocessing_step_id: None,
multiple_capture_count: None,
connector_response_reference_id: None,
updated_by: storage_scheme.to_string(),
redirection_data: None,
encoded_data: None,
merchant_connector_id: None,
external_three_ds_authentication_attempted: None,
authentication_connector: None,
authentication_id: None,
fingerprint_id: None,
charges: None,
client_source: None,
client_version: None,
customer_acceptance: request.customer_acceptance.clone().map(Secret::new),
profile_id: payment_intent.profile_id.clone(),
organization_id: payment_intent.organization_id.clone(),
payment_method_type: request.payment_method_type,
payment_method_id: request.payment_method_id.clone(),
connector_payment_id: None,
payment_method_subtype: request.payment_method_subtype,
authentication_applied: None,
external_reference_id: None,
payment_method_billing_address,
error: None,
connector_token_details: connector_token,
id,
card_discovery: None,
feature_metadata: None,
processor_merchant_id: payment_intent.merchant_id.clone(),
created_by: None,
connector_request_reference_id: None,
network_transaction_id: None,
authorized_amount: None,
})
}
#[cfg(feature = "v2")]
pub async fn proxy_create_domain_model(
payment_intent: &super::PaymentIntent,
cell_id: id_type::CellId,
storage_scheme: storage_enums::MerchantStorageScheme,
request: &api_models::payments::ProxyPaymentsRequest,
encrypted_data: DecryptedPaymentAttempt,
) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> {
let id = id_type::GlobalAttemptId::generate(&cell_id);
let intent_amount_details = payment_intent.amount_details.clone();
let attempt_amount_details =
intent_amount_details.proxy_create_attempt_amount_details(request);
let now = common_utils::date_time::now();
let payment_method_billing_address = encrypted_data
.payment_method_billing_address
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode billing address")?;
let connector_token = Some(diesel_models::ConnectorTokenDetails {
connector_mandate_id: None,
connector_token_request_reference_id: Some(common_utils::generate_id_with_len(
consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
)),
});
let payment_method_type_data = payment_intent.get_payment_method_type();
let payment_method_subtype_data = payment_intent.get_payment_method_sub_type();
let authentication_type = payment_intent.authentication_type.unwrap_or_default();
Ok(Self {
payment_id: payment_intent.id.clone(),
merchant_id: payment_intent.merchant_id.clone(),
attempts_group_id: None,
amount_details: attempt_amount_details,
status: common_enums::AttemptStatus::Started,
connector: Some(request.connector.clone()),
authentication_type,
created_at: now,
modified_at: now,
last_synced: None,
cancellation_reason: None,
browser_info: request.browser_info.clone(),
payment_token: None,
connector_metadata: None,
payment_experience: None,
payment_method_data: None,
routing_result: None,
preprocessing_step_id: None,
multiple_capture_count: None,
connector_response_reference_id: None,
updated_by: storage_scheme.to_string(),
redirection_data: None,
encoded_data: None,
merchant_connector_id: Some(request.merchant_connector_id.clone()),
external_three_ds_authentication_attempted: None,
authentication_connector: None,
authentication_id: None,
fingerprint_id: None,
charges: None,
client_source: None,
client_version: None,
customer_acceptance: None,
profile_id: payment_intent.profile_id.clone(),
organization_id: payment_intent.organization_id.clone(),
payment_method_type: payment_method_type_data
.unwrap_or(common_enums::PaymentMethod::Card),
payment_method_id: None,
connector_payment_id: None,
payment_method_subtype: payment_method_subtype_data
.unwrap_or(common_enums::PaymentMethodType::Credit),
authentication_applied: None,
external_reference_id: None,
payment_method_billing_address,
error: None,
connector_token_details: connector_token,
feature_metadata: None,
id,
card_discovery: None,
processor_merchant_id: payment_intent.merchant_id.clone(),
created_by: None,
connector_request_reference_id: None,
network_transaction_id: None,
authorized_amount: None,
})
}
#[cfg(feature = "v2")]
pub async fn external_vault_proxy_create_domain_model(
payment_intent: &super::PaymentIntent,
cell_id: id_type::CellId,
storage_scheme: storage_enums::MerchantStorageScheme,
request: &api_models::payments::ExternalVaultProxyPaymentsRequest,
encrypted_data: DecryptedPaymentAttempt,
) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> {
let id = id_type::GlobalAttemptId::generate(&cell_id);
let intent_amount_details = payment_intent.amount_details.clone();
let attempt_amount_details = AttemptAmountDetails {
net_amount: intent_amount_details.order_amount,
amount_to_capture: None,
surcharge_amount: None,
tax_on_surcharge: None,
amount_capturable: intent_amount_details.order_amount,
shipping_cost: None,
order_tax_amount: None,
};
let now = common_utils::date_time::now();
let payment_method_billing_address = encrypted_data
.payment_method_billing_address
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode billing address")?;
let connector_token = Some(diesel_models::ConnectorTokenDetails {
connector_mandate_id: None,
connector_token_request_reference_id: Some(common_utils::generate_id_with_len(
consts::CONNECTOR_MANDATE_REQUEST_REFERENCE_ID_LENGTH,
)),
});
let payment_method_type_data = payment_intent.get_payment_method_type();
let payment_method_subtype_data = payment_intent.get_payment_method_sub_type();
let authentication_type = payment_intent.authentication_type.unwrap_or_default();
Ok(Self {
payment_id: payment_intent.id.clone(),
merchant_id: payment_intent.merchant_id.clone(),
attempts_group_id: None,
amount_details: attempt_amount_details,
status: common_enums::AttemptStatus::Started,
connector: None,
authentication_type,
created_at: now,
modified_at: now,
last_synced: None,
cancellation_reason: None,
browser_info: request.browser_info.clone(),
payment_token: request.payment_token.clone(),
connector_metadata: None,
payment_experience: None,
payment_method_data: None,
routing_result: None,
preprocessing_step_id: None,
multiple_capture_count: None,
connector_response_reference_id: None,
updated_by: storage_scheme.to_string(),
redirection_data: None,
encoded_data: None,
merchant_connector_id: None,
external_three_ds_authentication_attempted: None,
authentication_connector: None,
authentication_id: None,
fingerprint_id: None,
charges: None,
client_source: None,
client_version: None,
customer_acceptance: request.customer_acceptance.clone().map(Secret::new),
profile_id: payment_intent.profile_id.clone(),
organization_id: payment_intent.organization_id.clone(),
payment_method_type: payment_method_type_data
.unwrap_or(common_enums::PaymentMethod::Card),
payment_method_id: request.payment_method_id.clone(),
connector_payment_id: None,
payment_method_subtype: payment_method_subtype_data
.unwrap_or(common_enums::PaymentMethodType::Credit),
authentication_applied: None,
external_reference_id: None,
payment_method_billing_address,
error: None,
connector_token_details: connector_token,
feature_metadata: None,
id,
card_discovery: None,
processor_merchant_id: payment_intent.merchant_id.clone(),
created_by: None,
connector_request_reference_id: None,
network_transaction_id: None,
authorized_amount: None,
})
}
/// Construct the domain model from the ConfirmIntentRequest and PaymentIntent
#[cfg(feature = "v2")]
pub async fn create_domain_model_using_record_request(
payment_intent: &super::PaymentIntent,
cell_id: id_type::CellId,
storage_scheme: storage_enums::MerchantStorageScheme,
request: &api_models::payments::PaymentsAttemptRecordRequest,
encrypted_data: DecryptedPaymentAttempt,
) -> CustomResult<Self, errors::api_error_response::ApiErrorResponse> {
let id = id_type::GlobalAttemptId::generate(&cell_id);
let amount_details = AttemptAmountDetailsSetter::from(&request.amount_details);
let now = common_utils::date_time::now();
// we consume transaction_created_at from webhook request, if it is not present we take store current time as transaction_created_at.
let transaction_created_at = request
.transaction_created_at
.unwrap_or(common_utils::date_time::now());
// This function is called in the record attempt flow, which tells us that this is a payment attempt created by an external system.
let feature_metadata = PaymentAttemptFeatureMetadata {
revenue_recovery: Some({
PaymentAttemptRevenueRecoveryData {
attempt_triggered_by: request.triggered_by,
charge_id: request.feature_metadata.as_ref().and_then(|metadata| {
metadata
.revenue_recovery
.as_ref()
.and_then(|data| data.charge_id.clone())
}),
}
}),
};
let payment_method_data = request
.payment_method_data
.as_ref()
.map(|data| data.payment_method_data.clone().encode_to_value())
.transpose()
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode additional payment method data")?
.map(pii::SecretSerdeValue::new);
let payment_method_billing_address = encrypted_data
.payment_method_billing_address
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode billing address")?;
let error = request.error.as_ref().map(ErrorDetails::from);
let connector_payment_id = request
.connector_transaction_id
.as_ref()
.map(|txn_id| txn_id.get_id().clone());
let connector = request.connector.map(|connector| connector.to_string());
let connector_request_reference_id = payment_intent
.merchant_reference_id
.as_ref()
.map(|id| id.get_string_repr().to_owned());
Ok(Self {
payment_id: payment_intent.id.clone(),
merchant_id: payment_intent.merchant_id.clone(),
attempts_group_id: None,
amount_details: AttemptAmountDetails::from(amount_details),
status: request.status,
connector,
authentication_type: storage_enums::AuthenticationType::NoThreeDs,
created_at: transaction_created_at,
modified_at: now,
last_synced: None,
cancellation_reason: None,
browser_info: None,
payment_token: None,
connector_metadata: None,
payment_experience: None,
payment_method_data,
routing_result: None,
preprocessing_step_id: None,
multiple_capture_count: None,
connector_response_reference_id: None,
updated_by: storage_scheme.to_string(),
redirection_data: None,
encoded_data: None,
merchant_connector_id: request.payment_merchant_connector_id.clone(),
external_three_ds_authentication_attempted: None,
authentication_connector: None,
authentication_id: None,
fingerprint_id: None,
client_source: None,
client_version: None,
customer_acceptance: None,
profile_id: payment_intent.profile_id.clone(),
organization_id: payment_intent.organization_id.clone(),
payment_method_type: request.payment_method_type,
payment_method_id: None,
connector_payment_id,
payment_method_subtype: request.payment_method_subtype,
authentication_applied: None,
external_reference_id: None,
payment_method_billing_address,
error,
feature_metadata: Some(feature_metadata),
id,
connector_token_details: Some(diesel_models::ConnectorTokenDetails {
connector_mandate_id: Some(request.processor_payment_method_token.clone()),
connector_token_request_reference_id: None,
}),
card_discovery: None,
charges: None,
processor_merchant_id: payment_intent.merchant_id.clone(),
created_by: None,
connector_request_reference_id,
network_transaction_id: None,
authorized_amount: None,
})
}
pub fn get_attempt_merchant_connector_account_id(
&self,
) -> CustomResult<
id_type::MerchantConnectorAccountId,
errors::api_error_response::ApiErrorResponse,
> {
let merchant_connector_id = self
.merchant_connector_id
.clone()
.get_required_value("merchant_connector_id")
.change_context(errors::api_error_response::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant connector id is None")?;
Ok(merchant_connector_id)
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PaymentAttempt {
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
pub net_amount: NetAmount,
pub currency: Option<storage_enums::Currency>,
pub save_to_locker: Option<bool>,
pub connector: Option<String>,
pub error_message: Option<String>,
pub offer_amount: Option<MinorUnit>,
pub payment_method_id: Option<String>,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub connector_transaction_id: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub capture_on: Option<PrimitiveDateTime>,
pub confirm: bool,
pub authentication_type: Option<storage_enums::AuthenticationType>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub cancellation_reason: Option<String>,
pub amount_to_capture: Option<MinorUnit>,
pub mandate_id: Option<String>,
pub browser_info: Option<serde_json::Value>,
pub error_code: Option<String>,
pub payment_token: Option<String>,
pub connector_metadata: Option<serde_json::Value>,
pub payment_experience: Option<storage_enums::PaymentExperience>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_data: Option<serde_json::Value>,
pub business_sub_label: Option<String>,
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
// providing a location to store mandate details intermediately for transaction
pub mandate_details: Option<MandateDataType>,
pub error_reason: Option<String>,
pub multiple_capture_count: Option<i16>,
// reference to the payment at connector side
pub connector_response_reference_id: Option<String>,
pub amount_capturable: MinorUnit,
pub updated_by: String,
pub authentication_data: Option<serde_json::Value>,
pub encoded_data: Option<String>,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub external_three_ds_authentication_attempted: Option<bool>,
pub authentication_connector: Option<String>,
pub authentication_id: Option<id_type::AuthenticationId>,
pub mandate_data: Option<MandateDetails>,
pub payment_method_billing_address_id: Option<String>,
pub fingerprint_id: Option<String>,
pub charge_id: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub profile_id: id_type::ProfileId,
pub organization_id: id_type::OrganizationId,
pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>,
pub capture_before: Option<PrimitiveDateTime>,
pub card_discovery: Option<common_enums::CardDiscovery>,
pub charges: Option<common_types::payments::ConnectorChargeResponseData>,
pub issuer_error_code: Option<String>,
pub issuer_error_message: Option<String>,
/// merchant who owns the credentials of the processor, i.e. processor owner
pub processor_merchant_id: id_type::MerchantId,
/// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard))
pub created_by: Option<CreatedBy>,
pub setup_future_usage_applied: Option<storage_enums::FutureUsage>,
pub routing_approach: Option<storage_enums::RoutingApproach>,
pub connector_request_reference_id: Option<String>,
pub debit_routing_savings: Option<MinorUnit>,
pub network_transaction_id: Option<String>,
pub is_overcapture_enabled: Option<OvercaptureEnabledBool>,
pub network_details: Option<NetworkDetails>,
pub is_stored_credential: Option<bool>,
/// stores the authorized amount in case of partial authorization
pub authorized_amount: Option<MinorUnit>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize, Default)]
pub struct NetAmount {
/// The payment amount
order_amount: MinorUnit,
/// The shipping cost of the order
shipping_cost: Option<MinorUnit>,
/// Tax amount related to the order
order_tax_amount: Option<MinorUnit>,
/// The surcharge amount to be added to the order
surcharge_amount: Option<MinorUnit>,
/// tax on surcharge amount
tax_on_surcharge: Option<MinorUnit>,
}
#[cfg(feature = "v1")]
impl NetAmount {
pub fn new(
order_amount: MinorUnit,
shipping_cost: Option<MinorUnit>,
order_tax_amount: Option<MinorUnit>,
surcharge_amount: Option<MinorUnit>,
tax_on_surcharge: Option<MinorUnit>,
) -> Self {
Self {
order_amount,
shipping_cost,
order_tax_amount,
surcharge_amount,
tax_on_surcharge,
}
}
pub fn get_order_amount(&self) -> MinorUnit {
self.order_amount
}
pub fn get_shipping_cost(&self) -> Option<MinorUnit> {
self.shipping_cost
}
pub fn get_order_tax_amount(&self) -> Option<MinorUnit> {
self.order_tax_amount
}
pub fn get_surcharge_amount(&self) -> Option<MinorUnit> {
self.surcharge_amount
}
pub fn get_tax_on_surcharge(&self) -> Option<MinorUnit> {
self.tax_on_surcharge
}
pub fn get_total_surcharge_amount(&self) -> Option<MinorUnit> {
self.surcharge_amount
.map(|surcharge_amount| surcharge_amount + self.tax_on_surcharge.unwrap_or_default())
}
pub fn get_total_amount(&self) -> MinorUnit {
self.order_amount
+ self.shipping_cost.unwrap_or_default()
+ self.order_tax_amount.unwrap_or_default()
+ self.surcharge_amount.unwrap_or_default()
+ self.tax_on_surcharge.unwrap_or_default()
}
pub fn get_additional_amount(&self) -> MinorUnit {
self.get_total_amount() - self.get_order_amount()
}
pub fn set_order_amount(&mut self, order_amount: MinorUnit) {
self.order_amount = order_amount;
}
pub fn set_order_tax_amount(&mut self, order_tax_amount: Option<MinorUnit>) {
self.order_tax_amount = order_tax_amount;
}
pub fn set_surcharge_details(
&mut self,
surcharge_details: Option<router_request_types::SurchargeDetails>,
) {
self.surcharge_amount = surcharge_details
.clone()
.map(|details| details.surcharge_amount);
self.tax_on_surcharge = surcharge_details.map(|details| details.tax_on_surcharge_amount);
}
pub fn from_payments_request(
payments_request: &api_models::payments::PaymentsRequest,
order_amount: MinorUnit,
) -> Self {
let surcharge_amount = payments_request
.surcharge_details
.map(|surcharge_details| surcharge_details.surcharge_amount);
let tax_on_surcharge = payments_request
.surcharge_details
.and_then(|surcharge_details| surcharge_details.tax_amount);
Self {
order_amount,
shipping_cost: payments_request.shipping_cost,
order_tax_amount: payments_request.order_tax_amount,
surcharge_amount,
tax_on_surcharge,
}
}
#[cfg(feature = "v1")]
pub fn from_payments_request_and_payment_attempt(
payments_request: &api_models::payments::PaymentsRequest,
payment_attempt: Option<&PaymentAttempt>,
) -> Option<Self> {
let option_order_amount = payments_request
.amount
.map(MinorUnit::from)
.or(payment_attempt
.map(|payment_attempt| payment_attempt.net_amount.get_order_amount()));
option_order_amount.map(|order_amount| {
let shipping_cost = payments_request.shipping_cost.or(payment_attempt
.and_then(|payment_attempt| payment_attempt.net_amount.get_shipping_cost()));
let order_tax_amount = payment_attempt
.and_then(|payment_attempt| payment_attempt.net_amount.get_order_tax_amount());
let surcharge_amount = payments_request
.surcharge_details
.map(|surcharge_details| surcharge_details.get_surcharge_amount())
.or_else(|| {
payment_attempt.and_then(|payment_attempt| {
payment_attempt.net_amount.get_surcharge_amount()
})
});
let tax_on_surcharge = payments_request
.surcharge_details
.and_then(|surcharge_details| surcharge_details.get_tax_amount())
.or_else(|| {
payment_attempt.and_then(|payment_attempt| {
payment_attempt.net_amount.get_tax_on_surcharge()
})
});
Self {
order_amount,
shipping_cost,
order_tax_amount,
surcharge_amount,
tax_on_surcharge,
}
})
}
}
#[cfg(feature = "v2")]
impl PaymentAttempt {
#[track_caller]
pub fn get_total_amount(&self) -> MinorUnit {
self.amount_details.get_net_amount()
}
pub fn get_total_surcharge_amount(&self) -> Option<MinorUnit> {
self.amount_details.surcharge_amount
}
pub fn extract_card_network(&self) -> Option<common_enums::CardNetwork> {
todo!()
}
}
#[cfg(feature = "v1")]
impl PaymentAttempt {
pub fn get_total_amount(&self) -> MinorUnit {
self.net_amount.get_total_amount()
}
pub fn get_total_surcharge_amount(&self) -> Option<MinorUnit> {
self.net_amount.get_total_surcharge_amount()
}
pub fn set_debit_routing_savings(&mut self, debit_routing_savings: Option<&MinorUnit>) {
self.debit_routing_savings = debit_routing_savings.copied();
}
pub fn extract_card_network(&self) -> Option<common_enums::CardNetwork> {
self.payment_method_data
.as_ref()
.and_then(|value| {
value
.clone()
.parse_value::<api_models::payments::AdditionalPaymentData>(
"AdditionalPaymentData",
)
.ok()
})
.and_then(|data| data.get_additional_card_info())
.and_then(|card_info| card_info.card_network)
}
pub fn get_payment_method_data(&self) -> Option<api_models::payments::AdditionalPaymentData> {
self.payment_method_data
.clone()
.and_then(|data| match data {
serde_json::Value::Null => None,
_ => Some(data.parse_value("AdditionalPaymentData")),
})
.transpose()
.map_err(|err| logger::error!("Failed to parse AdditionalPaymentData {err:?}"))
.ok()
.flatten()
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PaymentListFilters {
pub connector: Vec<String>,
pub currency: Vec<storage_enums::Currency>,
pub status: Vec<storage_enums::IntentStatus>,
pub payment_method: Vec<storage_enums::PaymentMethod>,
pub payment_method_type: Vec<storage_enums::PaymentMethodType>,
pub authentication_type: Vec<storage_enums::AuthenticationType>,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct PaymentAttemptNew {
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
pub attempt_id: String,
pub status: storage_enums::AttemptStatus,
/// amount + surcharge_amount + tax_amount
/// This field will always be derived before updating in the Database
pub net_amount: NetAmount,
pub currency: Option<storage_enums::Currency>,
// pub auto_capture: Option<bool>,
pub save_to_locker: Option<bool>,
pub connector: Option<String>,
pub error_message: Option<String>,
pub offer_amount: Option<MinorUnit>,
pub payment_method_id: Option<String>,
pub payment_method: Option<storage_enums::PaymentMethod>,
pub capture_method: Option<storage_enums::CaptureMethod>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub capture_on: Option<PrimitiveDateTime>,
pub confirm: bool,
pub authentication_type: Option<storage_enums::AuthenticationType>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub created_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub modified_at: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub last_synced: Option<PrimitiveDateTime>,
pub cancellation_reason: Option<String>,
pub amount_to_capture: Option<MinorUnit>,
pub mandate_id: Option<String>,
pub browser_info: Option<serde_json::Value>,
pub payment_token: Option<String>,
pub error_code: Option<String>,
pub connector_metadata: Option<serde_json::Value>,
pub payment_experience: Option<storage_enums::PaymentExperience>,
pub payment_method_type: Option<storage_enums::PaymentMethodType>,
pub payment_method_data: Option<serde_json::Value>,
pub business_sub_label: Option<String>,
pub straight_through_algorithm: Option<serde_json::Value>,
pub preprocessing_step_id: Option<String>,
pub mandate_details: Option<MandateDataType>,
pub error_reason: Option<String>,
pub connector_response_reference_id: Option<String>,
pub multiple_capture_count: Option<i16>,
pub amount_capturable: MinorUnit,
pub updated_by: String,
pub authentication_data: Option<serde_json::Value>,
pub encoded_data: Option<String>,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub external_three_ds_authentication_attempted: Option<bool>,
pub authentication_connector: Option<String>,
pub authentication_id: Option<id_type::AuthenticationId>,
pub mandate_data: Option<MandateDetails>,
pub payment_method_billing_address_id: Option<String>,
pub fingerprint_id: Option<String>,
pub client_source: Option<String>,
pub client_version: Option<String>,
pub customer_acceptance: Option<pii::SecretSerdeValue>,
pub profile_id: id_type::ProfileId,
pub organization_id: id_type::OrganizationId,
pub connector_mandate_detail: Option<ConnectorMandateReferenceId>,
pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>,
pub capture_before: Option<PrimitiveDateTime>,
pub card_discovery: Option<common_enums::CardDiscovery>,
/// merchant who owns the credentials of the processor, i.e. processor owner
pub processor_merchant_id: id_type::MerchantId,
/// merchantwho invoked the resource based api (identifier) and through what source (Api, Jwt(Dashboard))
pub created_by: Option<CreatedBy>,
pub setup_future_usage_applied: Option<storage_enums::FutureUsage>,
pub routing_approach: Option<storage_enums::RoutingApproach>,
pub connector_request_reference_id: Option<String>,
pub network_transaction_id: Option<String>,
pub network_details: Option<NetworkDetails>,
pub is_stored_credential: Option<bool>,
pub authorized_amount: Option<MinorUnit>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Serialize, Deserialize)]
pub enum PaymentAttemptUpdate {
Update {
net_amount: NetAmount,
currency: storage_enums::Currency,
status: storage_enums::AttemptStatus,
authentication_type: Option<storage_enums::AuthenticationType>,
payment_method: Option<storage_enums::PaymentMethod>,
payment_token: Option<String>,
payment_method_data: Option<serde_json::Value>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
payment_experience: Option<storage_enums::PaymentExperience>,
business_sub_label: Option<String>,
amount_to_capture: Option<MinorUnit>,
capture_method: Option<storage_enums::CaptureMethod>,
fingerprint_id: Option<String>,
payment_method_billing_address_id: Option<String>,
updated_by: String,
network_transaction_id: Option<String>,
},
UpdateTrackers {
payment_token: Option<String>,
connector: Option<String>,
straight_through_algorithm: Option<serde_json::Value>,
amount_capturable: Option<MinorUnit>,
surcharge_amount: Option<MinorUnit>,
tax_amount: Option<MinorUnit>,
updated_by: String,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
routing_approach: Option<storage_enums::RoutingApproach>,
is_stored_credential: Option<bool>,
},
AuthenticationTypeUpdate {
authentication_type: storage_enums::AuthenticationType,
updated_by: String,
},
ConfirmUpdate {
net_amount: NetAmount,
currency: storage_enums::Currency,
status: storage_enums::AttemptStatus,
authentication_type: Option<storage_enums::AuthenticationType>,
capture_method: Option<storage_enums::CaptureMethod>,
payment_method: Option<storage_enums::PaymentMethod>,
browser_info: Option<serde_json::Value>,
connector: Option<String>,
payment_token: Option<String>,
payment_method_data: Option<serde_json::Value>,
payment_method_type: Option<storage_enums::PaymentMethodType>,
payment_experience: Option<storage_enums::PaymentExperience>,
business_sub_label: Option<String>,
straight_through_algorithm: Option<serde_json::Value>,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
updated_by: String,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
external_three_ds_authentication_attempted: Option<bool>,
authentication_connector: Option<String>,
authentication_id: Option<id_type::AuthenticationId>,
payment_method_billing_address_id: Option<String>,
fingerprint_id: Option<String>,
payment_method_id: Option<String>,
client_source: Option<String>,
client_version: Option<String>,
customer_acceptance: Option<pii::SecretSerdeValue>,
connector_mandate_detail: Option<ConnectorMandateReferenceId>,
card_discovery: Option<common_enums::CardDiscovery>,
routing_approach: Option<storage_enums::RoutingApproach>,
connector_request_reference_id: Option<String>,
network_transaction_id: Option<String>,
is_stored_credential: Option<bool>,
request_extended_authorization: Option<RequestExtendedAuthorizationBool>,
},
RejectUpdate {
status: storage_enums::AttemptStatus,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
updated_by: String,
},
BlocklistUpdate {
status: storage_enums::AttemptStatus,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
updated_by: String,
},
PaymentMethodDetailsUpdate {
payment_method_id: Option<String>,
updated_by: String,
},
ConnectorMandateDetailUpdate {
connector_mandate_detail: Option<ConnectorMandateReferenceId>,
updated_by: String,
},
VoidUpdate {
status: storage_enums::AttemptStatus,
cancellation_reason: Option<String>,
updated_by: String,
},
ResponseUpdate {
status: storage_enums::AttemptStatus,
connector: Option<String>,
connector_transaction_id: Option<String>,
network_transaction_id: Option<String>,
authentication_type: Option<storage_enums::AuthenticationType>,
payment_method_id: Option<String>,
mandate_id: Option<String>,
connector_metadata: Option<serde_json::Value>,
payment_token: Option<String>,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
error_reason: Option<Option<String>>,
connector_response_reference_id: Option<String>,
amount_capturable: Option<MinorUnit>,
updated_by: String,
authentication_data: Option<serde_json::Value>,
encoded_data: Option<String>,
unified_code: Option<Option<String>>,
unified_message: Option<Option<String>>,
capture_before: Option<PrimitiveDateTime>,
extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>,
payment_method_data: Option<serde_json::Value>,
connector_mandate_detail: Option<ConnectorMandateReferenceId>,
charges: Option<common_types::payments::ConnectorChargeResponseData>,
setup_future_usage_applied: Option<storage_enums::FutureUsage>,
debit_routing_savings: Option<MinorUnit>,
is_overcapture_enabled: Option<OvercaptureEnabledBool>,
authorized_amount: Option<MinorUnit>,
},
UnresolvedResponseUpdate {
status: storage_enums::AttemptStatus,
connector: Option<String>,
connector_transaction_id: Option<String>,
payment_method_id: Option<String>,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
error_reason: Option<Option<String>>,
connector_response_reference_id: Option<String>,
updated_by: String,
},
StatusUpdate {
status: storage_enums::AttemptStatus,
updated_by: String,
},
ErrorUpdate {
connector: Option<String>,
status: storage_enums::AttemptStatus,
error_code: Option<Option<String>>,
error_message: Option<Option<String>>,
error_reason: Option<Option<String>>,
amount_capturable: Option<MinorUnit>,
updated_by: String,
unified_code: Option<Option<String>>,
unified_message: Option<Option<String>>,
connector_transaction_id: Option<String>,
payment_method_data: Option<serde_json::Value>,
authentication_type: Option<storage_enums::AuthenticationType>,
issuer_error_code: Option<String>,
issuer_error_message: Option<String>,
network_details: Option<NetworkDetails>,
},
CaptureUpdate {
amount_to_capture: Option<MinorUnit>,
multiple_capture_count: Option<i16>,
updated_by: String,
},
AmountToCaptureUpdate {
status: storage_enums::AttemptStatus,
amount_capturable: MinorUnit,
updated_by: String,
},
PreprocessingUpdate {
status: storage_enums::AttemptStatus,
payment_method_id: Option<String>,
connector_metadata: Option<serde_json::Value>,
preprocessing_step_id: Option<String>,
connector_transaction_id: Option<String>,
connector_response_reference_id: Option<String>,
updated_by: String,
},
ConnectorResponse {
authentication_data: Option<serde_json::Value>,
encoded_data: Option<String>,
connector_transaction_id: Option<String>,
connector: Option<String>,
charges: Option<common_types::payments::ConnectorChargeResponseData>,
updated_by: String,
},
IncrementalAuthorizationAmountUpdate {
net_amount: NetAmount,
amount_capturable: MinorUnit,
},
AuthenticationUpdate {
status: storage_enums::AttemptStatus,
external_three_ds_authentication_attempted: Option<bool>,
authentication_connector: Option<String>,
authentication_id: Option<id_type::AuthenticationId>,
updated_by: String,
},
ManualUpdate {
status: Option<storage_enums::AttemptStatus>,
error_code: Option<String>,
error_message: Option<String>,
error_reason: Option<String>,
updated_by: String,
unified_code: Option<String>,
unified_message: Option<String>,
connector_transaction_id: Option<String>,
},
PostSessionTokensUpdate {
updated_by: String,
connector_metadata: Option<serde_json::Value>,
},
}
#[cfg(feature = "v1")]
impl PaymentAttemptUpdate {
pub fn to_storage_model(self) -> diesel_models::PaymentAttemptUpdate {
match self {
Self::Update {
net_amount,
currency,
status,
authentication_type,
payment_method,
payment_token,
payment_method_data,
payment_method_type,
payment_experience,
business_sub_label,
amount_to_capture,
capture_method,
fingerprint_id,
network_transaction_id,
payment_method_billing_address_id,
updated_by,
} => DieselPaymentAttemptUpdate::Update {
amount: net_amount.get_order_amount(),
currency,
status,
authentication_type,
payment_method,
payment_token,
payment_method_data,
payment_method_type,
payment_experience,
business_sub_label,
amount_to_capture,
capture_method,
surcharge_amount: net_amount.get_surcharge_amount(),
tax_amount: net_amount.get_tax_on_surcharge(),
fingerprint_id,
payment_method_billing_address_id,
network_transaction_id,
updated_by,
},
Self::UpdateTrackers {
payment_token,
connector,
straight_through_algorithm,
amount_capturable,
updated_by,
surcharge_amount,
tax_amount,
merchant_connector_id,
routing_approach,
is_stored_credential,
} => DieselPaymentAttemptUpdate::UpdateTrackers {
payment_token,
connector,
straight_through_algorithm,
amount_capturable,
surcharge_amount,
tax_amount,
updated_by,
merchant_connector_id,
routing_approach: routing_approach.map(|approach| match approach {
storage_enums::RoutingApproach::Other(_) => {
// we need to make sure Other variant is not stored in DB, in the rare case
// where we attempt to store an unknown value, we default to the default value
storage_enums::RoutingApproach::default()
}
_ => approach,
}),
is_stored_credential,
},
Self::AuthenticationTypeUpdate {
authentication_type,
updated_by,
} => DieselPaymentAttemptUpdate::AuthenticationTypeUpdate {
authentication_type,
updated_by,
},
Self::BlocklistUpdate {
status,
error_code,
error_message,
updated_by,
} => DieselPaymentAttemptUpdate::BlocklistUpdate {
status,
error_code,
error_message,
updated_by,
},
Self::ConnectorMandateDetailUpdate {
connector_mandate_detail,
updated_by,
} => DieselPaymentAttemptUpdate::ConnectorMandateDetailUpdate {
connector_mandate_detail,
updated_by,
},
Self::PaymentMethodDetailsUpdate {
payment_method_id,
updated_by,
} => DieselPaymentAttemptUpdate::PaymentMethodDetailsUpdate {
payment_method_id,
updated_by,
},
Self::ConfirmUpdate {
net_amount,
currency,
status,
authentication_type,
capture_method,
payment_method,
browser_info,
connector,
payment_token,
payment_method_data,
payment_method_type,
payment_experience,
business_sub_label,
straight_through_algorithm,
error_code,
error_message,
fingerprint_id,
updated_by,
merchant_connector_id: connector_id,
payment_method_id,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
payment_method_billing_address_id,
client_source,
client_version,
customer_acceptance,
connector_mandate_detail,
card_discovery,
routing_approach,
connector_request_reference_id,
network_transaction_id,
is_stored_credential,
request_extended_authorization,
} => DieselPaymentAttemptUpdate::ConfirmUpdate {
amount: net_amount.get_order_amount(),
currency,
status,
authentication_type,
capture_method,
payment_method,
browser_info,
connector,
payment_token,
payment_method_data,
payment_method_type,
payment_experience,
business_sub_label,
straight_through_algorithm,
error_code,
error_message,
surcharge_amount: net_amount.get_surcharge_amount(),
tax_amount: net_amount.get_tax_on_surcharge(),
fingerprint_id,
updated_by,
merchant_connector_id: connector_id,
payment_method_id,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
payment_method_billing_address_id,
client_source,
client_version,
customer_acceptance,
shipping_cost: net_amount.get_shipping_cost(),
order_tax_amount: net_amount.get_order_tax_amount(),
connector_mandate_detail,
card_discovery,
routing_approach: routing_approach.map(|approach| match approach {
// we need to make sure Other variant is not stored in DB, in the rare case
// where we attempt to store an unknown value, we default to the default value
storage_enums::RoutingApproach::Other(_) => {
storage_enums::RoutingApproach::default()
}
_ => approach,
}),
connector_request_reference_id,
network_transaction_id,
is_stored_credential,
request_extended_authorization,
},
Self::VoidUpdate {
status,
cancellation_reason,
updated_by,
} => DieselPaymentAttemptUpdate::VoidUpdate {
status,
cancellation_reason,
updated_by,
},
Self::ResponseUpdate {
status,
connector,
connector_transaction_id,
authentication_type,
payment_method_id,
mandate_id,
connector_metadata,
payment_token,
error_code,
error_message,
error_reason,
connector_response_reference_id,
amount_capturable,
updated_by,
authentication_data,
encoded_data,
unified_code,
unified_message,
capture_before,
extended_authorization_applied,
payment_method_data,
connector_mandate_detail,
charges,
setup_future_usage_applied,
network_transaction_id,
debit_routing_savings: _,
is_overcapture_enabled,
authorized_amount,
} => DieselPaymentAttemptUpdate::ResponseUpdate {
status,
connector,
connector_transaction_id,
authentication_type,
payment_method_id,
mandate_id,
connector_metadata,
payment_token,
error_code,
error_message,
error_reason,
connector_response_reference_id,
amount_capturable,
updated_by,
authentication_data,
encoded_data,
unified_code,
unified_message,
capture_before,
extended_authorization_applied,
payment_method_data,
connector_mandate_detail,
charges,
setup_future_usage_applied,
network_transaction_id,
is_overcapture_enabled,
authorized_amount,
},
Self::UnresolvedResponseUpdate {
status,
connector,
connector_transaction_id,
payment_method_id,
error_code,
error_message,
error_reason,
connector_response_reference_id,
updated_by,
} => DieselPaymentAttemptUpdate::UnresolvedResponseUpdate {
status,
connector,
connector_transaction_id,
payment_method_id,
error_code,
error_message,
error_reason,
connector_response_reference_id,
updated_by,
},
Self::StatusUpdate { status, updated_by } => {
DieselPaymentAttemptUpdate::StatusUpdate { status, updated_by }
}
Self::ErrorUpdate {
connector,
status,
error_code,
error_message,
error_reason,
amount_capturable,
updated_by,
unified_code,
unified_message,
connector_transaction_id,
payment_method_data,
authentication_type,
issuer_error_code,
issuer_error_message,
network_details,
} => DieselPaymentAttemptUpdate::ErrorUpdate {
connector,
status,
error_code,
error_message,
error_reason,
amount_capturable,
updated_by,
unified_code,
unified_message,
connector_transaction_id,
payment_method_data,
authentication_type,
issuer_error_code,
issuer_error_message,
network_details,
},
Self::CaptureUpdate {
multiple_capture_count,
updated_by,
amount_to_capture,
} => DieselPaymentAttemptUpdate::CaptureUpdate {
multiple_capture_count,
updated_by,
amount_to_capture,
},
Self::PreprocessingUpdate {
status,
payment_method_id,
connector_metadata,
preprocessing_step_id,
connector_transaction_id,
connector_response_reference_id,
updated_by,
} => DieselPaymentAttemptUpdate::PreprocessingUpdate {
status,
payment_method_id,
connector_metadata,
preprocessing_step_id,
connector_transaction_id,
connector_response_reference_id,
updated_by,
},
Self::RejectUpdate {
status,
error_code,
error_message,
updated_by,
} => DieselPaymentAttemptUpdate::RejectUpdate {
status,
error_code,
error_message,
updated_by,
},
Self::AmountToCaptureUpdate {
status,
amount_capturable,
updated_by,
} => DieselPaymentAttemptUpdate::AmountToCaptureUpdate {
status,
amount_capturable,
updated_by,
},
Self::ConnectorResponse {
authentication_data,
encoded_data,
connector_transaction_id,
connector,
charges,
updated_by,
} => DieselPaymentAttemptUpdate::ConnectorResponse {
authentication_data,
encoded_data,
connector_transaction_id,
charges,
connector,
updated_by,
},
Self::IncrementalAuthorizationAmountUpdate {
net_amount,
amount_capturable,
} => DieselPaymentAttemptUpdate::IncrementalAuthorizationAmountUpdate {
amount: net_amount.get_order_amount(),
amount_capturable,
},
Self::AuthenticationUpdate {
status,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
updated_by,
} => DieselPaymentAttemptUpdate::AuthenticationUpdate {
status,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
updated_by,
},
Self::ManualUpdate {
status,
error_code,
error_message,
error_reason,
updated_by,
unified_code,
unified_message,
connector_transaction_id,
} => DieselPaymentAttemptUpdate::ManualUpdate {
status,
error_code,
error_message,
error_reason,
updated_by,
unified_code,
unified_message,
connector_transaction_id,
},
Self::PostSessionTokensUpdate {
updated_by,
connector_metadata,
} => DieselPaymentAttemptUpdate::PostSessionTokensUpdate {
updated_by,
connector_metadata,
},
}
}
pub fn get_debit_routing_savings(&self) -> Option<&MinorUnit> {
match self {
Self::ResponseUpdate {
debit_routing_savings,
..
} => debit_routing_savings.as_ref(),
Self::Update { .. }
| Self::UpdateTrackers { .. }
| Self::AuthenticationTypeUpdate { .. }
| Self::ConfirmUpdate { .. }
| Self::RejectUpdate { .. }
| Self::BlocklistUpdate { .. }
| Self::PaymentMethodDetailsUpdate { .. }
| Self::ConnectorMandateDetailUpdate { .. }
| Self::VoidUpdate { .. }
| Self::UnresolvedResponseUpdate { .. }
| Self::StatusUpdate { .. }
| Self::ErrorUpdate { .. }
| Self::CaptureUpdate { .. }
| Self::AmountToCaptureUpdate { .. }
| Self::PreprocessingUpdate { .. }
| Self::ConnectorResponse { .. }
| Self::IncrementalAuthorizationAmountUpdate { .. }
| Self::AuthenticationUpdate { .. }
| Self::ManualUpdate { .. }
| Self::PostSessionTokensUpdate { .. } => None,
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Serialize)]
pub struct ConfirmIntentResponseUpdate {
pub status: storage_enums::AttemptStatus,
pub connector_payment_id: Option<String>,
pub updated_by: String,
pub redirection_data: Option<router_response_types::RedirectForm>,
pub connector_metadata: Option<pii::SecretSerdeValue>,
pub amount_capturable: Option<MinorUnit>,
pub connector_token_details: Option<diesel_models::ConnectorTokenDetails>,
pub connector_response_reference_id: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Serialize)]
pub enum PaymentAttemptUpdate {
/// Update the payment attempt on confirming the intent, before calling the connector
ConfirmIntent {
status: storage_enums::AttemptStatus,
updated_by: String,
connector: String,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
authentication_type: storage_enums::AuthenticationType,
connector_request_reference_id: Option<String>,
connector_response_reference_id: Option<String>,
},
/// Update the payment attempt on confirming the intent, before calling the connector, when payment_method_id is present
ConfirmIntentTokenized {
status: storage_enums::AttemptStatus,
updated_by: String,
connector: String,
merchant_connector_id: id_type::MerchantConnectorAccountId,
authentication_type: storage_enums::AuthenticationType,
payment_method_id: id_type::GlobalPaymentMethodId,
connector_request_reference_id: Option<String>,
},
/// Update the payment attempt on confirming the intent, after calling the connector on success response
ConfirmIntentResponse(Box<ConfirmIntentResponseUpdate>),
/// Update the payment attempt after force syncing with the connector
SyncUpdate {
status: storage_enums::AttemptStatus,
amount_capturable: Option<MinorUnit>,
updated_by: String,
},
PreCaptureUpdate {
amount_to_capture: Option<MinorUnit>,
updated_by: String,
},
/// Update the payment after attempting capture with the connector
CaptureUpdate {
status: storage_enums::AttemptStatus,
amount_capturable: Option<MinorUnit>,
updated_by: String,
},
/// Update the payment attempt on confirming the intent, after calling the connector on error response
ErrorUpdate {
status: storage_enums::AttemptStatus,
amount_capturable: Option<MinorUnit>,
error: ErrorDetails,
updated_by: String,
connector_payment_id: Option<String>,
},
VoidUpdate {
status: storage_enums::AttemptStatus,
cancellation_reason: Option<String>,
updated_by: String,
},
}
#[cfg(feature = "v2")]
impl ForeignIDRef for PaymentAttempt {
fn foreign_id(&self) -> String {
todo!()
}
}
#[cfg(feature = "v1")]
impl ForeignIDRef for PaymentAttempt {
fn foreign_id(&self) -> String {
self.attempt_id.clone()
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl behaviour::Conversion for PaymentAttempt {
type DstType = DieselPaymentAttempt;
type NewDstType = DieselPaymentAttemptNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let card_network = self
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|card| card.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string());
let (connector_transaction_id, processor_transaction_data) = self
.connector_transaction_id
.map(ConnectorTransactionId::form_id_and_data)
.map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
.unwrap_or((None, None));
Ok(DieselPaymentAttempt {
payment_id: self.payment_id,
merchant_id: self.merchant_id,
attempt_id: self.attempt_id,
status: self.status,
amount: self.net_amount.get_order_amount(),
currency: self.currency,
save_to_locker: self.save_to_locker,
connector: self.connector,
error_message: self.error_message,
offer_amount: self.offer_amount,
surcharge_amount: self.net_amount.get_surcharge_amount(),
tax_amount: self.net_amount.get_tax_on_surcharge(),
payment_method_id: self.payment_method_id,
payment_method: self.payment_method,
connector_transaction_id,
capture_method: self.capture_method,
capture_on: self.capture_on,
confirm: self.confirm,
authentication_type: self.authentication_type,
created_at: self.created_at,
modified_at: self.modified_at,
last_synced: self.last_synced,
cancellation_reason: self.cancellation_reason,
amount_to_capture: self.amount_to_capture,
mandate_id: self.mandate_id,
browser_info: self.browser_info,
error_code: self.error_code,
payment_token: self.payment_token,
connector_metadata: self.connector_metadata,
payment_experience: self.payment_experience,
payment_method_type: self.payment_method_type,
payment_method_data: self.payment_method_data,
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
preprocessing_step_id: self.preprocessing_step_id,
mandate_details: self.mandate_details.map(Into::into),
error_reason: self.error_reason,
multiple_capture_count: self.multiple_capture_count,
connector_response_reference_id: self.connector_response_reference_id,
amount_capturable: self.amount_capturable,
updated_by: self.updated_by,
merchant_connector_id: self.merchant_connector_id,
authentication_data: self.authentication_data,
encoded_data: self.encoded_data,
unified_code: self.unified_code,
unified_message: self.unified_message,
net_amount: Some(self.net_amount.get_total_amount()),
external_three_ds_authentication_attempted: self
.external_three_ds_authentication_attempted,
authentication_connector: self.authentication_connector,
authentication_id: self.authentication_id,
mandate_data: self.mandate_data.map(Into::into),
fingerprint_id: self.fingerprint_id,
payment_method_billing_address_id: self.payment_method_billing_address_id,
charge_id: self.charge_id,
client_source: self.client_source,
client_version: self.client_version,
customer_acceptance: self.customer_acceptance,
profile_id: self.profile_id,
organization_id: self.organization_id,
card_network,
order_tax_amount: self.net_amount.get_order_tax_amount(),
shipping_cost: self.net_amount.get_shipping_cost(),
connector_mandate_detail: self.connector_mandate_detail,
request_extended_authorization: self.request_extended_authorization,
extended_authorization_applied: self.extended_authorization_applied,
capture_before: self.capture_before,
processor_transaction_data,
card_discovery: self.card_discovery,
charges: self.charges,
issuer_error_code: self.issuer_error_code,
issuer_error_message: self.issuer_error_message,
setup_future_usage_applied: self.setup_future_usage_applied,
// Below fields are deprecated. Please add any new fields above this line.
connector_transaction_data: None,
processor_merchant_id: Some(self.processor_merchant_id),
created_by: self.created_by.map(|cb| cb.to_string()),
routing_approach: self.routing_approach,
connector_request_reference_id: self.connector_request_reference_id,
network_transaction_id: self.network_transaction_id,
is_overcapture_enabled: self.is_overcapture_enabled,
network_details: self.network_details,
is_stored_credential: self.is_stored_credential,
authorized_amount: self.authorized_amount,
})
}
async fn convert_back(
_state: &KeyManagerState,
storage_model: Self::DstType,
_key: &Secret<Vec<u8>>,
_key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
async {
let connector_transaction_id = storage_model
.get_optional_connector_transaction_id()
.cloned();
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
payment_id: storage_model.payment_id,
merchant_id: storage_model.merchant_id.clone(),
attempt_id: storage_model.attempt_id,
status: storage_model.status,
net_amount: NetAmount::new(
storage_model.amount,
storage_model.shipping_cost,
storage_model.order_tax_amount,
storage_model.surcharge_amount,
storage_model.tax_amount,
),
currency: storage_model.currency,
save_to_locker: storage_model.save_to_locker,
connector: storage_model.connector,
error_message: storage_model.error_message,
offer_amount: storage_model.offer_amount,
payment_method_id: storage_model.payment_method_id,
payment_method: storage_model.payment_method,
connector_transaction_id,
capture_method: storage_model.capture_method,
capture_on: storage_model.capture_on,
confirm: storage_model.confirm,
authentication_type: storage_model.authentication_type,
created_at: storage_model.created_at,
modified_at: storage_model.modified_at,
last_synced: storage_model.last_synced,
cancellation_reason: storage_model.cancellation_reason,
amount_to_capture: storage_model.amount_to_capture,
mandate_id: storage_model.mandate_id,
browser_info: storage_model.browser_info,
error_code: storage_model.error_code,
payment_token: storage_model.payment_token,
connector_metadata: storage_model.connector_metadata,
payment_experience: storage_model.payment_experience,
payment_method_type: storage_model.payment_method_type,
payment_method_data: storage_model.payment_method_data,
business_sub_label: storage_model.business_sub_label,
straight_through_algorithm: storage_model.straight_through_algorithm,
preprocessing_step_id: storage_model.preprocessing_step_id,
mandate_details: storage_model.mandate_details.map(Into::into),
error_reason: storage_model.error_reason,
multiple_capture_count: storage_model.multiple_capture_count,
connector_response_reference_id: storage_model.connector_response_reference_id,
amount_capturable: storage_model.amount_capturable,
updated_by: storage_model.updated_by,
authentication_data: storage_model.authentication_data,
encoded_data: storage_model.encoded_data,
merchant_connector_id: storage_model.merchant_connector_id,
unified_code: storage_model.unified_code,
unified_message: storage_model.unified_message,
external_three_ds_authentication_attempted: storage_model
.external_three_ds_authentication_attempted,
authentication_connector: storage_model.authentication_connector,
authentication_id: storage_model.authentication_id,
mandate_data: storage_model.mandate_data.map(Into::into),
payment_method_billing_address_id: storage_model.payment_method_billing_address_id,
fingerprint_id: storage_model.fingerprint_id,
charge_id: storage_model.charge_id,
client_source: storage_model.client_source,
client_version: storage_model.client_version,
customer_acceptance: storage_model.customer_acceptance,
profile_id: storage_model.profile_id,
organization_id: storage_model.organization_id,
connector_mandate_detail: storage_model.connector_mandate_detail,
request_extended_authorization: storage_model.request_extended_authorization,
extended_authorization_applied: storage_model.extended_authorization_applied,
capture_before: storage_model.capture_before,
card_discovery: storage_model.card_discovery,
charges: storage_model.charges,
issuer_error_code: storage_model.issuer_error_code,
issuer_error_message: storage_model.issuer_error_message,
processor_merchant_id: storage_model
.processor_merchant_id
.unwrap_or(storage_model.merchant_id),
created_by: storage_model
.created_by
.and_then(|created_by| created_by.parse::<CreatedBy>().ok()),
setup_future_usage_applied: storage_model.setup_future_usage_applied,
routing_approach: storage_model.routing_approach,
connector_request_reference_id: storage_model.connector_request_reference_id,
debit_routing_savings: None,
network_transaction_id: storage_model.network_transaction_id,
is_overcapture_enabled: storage_model.is_overcapture_enabled,
network_details: storage_model.network_details,
is_stored_credential: storage_model.is_stored_credential,
authorized_amount: storage_model.authorized_amount,
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting payment attempt".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let card_network = self
.payment_method_data
.as_ref()
.and_then(|data| data.as_object())
.and_then(|card| card.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string());
Ok(DieselPaymentAttemptNew {
payment_id: self.payment_id,
merchant_id: self.merchant_id,
attempt_id: self.attempt_id,
status: self.status,
amount: self.net_amount.get_order_amount(),
currency: self.currency,
save_to_locker: self.save_to_locker,
connector: self.connector,
error_message: self.error_message,
offer_amount: self.offer_amount,
surcharge_amount: self.net_amount.get_surcharge_amount(),
tax_amount: self.net_amount.get_tax_on_surcharge(),
payment_method_id: self.payment_method_id,
payment_method: self.payment_method,
capture_method: self.capture_method,
capture_on: self.capture_on,
confirm: self.confirm,
authentication_type: self.authentication_type,
created_at: self.created_at,
modified_at: self.modified_at,
last_synced: self.last_synced,
cancellation_reason: self.cancellation_reason,
amount_to_capture: self.amount_to_capture,
mandate_id: self.mandate_id,
browser_info: self.browser_info,
payment_token: self.payment_token,
error_code: self.error_code,
connector_metadata: self.connector_metadata,
payment_experience: self.payment_experience,
payment_method_type: self.payment_method_type,
payment_method_data: self.payment_method_data,
business_sub_label: self.business_sub_label,
straight_through_algorithm: self.straight_through_algorithm,
preprocessing_step_id: self.preprocessing_step_id,
mandate_details: self.mandate_details.map(Into::into),
error_reason: self.error_reason,
connector_response_reference_id: self.connector_response_reference_id,
multiple_capture_count: self.multiple_capture_count,
amount_capturable: self.amount_capturable,
updated_by: self.updated_by,
merchant_connector_id: self.merchant_connector_id,
authentication_data: self.authentication_data,
encoded_data: self.encoded_data,
unified_code: self.unified_code,
unified_message: self.unified_message,
net_amount: Some(self.net_amount.get_total_amount()),
external_three_ds_authentication_attempted: self
.external_three_ds_authentication_attempted,
authentication_connector: self.authentication_connector,
authentication_id: self.authentication_id,
mandate_data: self.mandate_data.map(Into::into),
fingerprint_id: self.fingerprint_id,
payment_method_billing_address_id: self.payment_method_billing_address_id,
client_source: self.client_source,
client_version: self.client_version,
customer_acceptance: self.customer_acceptance,
profile_id: self.profile_id,
organization_id: self.organization_id,
card_network,
order_tax_amount: self.net_amount.get_order_tax_amount(),
shipping_cost: self.net_amount.get_shipping_cost(),
connector_mandate_detail: self.connector_mandate_detail,
request_extended_authorization: self.request_extended_authorization,
extended_authorization_applied: self.extended_authorization_applied,
capture_before: self.capture_before,
card_discovery: self.card_discovery,
processor_merchant_id: Some(self.processor_merchant_id),
created_by: self.created_by.map(|cb| cb.to_string()),
setup_future_usage_applied: self.setup_future_usage_applied,
routing_approach: self.routing_approach,
connector_request_reference_id: self.connector_request_reference_id,
network_transaction_id: self.network_transaction_id,
network_details: self.network_details,
is_stored_credential: self.is_stored_credential,
authorized_amount: self.authorized_amount,
})
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl behaviour::Conversion for PaymentAttempt {
type DstType = DieselPaymentAttempt;
type NewDstType = DieselPaymentAttemptNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
use common_utils::encryption::Encryption;
let card_network = self
.payment_method_data
.as_ref()
.and_then(|data| data.peek().as_object())
.and_then(|card| card.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string());
let Self {
payment_id,
merchant_id,
attempts_group_id,
status,
error,
amount_details,
authentication_type,
created_at,
modified_at,
last_synced,
cancellation_reason,
browser_info,
payment_token,
connector_metadata,
payment_experience,
payment_method_data,
routing_result,
preprocessing_step_id,
multiple_capture_count,
connector_response_reference_id,
updated_by,
redirection_data,
encoded_data,
merchant_connector_id,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
fingerprint_id,
client_source,
client_version,
customer_acceptance,
profile_id,
organization_id,
payment_method_type,
connector_payment_id,
payment_method_subtype,
authentication_applied,
external_reference_id,
id,
payment_method_id,
payment_method_billing_address,
connector,
connector_token_details,
card_discovery,
charges,
feature_metadata,
processor_merchant_id,
created_by,
connector_request_reference_id,
network_transaction_id,
authorized_amount,
} = self;
let AttemptAmountDetails {
net_amount,
tax_on_surcharge,
surcharge_amount,
order_tax_amount,
shipping_cost,
amount_capturable,
amount_to_capture,
} = amount_details;
let (connector_payment_id, connector_payment_data) = connector_payment_id
.map(ConnectorTransactionId::form_id_and_data)
.map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
.unwrap_or((None, None));
let feature_metadata = feature_metadata.as_ref().map(From::from);
Ok(DieselPaymentAttempt {
payment_id,
merchant_id,
id,
status,
error_message: error.as_ref().map(|details| details.message.clone()),
payment_method_id,
payment_method_type_v2: payment_method_type,
connector_payment_id,
authentication_type,
created_at,
modified_at,
last_synced,
cancellation_reason,
amount_to_capture,
browser_info,
error_code: error.as_ref().map(|details| details.code.clone()),
payment_token,
connector_metadata,
payment_experience,
payment_method_subtype,
payment_method_data,
preprocessing_step_id,
error_reason: error.as_ref().and_then(|details| details.reason.clone()),
multiple_capture_count,
connector_response_reference_id,
amount_capturable,
updated_by,
merchant_connector_id,
redirection_data: redirection_data.map(From::from),
encoded_data,
unified_code: error
.as_ref()
.and_then(|details| details.unified_code.clone()),
unified_message: error
.as_ref()
.and_then(|details| details.unified_message.clone()),
net_amount,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
fingerprint_id,
client_source,
client_version,
customer_acceptance,
profile_id,
organization_id,
card_network,
order_tax_amount,
shipping_cost,
routing_result,
authentication_applied,
external_reference_id,
connector,
surcharge_amount,
tax_on_surcharge,
payment_method_billing_address: payment_method_billing_address.map(Encryption::from),
connector_payment_data,
connector_token_details,
card_discovery,
request_extended_authorization: None,
extended_authorization_applied: None,
capture_before: None,
charges,
feature_metadata,
network_advice_code: error
.as_ref()
.and_then(|details| details.network_advice_code.clone()),
network_decline_code: error
.as_ref()
.and_then(|details| details.network_decline_code.clone()),
network_error_message: error
.as_ref()
.and_then(|details| details.network_error_message.clone()),
processor_merchant_id: Some(processor_merchant_id),
created_by: created_by.map(|cb| cb.to_string()),
connector_request_reference_id,
network_transaction_id,
is_overcapture_enabled: None,
network_details: None,
attempts_group_id,
is_stored_credential: None,
authorized_amount,
})
}
async fn convert_back(
state: &KeyManagerState,
storage_model: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
async {
let connector_payment_id = storage_model
.get_optional_connector_transaction_id()
.cloned();
let decrypted_data = crypto_operation(
state,
common_utils::type_name!(Self::DstType),
CryptoOperation::BatchDecrypt(EncryptedPaymentAttempt::to_encryptable(
EncryptedPaymentAttempt {
payment_method_billing_address: storage_model
.payment_method_billing_address,
},
)),
key_manager_identifier,
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())?;
let decrypted_data = EncryptedPaymentAttempt::from_encryptable(decrypted_data)
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Invalid batch operation data")?;
let payment_method_billing_address = decrypted_data
.payment_method_billing_address
.map(|billing| {
billing.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing Address")?;
let amount_details = AttemptAmountDetails {
net_amount: storage_model.net_amount,
tax_on_surcharge: storage_model.tax_on_surcharge,
surcharge_amount: storage_model.surcharge_amount,
order_tax_amount: storage_model.order_tax_amount,
shipping_cost: storage_model.shipping_cost,
amount_capturable: storage_model.amount_capturable,
amount_to_capture: storage_model.amount_to_capture,
};
let error = storage_model
.error_code
.zip(storage_model.error_message)
.map(|(error_code, error_message)| ErrorDetails {
code: error_code,
message: error_message,
reason: storage_model.error_reason,
unified_code: storage_model.unified_code,
unified_message: storage_model.unified_message,
network_advice_code: storage_model.network_advice_code,
network_decline_code: storage_model.network_decline_code,
network_error_message: storage_model.network_error_message,
});
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
payment_id: storage_model.payment_id,
merchant_id: storage_model.merchant_id.clone(),
attempts_group_id: storage_model.attempts_group_id,
id: storage_model.id,
status: storage_model.status,
amount_details,
error,
payment_method_id: storage_model.payment_method_id,
payment_method_type: storage_model.payment_method_type_v2,
connector_payment_id,
authentication_type: storage_model.authentication_type,
created_at: storage_model.created_at,
modified_at: storage_model.modified_at,
last_synced: storage_model.last_synced,
cancellation_reason: storage_model.cancellation_reason,
browser_info: storage_model.browser_info,
payment_token: storage_model.payment_token,
connector_metadata: storage_model.connector_metadata,
payment_experience: storage_model.payment_experience,
payment_method_data: storage_model.payment_method_data,
routing_result: storage_model.routing_result,
preprocessing_step_id: storage_model.preprocessing_step_id,
multiple_capture_count: storage_model.multiple_capture_count,
connector_response_reference_id: storage_model.connector_response_reference_id,
updated_by: storage_model.updated_by,
redirection_data: storage_model.redirection_data.map(From::from),
encoded_data: storage_model.encoded_data,
merchant_connector_id: storage_model.merchant_connector_id,
external_three_ds_authentication_attempted: storage_model
.external_three_ds_authentication_attempted,
authentication_connector: storage_model.authentication_connector,
authentication_id: storage_model.authentication_id,
fingerprint_id: storage_model.fingerprint_id,
charges: storage_model.charges,
client_source: storage_model.client_source,
client_version: storage_model.client_version,
customer_acceptance: storage_model.customer_acceptance,
profile_id: storage_model.profile_id,
organization_id: storage_model.organization_id,
payment_method_subtype: storage_model.payment_method_subtype,
authentication_applied: storage_model.authentication_applied,
external_reference_id: storage_model.external_reference_id,
connector: storage_model.connector,
payment_method_billing_address,
connector_token_details: storage_model.connector_token_details,
card_discovery: storage_model.card_discovery,
feature_metadata: storage_model.feature_metadata.map(From::from),
processor_merchant_id: storage_model
.processor_merchant_id
.unwrap_or(storage_model.merchant_id),
created_by: storage_model
.created_by
.and_then(|created_by| created_by.parse::<CreatedBy>().ok()),
connector_request_reference_id: storage_model.connector_request_reference_id,
network_transaction_id: storage_model.network_transaction_id,
authorized_amount: storage_model.authorized_amount,
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting payment attempt".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
use common_utils::encryption::Encryption;
let Self {
payment_id,
merchant_id,
attempts_group_id,
status,
error,
amount_details,
authentication_type,
created_at,
modified_at,
last_synced,
cancellation_reason,
browser_info,
payment_token,
connector_metadata,
payment_experience,
payment_method_data,
routing_result: _,
preprocessing_step_id,
multiple_capture_count,
connector_response_reference_id,
updated_by,
redirection_data,
encoded_data,
merchant_connector_id,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
fingerprint_id,
client_source,
client_version,
customer_acceptance,
profile_id,
organization_id,
payment_method_type,
connector_payment_id,
payment_method_subtype,
authentication_applied: _,
external_reference_id: _,
id,
payment_method_id,
payment_method_billing_address,
connector,
connector_token_details,
card_discovery,
charges,
feature_metadata,
processor_merchant_id,
created_by,
connector_request_reference_id,
network_transaction_id,
authorized_amount,
} = self;
let card_network = payment_method_data
.as_ref()
.and_then(|data| data.peek().as_object())
.and_then(|card| card.get("card"))
.and_then(|data| data.as_object())
.and_then(|card| card.get("card_network"))
.and_then(|network| network.as_str())
.map(|network| network.to_string());
let error_details = error;
Ok(DieselPaymentAttemptNew {
payment_id,
merchant_id,
status,
network_transaction_id,
error_message: error_details
.as_ref()
.map(|details| details.message.clone()),
surcharge_amount: amount_details.surcharge_amount,
tax_on_surcharge: amount_details.tax_on_surcharge,
payment_method_id,
authentication_type,
created_at,
modified_at,
last_synced,
cancellation_reason,
browser_info,
payment_token,
error_code: error_details.as_ref().map(|details| details.code.clone()),
connector_metadata,
payment_experience,
payment_method_data,
preprocessing_step_id,
error_reason: error_details
.as_ref()
.and_then(|details| details.reason.clone()),
connector_response_reference_id,
multiple_capture_count,
amount_capturable: amount_details.amount_capturable,
updated_by,
merchant_connector_id,
redirection_data: redirection_data.map(From::from),
encoded_data,
unified_code: error_details
.as_ref()
.and_then(|details| details.unified_code.clone()),
unified_message: error_details
.as_ref()
.and_then(|details| details.unified_message.clone()),
net_amount: amount_details.net_amount,
external_three_ds_authentication_attempted,
authentication_connector,
authentication_id,
fingerprint_id,
client_source,
client_version,
customer_acceptance,
profile_id,
organization_id,
card_network,
order_tax_amount: amount_details.order_tax_amount,
shipping_cost: amount_details.shipping_cost,
amount_to_capture: amount_details.amount_to_capture,
payment_method_billing_address: payment_method_billing_address.map(Encryption::from),
payment_method_subtype,
connector_payment_id: connector_payment_id
.as_ref()
.map(|txn_id| ConnectorTransactionId::TxnId(txn_id.clone())),
payment_method_type_v2: payment_method_type,
id,
charges,
connector_token_details,
card_discovery,
extended_authorization_applied: None,
request_extended_authorization: None,
capture_before: None,
feature_metadata: feature_metadata.as_ref().map(From::from),
connector,
network_advice_code: error_details
.as_ref()
.and_then(|details| details.network_advice_code.clone()),
network_decline_code: error_details
.as_ref()
.and_then(|details| details.network_decline_code.clone()),
network_error_message: error_details
.as_ref()
.and_then(|details| details.network_error_message.clone()),
processor_merchant_id: Some(processor_merchant_id),
created_by: created_by.map(|cb| cb.to_string()),
connector_request_reference_id,
network_details: None,
attempts_group_id,
is_stored_credential: None,
authorized_amount,
})
}
}
#[cfg(feature = "v2")]
impl From<PaymentAttemptUpdate> for diesel_models::PaymentAttemptUpdateInternal {
fn from(update: PaymentAttemptUpdate) -> Self {
match update {
PaymentAttemptUpdate::ConfirmIntent {
status,
updated_by,
connector,
merchant_connector_id,
authentication_type,
connector_request_reference_id,
connector_response_reference_id,
} => Self {
status: Some(status),
payment_method_id: None,
error_message: None,
modified_at: common_utils::date_time::now(),
browser_info: None,
error_code: None,
error_reason: None,
updated_by,
merchant_connector_id,
unified_code: None,
unified_message: None,
connector_payment_id: None,
connector_payment_data: None,
connector: Some(connector),
redirection_data: None,
connector_metadata: None,
amount_capturable: None,
amount_to_capture: None,
connector_token_details: None,
authentication_type: Some(authentication_type),
feature_metadata: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_request_reference_id,
connector_response_reference_id,
cancellation_reason: None,
},
PaymentAttemptUpdate::ErrorUpdate {
status,
error,
connector_payment_id,
amount_capturable,
updated_by,
} => {
// Apply automatic hashing for long connector payment IDs
let (connector_payment_id, connector_payment_data) = connector_payment_id
.map(ConnectorTransactionId::form_id_and_data)
.map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
.unwrap_or((None, None));
Self {
status: Some(status),
payment_method_id: None,
error_message: Some(error.message),
error_code: Some(error.code),
modified_at: common_utils::date_time::now(),
browser_info: None,
error_reason: error.reason,
updated_by,
merchant_connector_id: None,
unified_code: None,
unified_message: None,
connector_payment_id,
connector_payment_data,
connector: None,
redirection_data: None,
connector_metadata: None,
amount_capturable,
amount_to_capture: None,
connector_token_details: None,
authentication_type: None,
feature_metadata: None,
network_advice_code: error.network_advice_code,
network_decline_code: error.network_decline_code,
network_error_message: error.network_error_message,
connector_request_reference_id: None,
connector_response_reference_id: None,
cancellation_reason: None,
}
}
PaymentAttemptUpdate::ConfirmIntentResponse(confirm_intent_response_update) => {
let ConfirmIntentResponseUpdate {
status,
connector_payment_id,
updated_by,
redirection_data,
connector_metadata,
amount_capturable,
connector_token_details,
connector_response_reference_id,
} = *confirm_intent_response_update;
// Apply automatic hashing for long connector payment IDs
let (connector_payment_id, connector_payment_data) = connector_payment_id
.map(ConnectorTransactionId::form_id_and_data)
.map(|(txn_id, txn_data)| (Some(txn_id), txn_data))
.unwrap_or((None, None));
Self {
status: Some(status),
payment_method_id: None,
amount_capturable,
error_message: None,
error_code: None,
modified_at: common_utils::date_time::now(),
browser_info: None,
error_reason: None,
updated_by,
merchant_connector_id: None,
unified_code: None,
unified_message: None,
connector_payment_id,
connector_payment_data,
connector: None,
redirection_data: redirection_data
.map(diesel_models::payment_attempt::RedirectForm::from),
connector_metadata,
amount_to_capture: None,
connector_token_details,
authentication_type: None,
feature_metadata: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_request_reference_id: None,
connector_response_reference_id,
cancellation_reason: None,
}
}
PaymentAttemptUpdate::SyncUpdate {
status,
amount_capturable,
updated_by,
} => Self {
status: Some(status),
payment_method_id: None,
amount_capturable,
error_message: None,
error_code: None,
modified_at: common_utils::date_time::now(),
browser_info: None,
error_reason: None,
updated_by,
merchant_connector_id: None,
unified_code: None,
unified_message: None,
connector_payment_id: None,
connector_payment_data: None,
connector: None,
redirection_data: None,
connector_metadata: None,
amount_to_capture: None,
connector_token_details: None,
authentication_type: None,
feature_metadata: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_request_reference_id: None,
connector_response_reference_id: None,
cancellation_reason: None,
},
PaymentAttemptUpdate::CaptureUpdate {
status,
amount_capturable,
updated_by,
} => Self {
status: Some(status),
payment_method_id: None,
amount_capturable,
amount_to_capture: None,
error_message: None,
error_code: None,
modified_at: common_utils::date_time::now(),
browser_info: None,
error_reason: None,
updated_by,
merchant_connector_id: None,
unified_code: None,
unified_message: None,
connector_payment_id: None,
connector_payment_data: None,
connector: None,
redirection_data: None,
connector_metadata: None,
connector_token_details: None,
authentication_type: None,
feature_metadata: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_request_reference_id: None,
connector_response_reference_id: None,
cancellation_reason: None,
},
PaymentAttemptUpdate::PreCaptureUpdate {
amount_to_capture,
updated_by,
} => Self {
amount_to_capture,
payment_method_id: None,
error_message: None,
modified_at: common_utils::date_time::now(),
browser_info: None,
error_code: None,
error_reason: None,
updated_by,
merchant_connector_id: None,
unified_code: None,
unified_message: None,
connector_payment_id: None,
connector_payment_data: None,
connector: None,
redirection_data: None,
status: None,
connector_metadata: None,
amount_capturable: None,
connector_token_details: None,
authentication_type: None,
feature_metadata: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_request_reference_id: None,
connector_response_reference_id: None,
cancellation_reason: None,
},
PaymentAttemptUpdate::ConfirmIntentTokenized {
status,
updated_by,
connector,
merchant_connector_id,
authentication_type,
payment_method_id,
connector_request_reference_id,
} => Self {
status: Some(status),
payment_method_id: Some(payment_method_id),
error_message: None,
modified_at: common_utils::date_time::now(),
browser_info: None,
error_code: None,
error_reason: None,
updated_by,
merchant_connector_id: Some(merchant_connector_id),
unified_code: None,
unified_message: None,
connector_payment_id: None,
connector_payment_data: None,
connector: Some(connector),
redirection_data: None,
connector_metadata: None,
amount_capturable: None,
amount_to_capture: None,
connector_token_details: None,
authentication_type: Some(authentication_type),
feature_metadata: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_request_reference_id,
connector_response_reference_id: None,
cancellation_reason: None,
},
PaymentAttemptUpdate::VoidUpdate {
status,
cancellation_reason,
updated_by,
} => Self {
status: Some(status),
cancellation_reason,
error_message: None,
error_code: None,
modified_at: common_utils::date_time::now(),
browser_info: None,
error_reason: None,
updated_by,
merchant_connector_id: None,
unified_code: None,
unified_message: None,
connector_payment_id: None,
connector_payment_data: None,
connector: None,
redirection_data: None,
connector_metadata: None,
amount_capturable: None,
amount_to_capture: None,
connector_token_details: None,
authentication_type: None,
feature_metadata: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_request_reference_id: None,
connector_response_reference_id: None,
payment_method_id: None,
},
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, PartialEq)]
pub struct PaymentAttemptFeatureMetadata {
pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, PartialEq)]
pub struct PaymentAttemptRevenueRecoveryData {
pub attempt_triggered_by: common_enums::TriggeredBy,
// stripe specific field used to identify duplicate attempts.
pub charge_id: Option<String>,
}
#[cfg(feature = "v2")]
impl From<&PaymentAttemptFeatureMetadata> for DieselPaymentAttemptFeatureMetadata {
fn from(item: &PaymentAttemptFeatureMetadata) -> Self {
let revenue_recovery =
item.revenue_recovery
.as_ref()
.map(|recovery_data| DieselPassiveChurnRecoveryData {
attempt_triggered_by: recovery_data.attempt_triggered_by,
charge_id: recovery_data.charge_id.clone(),
});
Self { revenue_recovery }
}
}
#[cfg(feature = "v2")]
impl From<DieselPaymentAttemptFeatureMetadata> for PaymentAttemptFeatureMetadata {
fn from(item: DieselPaymentAttemptFeatureMetadata) -> Self {
let revenue_recovery =
item.revenue_recovery
.map(|recovery_data| PaymentAttemptRevenueRecoveryData {
attempt_triggered_by: recovery_data.attempt_triggered_by,
charge_id: recovery_data.charge_id,
});
Self { revenue_recovery }
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/payments/payment_attempt.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 11,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_6007621901426249509
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/payments/payment_intent.rs
// Contains: 4 structs, 2 enums
use common_types::primitive_wrappers;
#[cfg(feature = "v1")]
use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V2;
#[cfg(feature = "v2")]
use common_utils::errors::ParsingError;
#[cfg(feature = "v2")]
use common_utils::ext_traits::{Encode, ValueExt};
use common_utils::{
consts::PAYMENTS_LIST_MAX_LIMIT_V1,
crypto::Encryptable,
encryption::Encryption,
errors::{CustomResult, ValidationError},
id_type,
pii::{self, Email},
type_name,
types::{
keymanager::{self, KeyManagerState, ToEncryptable},
CreatedBy, MinorUnit,
},
};
use diesel_models::{
PaymentIntent as DieselPaymentIntent, PaymentIntentNew as DieselPaymentIntentNew,
};
use error_stack::ResultExt;
#[cfg(feature = "v2")]
use masking::ExposeInterface;
use masking::{Deserialize, PeekInterface, Secret};
use serde::Serialize;
use time::PrimitiveDateTime;
#[cfg(all(feature = "v1", feature = "olap"))]
use super::payment_attempt::PaymentAttempt;
use super::PaymentIntent;
#[cfg(feature = "v2")]
use crate::address::Address;
#[cfg(feature = "v2")]
use crate::routing;
use crate::{
behaviour,
merchant_key_store::MerchantKeyStore,
type_encryption::{crypto_operation, CryptoOperation},
};
#[cfg(feature = "v1")]
use crate::{errors, RemoteStorageObject};
#[async_trait::async_trait]
pub trait PaymentIntentInterface {
type Error;
async fn update_payment_intent(
&self,
state: &KeyManagerState,
this: PaymentIntent,
payment_intent: PaymentIntentUpdate,
merchant_key_store: &MerchantKeyStore,
storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, Self::Error>;
async fn insert_payment_intent(
&self,
state: &KeyManagerState,
new: PaymentIntent,
merchant_key_store: &MerchantKeyStore,
storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, Self::Error>;
#[cfg(feature = "v1")]
async fn find_payment_intent_by_payment_id_merchant_id(
&self,
state: &KeyManagerState,
payment_id: &id_type::PaymentId,
merchant_id: &id_type::MerchantId,
merchant_key_store: &MerchantKeyStore,
storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, Self::Error>;
#[cfg(feature = "v2")]
async fn find_payment_intent_by_merchant_reference_id_profile_id(
&self,
state: &KeyManagerState,
merchant_reference_id: &id_type::PaymentReferenceId,
profile_id: &id_type::ProfileId,
merchant_key_store: &MerchantKeyStore,
storage_scheme: &common_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, Self::Error>;
#[cfg(feature = "v2")]
async fn find_payment_intent_by_id(
&self,
state: &KeyManagerState,
id: &id_type::GlobalPaymentId,
merchant_key_store: &MerchantKeyStore,
storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, Self::Error>;
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_payment_intent_by_constraints(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
filters: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, Self::Error>;
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_payment_intents_by_time_range_constraints(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
time_range: &common_utils::types::TimeRange,
merchant_key_store: &MerchantKeyStore,
storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, Self::Error>;
#[cfg(feature = "olap")]
async fn get_intent_status_with_count(
&self,
merchant_id: &id_type::MerchantId,
profile_id_list: Option<Vec<id_type::ProfileId>>,
constraints: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, Self::Error>;
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, Self::Error>;
#[cfg(all(feature = "v2", feature = "olap"))]
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<
Vec<(
PaymentIntent,
Option<super::payment_attempt::PaymentAttempt>,
)>,
Self::Error,
>;
#[cfg(all(feature = "v2", feature = "olap"))]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
merchant_id: &id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<Option<String>>, Self::Error>;
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
merchant_id: &id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, Self::Error>;
}
#[derive(Clone, Debug, PartialEq, router_derive::DebugAsDisplay, Serialize, Deserialize)]
pub struct CustomerData {
pub name: Option<Secret<String>>,
pub email: Option<Email>,
pub phone: Option<Secret<String>>,
pub phone_country_code: Option<String>,
pub tax_registration_id: Option<Secret<String>>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Serialize)]
pub struct PaymentIntentUpdateFields {
pub amount: Option<MinorUnit>,
pub currency: Option<common_enums::Currency>,
pub shipping_cost: Option<MinorUnit>,
pub tax_details: Option<diesel_models::TaxDetails>,
pub skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>,
pub skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>,
pub surcharge_amount: Option<MinorUnit>,
pub tax_on_surcharge: Option<MinorUnit>,
pub routing_algorithm_id: Option<id_type::RoutingId>,
pub capture_method: Option<common_enums::CaptureMethod>,
pub authentication_type: Option<common_enums::AuthenticationType>,
pub billing_address: Option<Encryptable<Address>>,
pub shipping_address: Option<Encryptable<Address>>,
pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>,
pub description: Option<common_utils::types::Description>,
pub return_url: Option<common_utils::types::Url>,
pub setup_future_usage: Option<common_enums::FutureUsage>,
pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>,
pub statement_descriptor: Option<common_utils::types::StatementDescriptor>,
pub order_details: Option<Vec<Secret<diesel_models::types::OrderDetailsWithAmount>>>,
pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_metadata: Option<pii::SecretSerdeValue>,
pub feature_metadata: Option<diesel_models::types::FeatureMetadata>,
pub payment_link_config: Option<diesel_models::PaymentLinkConfigRequestForPayments>,
pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>,
pub session_expiry: Option<PrimitiveDateTime>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
pub request_external_three_ds_authentication:
Option<common_enums::External3dsAuthenticationRequest>,
pub active_attempt_id: Option<Option<id_type::GlobalAttemptId>>,
// updated_by is set internally, field not present in request
pub updated_by: String,
pub force_3ds_challenge: Option<bool>,
pub is_iframe_redirection_enabled: Option<bool>,
pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Serialize)]
pub struct PaymentIntentUpdateFields {
pub amount: MinorUnit,
pub currency: common_enums::Currency,
pub setup_future_usage: Option<common_enums::FutureUsage>,
pub status: common_enums::IntentStatus,
pub customer_id: Option<id_type::CustomerId>,
pub shipping_address_id: Option<String>,
pub billing_address_id: Option<String>,
pub return_url: Option<String>,
pub business_country: Option<common_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub description: Option<String>,
pub statement_descriptor_name: Option<String>,
pub statement_descriptor_suffix: Option<String>,
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
pub metadata: Option<serde_json::Value>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
pub payment_confirm_source: Option<common_enums::PaymentSource>,
pub updated_by: String,
pub fingerprint_id: Option<String>,
pub session_expiry: Option<PrimitiveDateTime>,
pub request_external_three_ds_authentication: Option<bool>,
pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub is_payment_processor_token_flow: Option<bool>,
pub tax_details: Option<diesel_models::TaxDetails>,
pub force_3ds_challenge: Option<bool>,
pub is_iframe_redirection_enabled: Option<bool>,
pub tax_status: Option<common_enums::TaxStatus>,
pub discount_amount: Option<MinorUnit>,
pub order_date: Option<PrimitiveDateTime>,
pub shipping_amount_tax: Option<MinorUnit>,
pub duty_amount: Option<MinorUnit>,
pub is_confirm_operation: bool,
pub payment_channel: Option<common_enums::PaymentChannel>,
pub feature_metadata: Option<Secret<serde_json::Value>>,
pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,
pub enable_overcapture: Option<primitive_wrappers::EnableOvercaptureBool>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Serialize)]
pub enum PaymentIntentUpdate {
ResponseUpdate {
status: common_enums::IntentStatus,
amount_captured: Option<MinorUnit>,
updated_by: String,
fingerprint_id: Option<String>,
incremental_authorization_allowed: Option<bool>,
feature_metadata: Option<Secret<serde_json::Value>>,
},
MetadataUpdate {
metadata: serde_json::Value,
updated_by: String,
},
Update(Box<PaymentIntentUpdateFields>),
PaymentCreateUpdate {
return_url: Option<String>,
status: Option<common_enums::IntentStatus>,
customer_id: Option<id_type::CustomerId>,
shipping_address_id: Option<String>,
billing_address_id: Option<String>,
customer_details: Option<Encryptable<Secret<serde_json::Value>>>,
updated_by: String,
},
MerchantStatusUpdate {
status: common_enums::IntentStatus,
shipping_address_id: Option<String>,
billing_address_id: Option<String>,
updated_by: String,
},
PGStatusUpdate {
status: common_enums::IntentStatus,
incremental_authorization_allowed: Option<bool>,
updated_by: String,
feature_metadata: Option<Secret<serde_json::Value>>,
},
PaymentAttemptAndAttemptCountUpdate {
active_attempt_id: String,
attempt_count: i16,
updated_by: String,
},
StatusAndAttemptUpdate {
status: common_enums::IntentStatus,
active_attempt_id: String,
attempt_count: i16,
updated_by: String,
},
ApproveUpdate {
status: common_enums::IntentStatus,
merchant_decision: Option<String>,
updated_by: String,
},
RejectUpdate {
status: common_enums::IntentStatus,
merchant_decision: Option<String>,
updated_by: String,
},
SurchargeApplicableUpdate {
surcharge_applicable: bool,
updated_by: String,
},
IncrementalAuthorizationAmountUpdate {
amount: MinorUnit,
},
AuthorizationCountUpdate {
authorization_count: i32,
},
CompleteAuthorizeUpdate {
shipping_address_id: Option<String>,
},
ManualUpdate {
status: Option<common_enums::IntentStatus>,
updated_by: String,
},
SessionResponseUpdate {
tax_details: diesel_models::TaxDetails,
shipping_address_id: Option<String>,
updated_by: String,
shipping_details: Option<Encryptable<Secret<serde_json::Value>>>,
},
}
#[cfg(feature = "v1")]
impl PaymentIntentUpdate {
pub fn is_confirm_operation(&self) -> bool {
match self {
Self::Update(value) => value.is_confirm_operation,
_ => false,
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Serialize)]
pub enum PaymentIntentUpdate {
/// PreUpdate tracker of ConfirmIntent
ConfirmIntent {
status: common_enums::IntentStatus,
active_attempt_id: Option<id_type::GlobalAttemptId>,
updated_by: String,
},
/// PostUpdate tracker of ConfirmIntent
ConfirmIntentPostUpdate {
status: common_enums::IntentStatus,
amount_captured: Option<MinorUnit>,
updated_by: String,
feature_metadata: Option<Box<diesel_models::types::FeatureMetadata>>,
},
/// SyncUpdate of ConfirmIntent in PostUpdateTrackers
SyncUpdate {
status: common_enums::IntentStatus,
amount_captured: Option<MinorUnit>,
updated_by: String,
},
CaptureUpdate {
status: common_enums::IntentStatus,
amount_captured: Option<MinorUnit>,
updated_by: String,
},
/// Update the payment intent details on payment sdk session call, before calling the connector.
SessionIntentUpdate {
prerouting_algorithm: routing::PaymentRoutingInfo,
updated_by: String,
},
RecordUpdate {
status: common_enums::IntentStatus,
feature_metadata: Box<Option<diesel_models::types::FeatureMetadata>>,
updated_by: String,
active_attempt_id: Option<id_type::GlobalAttemptId>,
},
/// UpdateIntent
UpdateIntent(Box<PaymentIntentUpdateFields>),
/// VoidUpdate for payment cancellation
VoidUpdate {
status: common_enums::IntentStatus,
updated_by: String,
},
}
#[cfg(feature = "v2")]
impl PaymentIntentUpdate {
pub fn is_confirm_operation(&self) -> bool {
matches!(self, Self::ConfirmIntent { .. })
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Default)]
pub struct PaymentIntentUpdateInternal {
pub amount: Option<MinorUnit>,
pub currency: Option<common_enums::Currency>,
pub status: Option<common_enums::IntentStatus>,
pub amount_captured: Option<MinorUnit>,
pub customer_id: Option<id_type::CustomerId>,
pub return_url: Option<String>,
pub setup_future_usage: Option<common_enums::FutureUsage>,
pub off_session: Option<bool>,
pub metadata: Option<serde_json::Value>,
pub billing_address_id: Option<String>,
pub shipping_address_id: Option<String>,
pub modified_at: Option<PrimitiveDateTime>,
pub active_attempt_id: Option<String>,
pub business_country: Option<common_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub description: Option<String>,
pub statement_descriptor_name: Option<String>,
pub statement_descriptor_suffix: Option<String>,
pub order_details: Option<Vec<pii::SecretSerdeValue>>,
pub attempt_count: Option<i16>,
// Denotes the action(approve or reject) taken by merchant in case of manual review.
// Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment
pub merchant_decision: Option<String>,
pub payment_confirm_source: Option<common_enums::PaymentSource>,
pub updated_by: String,
pub surcharge_applicable: Option<bool>,
pub incremental_authorization_allowed: Option<bool>,
pub authorization_count: Option<i32>,
pub fingerprint_id: Option<String>,
pub session_expiry: Option<PrimitiveDateTime>,
pub request_external_three_ds_authentication: Option<bool>,
pub frm_metadata: Option<pii::SecretSerdeValue>,
pub customer_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub billing_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub merchant_order_reference_id: Option<String>,
pub shipping_details: Option<Encryptable<Secret<serde_json::Value>>>,
pub is_payment_processor_token_flow: Option<bool>,
pub tax_details: Option<diesel_models::TaxDetails>,
pub force_3ds_challenge: Option<bool>,
pub is_iframe_redirection_enabled: Option<bool>,
pub payment_channel: Option<common_enums::PaymentChannel>,
pub feature_metadata: Option<Secret<serde_json::Value>>,
pub tax_status: Option<common_enums::TaxStatus>,
pub discount_amount: Option<MinorUnit>,
pub order_date: Option<PrimitiveDateTime>,
pub shipping_amount_tax: Option<MinorUnit>,
pub duty_amount: Option<MinorUnit>,
pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,
pub enable_overcapture: Option<primitive_wrappers::EnableOvercaptureBool>,
}
// This conversion is used in the `update_payment_intent` function
#[cfg(feature = "v2")]
impl TryFrom<PaymentIntentUpdate> for diesel_models::PaymentIntentUpdateInternal {
type Error = error_stack::Report<ParsingError>;
fn try_from(payment_intent_update: PaymentIntentUpdate) -> Result<Self, Self::Error> {
match payment_intent_update {
PaymentIntentUpdate::ConfirmIntent {
status,
active_attempt_id,
updated_by,
} => Ok(Self {
status: Some(status),
active_attempt_id: Some(active_attempt_id),
prerouting_algorithm: None,
modified_at: common_utils::date_time::now(),
amount: None,
amount_captured: None,
currency: None,
shipping_cost: None,
tax_details: None,
skip_external_tax_calculation: None,
surcharge_applicable: None,
surcharge_amount: None,
tax_on_surcharge: None,
routing_algorithm_id: None,
capture_method: None,
authentication_type: None,
billing_address: None,
shipping_address: None,
customer_present: None,
description: None,
return_url: None,
setup_future_usage: None,
apply_mit_exemption: None,
statement_descriptor: None,
order_details: None,
allowed_payment_method_types: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
payment_link_config: None,
request_incremental_authorization: None,
session_expiry: None,
frm_metadata: None,
request_external_three_ds_authentication: None,
updated_by,
force_3ds_challenge: None,
is_iframe_redirection_enabled: None,
enable_partial_authorization: None,
}),
PaymentIntentUpdate::ConfirmIntentPostUpdate {
status,
updated_by,
amount_captured,
feature_metadata,
} => Ok(Self {
status: Some(status),
active_attempt_id: None,
prerouting_algorithm: None,
modified_at: common_utils::date_time::now(),
amount_captured,
amount: None,
currency: None,
shipping_cost: None,
tax_details: None,
skip_external_tax_calculation: None,
surcharge_applicable: None,
surcharge_amount: None,
tax_on_surcharge: None,
routing_algorithm_id: None,
capture_method: None,
authentication_type: None,
billing_address: None,
shipping_address: None,
customer_present: None,
description: None,
return_url: None,
setup_future_usage: None,
apply_mit_exemption: None,
statement_descriptor: None,
order_details: None,
allowed_payment_method_types: None,
metadata: None,
connector_metadata: None,
feature_metadata: feature_metadata.map(|val| *val),
payment_link_config: None,
request_incremental_authorization: None,
session_expiry: None,
frm_metadata: None,
request_external_three_ds_authentication: None,
updated_by,
force_3ds_challenge: None,
is_iframe_redirection_enabled: None,
enable_partial_authorization: None,
}),
PaymentIntentUpdate::SyncUpdate {
status,
amount_captured,
updated_by,
} => Ok(Self {
status: Some(status),
active_attempt_id: None,
prerouting_algorithm: None,
modified_at: common_utils::date_time::now(),
amount: None,
currency: None,
amount_captured,
shipping_cost: None,
tax_details: None,
skip_external_tax_calculation: None,
surcharge_applicable: None,
surcharge_amount: None,
tax_on_surcharge: None,
routing_algorithm_id: None,
capture_method: None,
authentication_type: None,
billing_address: None,
shipping_address: None,
customer_present: None,
description: None,
return_url: None,
setup_future_usage: None,
apply_mit_exemption: None,
statement_descriptor: None,
order_details: None,
allowed_payment_method_types: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
payment_link_config: None,
request_incremental_authorization: None,
session_expiry: None,
frm_metadata: None,
request_external_three_ds_authentication: None,
updated_by,
force_3ds_challenge: None,
is_iframe_redirection_enabled: None,
enable_partial_authorization: None,
}),
PaymentIntentUpdate::CaptureUpdate {
status,
amount_captured,
updated_by,
} => Ok(Self {
status: Some(status),
amount_captured,
active_attempt_id: None,
prerouting_algorithm: None,
modified_at: common_utils::date_time::now(),
amount: None,
currency: None,
shipping_cost: None,
tax_details: None,
skip_external_tax_calculation: None,
surcharge_applicable: None,
surcharge_amount: None,
tax_on_surcharge: None,
routing_algorithm_id: None,
capture_method: None,
authentication_type: None,
billing_address: None,
shipping_address: None,
customer_present: None,
description: None,
return_url: None,
setup_future_usage: None,
apply_mit_exemption: None,
statement_descriptor: None,
order_details: None,
allowed_payment_method_types: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
payment_link_config: None,
request_incremental_authorization: None,
session_expiry: None,
frm_metadata: None,
request_external_three_ds_authentication: None,
updated_by,
force_3ds_challenge: None,
is_iframe_redirection_enabled: None,
enable_partial_authorization: None,
}),
PaymentIntentUpdate::SessionIntentUpdate {
prerouting_algorithm,
updated_by,
} => Ok(Self {
status: None,
active_attempt_id: None,
modified_at: common_utils::date_time::now(),
amount_captured: None,
prerouting_algorithm: Some(
prerouting_algorithm
.encode_to_value()
.attach_printable("Failed to Serialize prerouting_algorithm")?,
),
amount: None,
currency: None,
shipping_cost: None,
tax_details: None,
skip_external_tax_calculation: None,
surcharge_applicable: None,
surcharge_amount: None,
tax_on_surcharge: None,
routing_algorithm_id: None,
capture_method: None,
authentication_type: None,
billing_address: None,
shipping_address: None,
customer_present: None,
description: None,
return_url: None,
setup_future_usage: None,
apply_mit_exemption: None,
statement_descriptor: None,
order_details: None,
allowed_payment_method_types: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
payment_link_config: None,
request_incremental_authorization: None,
session_expiry: None,
frm_metadata: None,
request_external_three_ds_authentication: None,
updated_by,
force_3ds_challenge: None,
is_iframe_redirection_enabled: None,
enable_partial_authorization: None,
}),
PaymentIntentUpdate::UpdateIntent(boxed_intent) => {
let PaymentIntentUpdateFields {
amount,
currency,
shipping_cost,
tax_details,
skip_external_tax_calculation,
skip_surcharge_calculation,
surcharge_amount,
tax_on_surcharge,
routing_algorithm_id,
capture_method,
authentication_type,
billing_address,
shipping_address,
customer_present,
description,
return_url,
setup_future_usage,
apply_mit_exemption,
statement_descriptor,
order_details,
allowed_payment_method_types,
metadata,
connector_metadata,
feature_metadata,
payment_link_config,
request_incremental_authorization,
session_expiry,
frm_metadata,
request_external_three_ds_authentication,
active_attempt_id,
updated_by,
force_3ds_challenge,
is_iframe_redirection_enabled,
enable_partial_authorization,
} = *boxed_intent;
Ok(Self {
status: None,
active_attempt_id,
prerouting_algorithm: None,
modified_at: common_utils::date_time::now(),
amount_captured: None,
amount,
currency,
shipping_cost,
tax_details,
skip_external_tax_calculation: skip_external_tax_calculation
.map(|val| val.as_bool()),
surcharge_applicable: skip_surcharge_calculation.map(|val| val.as_bool()),
surcharge_amount,
tax_on_surcharge,
routing_algorithm_id,
capture_method,
authentication_type,
billing_address: billing_address.map(Encryption::from),
shipping_address: shipping_address.map(Encryption::from),
customer_present: customer_present.map(|val| val.as_bool()),
description,
return_url,
setup_future_usage,
apply_mit_exemption: apply_mit_exemption.map(|val| val.as_bool()),
statement_descriptor,
order_details,
allowed_payment_method_types: allowed_payment_method_types
.map(|allowed_payment_method_types| {
allowed_payment_method_types.encode_to_value()
})
.and_then(|r| r.ok().map(Secret::new)),
metadata,
connector_metadata,
feature_metadata,
payment_link_config,
request_incremental_authorization,
session_expiry,
frm_metadata,
request_external_three_ds_authentication:
request_external_three_ds_authentication.map(|val| val.as_bool()),
updated_by,
force_3ds_challenge,
is_iframe_redirection_enabled,
enable_partial_authorization,
})
}
PaymentIntentUpdate::RecordUpdate {
status,
feature_metadata,
updated_by,
active_attempt_id,
} => Ok(Self {
status: Some(status),
amount_captured: None,
active_attempt_id: Some(active_attempt_id),
modified_at: common_utils::date_time::now(),
amount: None,
currency: None,
shipping_cost: None,
tax_details: None,
skip_external_tax_calculation: None,
surcharge_applicable: None,
surcharge_amount: None,
tax_on_surcharge: None,
routing_algorithm_id: None,
capture_method: None,
authentication_type: None,
billing_address: None,
shipping_address: None,
customer_present: None,
description: None,
return_url: None,
setup_future_usage: None,
apply_mit_exemption: None,
statement_descriptor: None,
order_details: None,
allowed_payment_method_types: None,
metadata: None,
connector_metadata: None,
feature_metadata: *feature_metadata,
payment_link_config: None,
request_incremental_authorization: None,
prerouting_algorithm: None,
session_expiry: None,
frm_metadata: None,
request_external_three_ds_authentication: None,
updated_by,
force_3ds_challenge: None,
is_iframe_redirection_enabled: None,
enable_partial_authorization: None,
}),
PaymentIntentUpdate::VoidUpdate { status, updated_by } => Ok(Self {
status: Some(status),
amount_captured: None,
active_attempt_id: None,
prerouting_algorithm: None,
modified_at: common_utils::date_time::now(),
amount: None,
currency: None,
shipping_cost: None,
tax_details: None,
skip_external_tax_calculation: None,
surcharge_applicable: None,
surcharge_amount: None,
tax_on_surcharge: None,
routing_algorithm_id: None,
capture_method: None,
authentication_type: None,
billing_address: None,
shipping_address: None,
customer_present: None,
description: None,
return_url: None,
setup_future_usage: None,
apply_mit_exemption: None,
statement_descriptor: None,
order_details: None,
allowed_payment_method_types: None,
metadata: None,
connector_metadata: None,
feature_metadata: None,
payment_link_config: None,
request_incremental_authorization: None,
session_expiry: None,
frm_metadata: None,
request_external_three_ds_authentication: None,
updated_by,
force_3ds_challenge: None,
is_iframe_redirection_enabled: None,
enable_partial_authorization: None,
}),
}
}
}
#[cfg(feature = "v1")]
impl From<PaymentIntentUpdate> for PaymentIntentUpdateInternal {
fn from(payment_intent_update: PaymentIntentUpdate) -> Self {
match payment_intent_update {
PaymentIntentUpdate::MetadataUpdate {
metadata,
updated_by,
} => Self {
metadata: Some(metadata),
modified_at: Some(common_utils::date_time::now()),
updated_by,
..Default::default()
},
PaymentIntentUpdate::Update(value) => Self {
amount: Some(value.amount),
currency: Some(value.currency),
setup_future_usage: value.setup_future_usage,
status: Some(value.status),
customer_id: value.customer_id,
shipping_address_id: value.shipping_address_id,
billing_address_id: value.billing_address_id,
return_url: value.return_url,
business_country: value.business_country,
business_label: value.business_label,
description: value.description,
statement_descriptor_name: value.statement_descriptor_name,
statement_descriptor_suffix: value.statement_descriptor_suffix,
order_details: value.order_details,
metadata: value.metadata,
payment_confirm_source: value.payment_confirm_source,
updated_by: value.updated_by,
session_expiry: value.session_expiry,
fingerprint_id: value.fingerprint_id,
request_external_three_ds_authentication: value
.request_external_three_ds_authentication,
frm_metadata: value.frm_metadata,
customer_details: value.customer_details,
billing_details: value.billing_details,
merchant_order_reference_id: value.merchant_order_reference_id,
shipping_details: value.shipping_details,
is_payment_processor_token_flow: value.is_payment_processor_token_flow,
tax_details: value.tax_details,
tax_status: value.tax_status,
discount_amount: value.discount_amount,
order_date: value.order_date,
shipping_amount_tax: value.shipping_amount_tax,
duty_amount: value.duty_amount,
..Default::default()
},
PaymentIntentUpdate::PaymentCreateUpdate {
return_url,
status,
customer_id,
shipping_address_id,
billing_address_id,
customer_details,
updated_by,
} => Self {
return_url,
status,
customer_id,
shipping_address_id,
billing_address_id,
customer_details,
modified_at: Some(common_utils::date_time::now()),
updated_by,
..Default::default()
},
PaymentIntentUpdate::PGStatusUpdate {
status,
updated_by,
incremental_authorization_allowed,
feature_metadata,
} => Self {
status: Some(status),
modified_at: Some(common_utils::date_time::now()),
updated_by,
incremental_authorization_allowed,
feature_metadata,
..Default::default()
},
PaymentIntentUpdate::MerchantStatusUpdate {
status,
shipping_address_id,
billing_address_id,
updated_by,
} => Self {
status: Some(status),
shipping_address_id,
billing_address_id,
modified_at: Some(common_utils::date_time::now()),
updated_by,
..Default::default()
},
PaymentIntentUpdate::ResponseUpdate {
// amount,
// currency,
status,
amount_captured,
fingerprint_id,
// customer_id,
updated_by,
incremental_authorization_allowed,
feature_metadata,
} => Self {
// amount,
// currency: Some(currency),
status: Some(status),
amount_captured,
fingerprint_id,
// customer_id,
modified_at: Some(common_utils::date_time::now()),
updated_by,
incremental_authorization_allowed,
feature_metadata,
..Default::default()
},
PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate {
active_attempt_id,
attempt_count,
updated_by,
} => Self {
active_attempt_id: Some(active_attempt_id),
attempt_count: Some(attempt_count),
updated_by,
..Default::default()
},
PaymentIntentUpdate::StatusAndAttemptUpdate {
status,
active_attempt_id,
attempt_count,
updated_by,
} => Self {
status: Some(status),
active_attempt_id: Some(active_attempt_id),
attempt_count: Some(attempt_count),
updated_by,
..Default::default()
},
PaymentIntentUpdate::ApproveUpdate {
status,
merchant_decision,
updated_by,
} => Self {
status: Some(status),
merchant_decision,
updated_by,
..Default::default()
},
PaymentIntentUpdate::RejectUpdate {
status,
merchant_decision,
updated_by,
} => Self {
status: Some(status),
merchant_decision,
updated_by,
..Default::default()
},
PaymentIntentUpdate::SurchargeApplicableUpdate {
surcharge_applicable,
updated_by,
} => Self {
surcharge_applicable: Some(surcharge_applicable),
updated_by,
..Default::default()
},
PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => Self {
amount: Some(amount),
..Default::default()
},
PaymentIntentUpdate::AuthorizationCountUpdate {
authorization_count,
} => Self {
authorization_count: Some(authorization_count),
..Default::default()
},
PaymentIntentUpdate::CompleteAuthorizeUpdate {
shipping_address_id,
} => Self {
shipping_address_id,
..Default::default()
},
PaymentIntentUpdate::ManualUpdate { status, updated_by } => Self {
status,
modified_at: Some(common_utils::date_time::now()),
updated_by,
..Default::default()
},
PaymentIntentUpdate::SessionResponseUpdate {
tax_details,
shipping_address_id,
updated_by,
shipping_details,
} => Self {
tax_details: Some(tax_details),
shipping_address_id,
updated_by,
shipping_details,
..Default::default()
},
}
}
}
#[cfg(feature = "v1")]
use diesel_models::{
PaymentIntentUpdate as DieselPaymentIntentUpdate,
PaymentIntentUpdateFields as DieselPaymentIntentUpdateFields,
};
// TODO: check where this conversion is used
// #[cfg(feature = "v2")]
// impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate {
// fn from(value: PaymentIntentUpdate) -> Self {
// match value {
// PaymentIntentUpdate::ConfirmIntent { status, updated_by } => {
// Self::ConfirmIntent { status, updated_by }
// }
// PaymentIntentUpdate::ConfirmIntentPostUpdate { status, updated_by } => {
// Self::ConfirmIntentPostUpdate { status, updated_by }
// }
// }
// }
// }
#[cfg(feature = "v1")]
impl From<PaymentIntentUpdate> for DieselPaymentIntentUpdate {
fn from(value: PaymentIntentUpdate) -> Self {
match value {
PaymentIntentUpdate::ResponseUpdate {
status,
amount_captured,
fingerprint_id,
updated_by,
incremental_authorization_allowed,
feature_metadata,
} => Self::ResponseUpdate {
status,
amount_captured,
fingerprint_id,
updated_by,
incremental_authorization_allowed,
feature_metadata,
},
PaymentIntentUpdate::MetadataUpdate {
metadata,
updated_by,
} => Self::MetadataUpdate {
metadata,
updated_by,
},
PaymentIntentUpdate::Update(value) => {
Self::Update(Box::new(DieselPaymentIntentUpdateFields {
amount: value.amount,
currency: value.currency,
setup_future_usage: value.setup_future_usage,
status: value.status,
customer_id: value.customer_id,
shipping_address_id: value.shipping_address_id,
billing_address_id: value.billing_address_id,
return_url: value.return_url,
business_country: value.business_country,
business_label: value.business_label,
description: value.description,
statement_descriptor_name: value.statement_descriptor_name,
statement_descriptor_suffix: value.statement_descriptor_suffix,
order_details: value.order_details,
metadata: value.metadata,
payment_confirm_source: value.payment_confirm_source,
updated_by: value.updated_by,
session_expiry: value.session_expiry,
fingerprint_id: value.fingerprint_id,
request_external_three_ds_authentication: value
.request_external_three_ds_authentication,
frm_metadata: value.frm_metadata,
customer_details: value.customer_details.map(Encryption::from),
billing_details: value.billing_details.map(Encryption::from),
merchant_order_reference_id: value.merchant_order_reference_id,
shipping_details: value.shipping_details.map(Encryption::from),
is_payment_processor_token_flow: value.is_payment_processor_token_flow,
tax_details: value.tax_details,
force_3ds_challenge: value.force_3ds_challenge,
is_iframe_redirection_enabled: value.is_iframe_redirection_enabled,
payment_channel: value.payment_channel,
feature_metadata: value.feature_metadata,
tax_status: value.tax_status,
discount_amount: value.discount_amount,
order_date: value.order_date,
shipping_amount_tax: value.shipping_amount_tax,
duty_amount: value.duty_amount,
enable_partial_authorization: value.enable_partial_authorization,
enable_overcapture: value.enable_overcapture,
}))
}
PaymentIntentUpdate::PaymentCreateUpdate {
return_url,
status,
customer_id,
shipping_address_id,
billing_address_id,
customer_details,
updated_by,
} => Self::PaymentCreateUpdate {
return_url,
status,
customer_id,
shipping_address_id,
billing_address_id,
customer_details: customer_details.map(Encryption::from),
updated_by,
},
PaymentIntentUpdate::MerchantStatusUpdate {
status,
shipping_address_id,
billing_address_id,
updated_by,
} => Self::MerchantStatusUpdate {
status,
shipping_address_id,
billing_address_id,
updated_by,
},
PaymentIntentUpdate::PGStatusUpdate {
status,
updated_by,
incremental_authorization_allowed,
feature_metadata,
} => Self::PGStatusUpdate {
status,
updated_by,
incremental_authorization_allowed,
feature_metadata,
},
PaymentIntentUpdate::PaymentAttemptAndAttemptCountUpdate {
active_attempt_id,
attempt_count,
updated_by,
} => Self::PaymentAttemptAndAttemptCountUpdate {
active_attempt_id,
attempt_count,
updated_by,
},
PaymentIntentUpdate::StatusAndAttemptUpdate {
status,
active_attempt_id,
attempt_count,
updated_by,
} => Self::StatusAndAttemptUpdate {
status,
active_attempt_id,
attempt_count,
updated_by,
},
PaymentIntentUpdate::ApproveUpdate {
status,
merchant_decision,
updated_by,
} => Self::ApproveUpdate {
status,
merchant_decision,
updated_by,
},
PaymentIntentUpdate::RejectUpdate {
status,
merchant_decision,
updated_by,
} => Self::RejectUpdate {
status,
merchant_decision,
updated_by,
},
PaymentIntentUpdate::SurchargeApplicableUpdate {
surcharge_applicable,
updated_by,
} => Self::SurchargeApplicableUpdate {
surcharge_applicable: Some(surcharge_applicable),
updated_by,
},
PaymentIntentUpdate::IncrementalAuthorizationAmountUpdate { amount } => {
Self::IncrementalAuthorizationAmountUpdate { amount }
}
PaymentIntentUpdate::AuthorizationCountUpdate {
authorization_count,
} => Self::AuthorizationCountUpdate {
authorization_count,
},
PaymentIntentUpdate::CompleteAuthorizeUpdate {
shipping_address_id,
} => Self::CompleteAuthorizeUpdate {
shipping_address_id,
},
PaymentIntentUpdate::ManualUpdate { status, updated_by } => {
Self::ManualUpdate { status, updated_by }
}
PaymentIntentUpdate::SessionResponseUpdate {
tax_details,
shipping_address_id,
updated_by,
shipping_details,
} => Self::SessionResponseUpdate {
tax_details,
shipping_address_id,
updated_by,
shipping_details: shipping_details.map(Encryption::from),
},
}
}
}
#[cfg(feature = "v1")]
impl From<PaymentIntentUpdateInternal> for diesel_models::PaymentIntentUpdateInternal {
fn from(value: PaymentIntentUpdateInternal) -> Self {
let modified_at = common_utils::date_time::now();
let PaymentIntentUpdateInternal {
amount,
currency,
status,
amount_captured,
customer_id,
return_url,
setup_future_usage,
off_session,
metadata,
billing_address_id,
shipping_address_id,
modified_at: _,
active_attempt_id,
business_country,
business_label,
description,
statement_descriptor_name,
statement_descriptor_suffix,
order_details,
attempt_count,
merchant_decision,
payment_confirm_source,
updated_by,
surcharge_applicable,
incremental_authorization_allowed,
authorization_count,
session_expiry,
fingerprint_id,
request_external_three_ds_authentication,
frm_metadata,
customer_details,
billing_details,
merchant_order_reference_id,
shipping_details,
is_payment_processor_token_flow,
tax_details,
force_3ds_challenge,
is_iframe_redirection_enabled,
payment_channel,
feature_metadata,
tax_status,
discount_amount,
order_date,
shipping_amount_tax,
duty_amount,
enable_partial_authorization,
enable_overcapture,
} = value;
Self {
amount,
currency,
status,
amount_captured,
customer_id,
return_url: None, // deprecated
setup_future_usage,
off_session,
metadata,
billing_address_id,
shipping_address_id,
modified_at,
active_attempt_id,
business_country,
business_label,
description,
statement_descriptor_name,
statement_descriptor_suffix,
order_details,
attempt_count,
merchant_decision,
payment_confirm_source,
updated_by,
surcharge_applicable,
incremental_authorization_allowed,
authorization_count,
session_expiry,
fingerprint_id,
request_external_three_ds_authentication,
frm_metadata,
customer_details: customer_details.map(Encryption::from),
billing_details: billing_details.map(Encryption::from),
merchant_order_reference_id,
shipping_details: shipping_details.map(Encryption::from),
is_payment_processor_token_flow,
tax_details,
force_3ds_challenge,
is_iframe_redirection_enabled,
extended_return_url: return_url,
payment_channel,
feature_metadata,
tax_status,
discount_amount,
order_date,
shipping_amount_tax,
duty_amount,
enable_partial_authorization,
enable_overcapture,
}
}
}
#[cfg(feature = "v1")]
pub enum PaymentIntentFetchConstraints {
Single {
payment_intent_id: id_type::PaymentId,
},
List(Box<PaymentIntentListParams>),
}
#[cfg(feature = "v1")]
impl PaymentIntentFetchConstraints {
pub fn get_profile_id_list(&self) -> Option<Vec<id_type::ProfileId>> {
if let Self::List(pi_list_params) = self {
pi_list_params.profile_id.clone()
} else {
None
}
}
}
#[cfg(feature = "v2")]
pub enum PaymentIntentFetchConstraints {
List(Box<PaymentIntentListParams>),
}
#[cfg(feature = "v2")]
impl PaymentIntentFetchConstraints {
pub fn get_profile_id(&self) -> Option<id_type::ProfileId> {
let Self::List(pi_list_params) = self;
pi_list_params.profile_id.clone()
}
}
#[cfg(feature = "v1")]
pub struct PaymentIntentListParams {
pub offset: u32,
pub starting_at: Option<PrimitiveDateTime>,
pub ending_at: Option<PrimitiveDateTime>,
pub amount_filter: Option<api_models::payments::AmountFilter>,
pub connector: Option<Vec<api_models::enums::Connector>>,
pub currency: Option<Vec<common_enums::Currency>>,
pub status: Option<Vec<common_enums::IntentStatus>>,
pub payment_method: Option<Vec<common_enums::PaymentMethod>>,
pub payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
pub authentication_type: Option<Vec<common_enums::AuthenticationType>>,
pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
pub profile_id: Option<Vec<id_type::ProfileId>>,
pub customer_id: Option<id_type::CustomerId>,
pub starting_after_id: Option<id_type::PaymentId>,
pub ending_before_id: Option<id_type::PaymentId>,
pub limit: Option<u32>,
pub order: api_models::payments::Order,
pub card_network: Option<Vec<common_enums::CardNetwork>>,
pub card_discovery: Option<Vec<common_enums::CardDiscovery>>,
pub merchant_order_reference_id: Option<String>,
}
#[cfg(feature = "v2")]
pub struct PaymentIntentListParams {
pub offset: u32,
pub starting_at: Option<PrimitiveDateTime>,
pub ending_at: Option<PrimitiveDateTime>,
pub amount_filter: Option<api_models::payments::AmountFilter>,
pub connector: Option<Vec<api_models::enums::Connector>>,
pub currency: Option<Vec<common_enums::Currency>>,
pub status: Option<Vec<common_enums::IntentStatus>>,
pub payment_method_type: Option<Vec<common_enums::PaymentMethod>>,
pub payment_method_subtype: Option<Vec<common_enums::PaymentMethodType>>,
pub authentication_type: Option<Vec<common_enums::AuthenticationType>>,
pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
pub profile_id: Option<id_type::ProfileId>,
pub customer_id: Option<id_type::GlobalCustomerId>,
pub starting_after_id: Option<id_type::GlobalPaymentId>,
pub ending_before_id: Option<id_type::GlobalPaymentId>,
pub limit: Option<u32>,
pub order: api_models::payments::Order,
pub card_network: Option<Vec<common_enums::CardNetwork>>,
pub merchant_order_reference_id: Option<String>,
pub payment_id: Option<id_type::GlobalPaymentId>,
}
#[cfg(feature = "v1")]
impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchConstraints {
fn from(value: api_models::payments::PaymentListConstraints) -> Self {
let api_models::payments::PaymentListConstraints {
customer_id,
starting_after,
ending_before,
limit,
created,
created_lt,
created_gt,
created_lte,
created_gte,
} = value;
Self::List(Box::new(PaymentIntentListParams {
offset: 0,
starting_at: created_gte.or(created_gt).or(created),
ending_at: created_lte.or(created_lt).or(created),
amount_filter: None,
connector: None,
currency: None,
status: None,
payment_method: None,
payment_method_type: None,
authentication_type: None,
merchant_connector_id: None,
profile_id: None,
customer_id,
starting_after_id: starting_after,
ending_before_id: ending_before,
limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V1)),
order: Default::default(),
card_network: None,
card_discovery: None,
merchant_order_reference_id: None,
}))
}
}
#[cfg(feature = "v2")]
impl From<api_models::payments::PaymentListConstraints> for PaymentIntentFetchConstraints {
fn from(value: api_models::payments::PaymentListConstraints) -> Self {
let api_models::payments::PaymentListConstraints {
customer_id,
starting_after,
ending_before,
limit,
created,
created_lt,
created_gt,
created_lte,
created_gte,
payment_id,
profile_id,
start_amount,
end_amount,
connector,
currency,
status,
payment_method_type,
payment_method_subtype,
authentication_type,
merchant_connector_id,
order_on,
order_by,
card_network,
merchant_order_reference_id,
offset,
} = value;
Self::List(Box::new(PaymentIntentListParams {
offset: offset.unwrap_or_default(),
starting_at: created_gte.or(created_gt).or(created),
ending_at: created_lte.or(created_lt).or(created),
amount_filter: (start_amount.is_some() || end_amount.is_some()).then_some({
api_models::payments::AmountFilter {
start_amount,
end_amount,
}
}),
connector,
currency,
status,
payment_method_type,
payment_method_subtype,
authentication_type,
merchant_connector_id,
profile_id,
customer_id,
starting_after_id: starting_after,
ending_before_id: ending_before,
limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V1)),
order: api_models::payments::Order {
on: order_on,
by: order_by,
},
card_network,
merchant_order_reference_id,
payment_id,
}))
}
}
#[cfg(feature = "v1")]
impl From<common_utils::types::TimeRange> for PaymentIntentFetchConstraints {
fn from(value: common_utils::types::TimeRange) -> Self {
Self::List(Box::new(PaymentIntentListParams {
offset: 0,
starting_at: Some(value.start_time),
ending_at: value.end_time,
amount_filter: None,
connector: None,
currency: None,
status: None,
payment_method: None,
payment_method_type: None,
authentication_type: None,
merchant_connector_id: None,
profile_id: None,
customer_id: None,
starting_after_id: None,
ending_before_id: None,
limit: None,
order: Default::default(),
card_network: None,
card_discovery: None,
merchant_order_reference_id: None,
}))
}
}
#[cfg(feature = "v1")]
impl From<api_models::payments::PaymentListFilterConstraints> for PaymentIntentFetchConstraints {
fn from(value: api_models::payments::PaymentListFilterConstraints) -> Self {
let api_models::payments::PaymentListFilterConstraints {
payment_id,
profile_id,
customer_id,
limit,
offset,
amount_filter,
time_range,
connector,
currency,
status,
payment_method,
payment_method_type,
authentication_type,
merchant_connector_id,
order,
card_network,
card_discovery,
merchant_order_reference_id,
} = value;
if let Some(payment_intent_id) = payment_id {
Self::Single { payment_intent_id }
} else {
Self::List(Box::new(PaymentIntentListParams {
offset: offset.unwrap_or_default(),
starting_at: time_range.map(|t| t.start_time),
ending_at: time_range.and_then(|t| t.end_time),
amount_filter,
connector,
currency,
status,
payment_method,
payment_method_type,
authentication_type,
merchant_connector_id,
profile_id: profile_id.map(|profile_id| vec![profile_id]),
customer_id,
starting_after_id: None,
ending_before_id: None,
limit: Some(std::cmp::min(limit, PAYMENTS_LIST_MAX_LIMIT_V2)),
order,
card_network,
card_discovery,
merchant_order_reference_id,
}))
}
}
}
#[cfg(feature = "v1")]
impl<T> TryFrom<(T, Option<Vec<id_type::ProfileId>>)> for PaymentIntentFetchConstraints
where
Self: From<T>,
{
type Error = error_stack::Report<errors::api_error_response::ApiErrorResponse>;
fn try_from(
(constraints, auth_profile_id_list): (T, Option<Vec<id_type::ProfileId>>),
) -> Result<Self, Self::Error> {
let payment_intent_constraints = Self::from(constraints);
if let Self::List(mut pi_list_params) = payment_intent_constraints {
let profile_id_from_request_body = pi_list_params.profile_id;
match (profile_id_from_request_body, auth_profile_id_list) {
(None, None) => pi_list_params.profile_id = None,
(None, Some(auth_profile_id_list)) => {
pi_list_params.profile_id = Some(auth_profile_id_list)
}
(Some(profile_id_from_request_body), None) => {
pi_list_params.profile_id = Some(profile_id_from_request_body)
}
(Some(profile_id_from_request_body), Some(auth_profile_id_list)) => {
let profile_id_from_request_body_is_available_in_auth_profile_id_list =
profile_id_from_request_body
.iter()
.all(|profile_id| auth_profile_id_list.contains(profile_id));
if profile_id_from_request_body_is_available_in_auth_profile_id_list {
pi_list_params.profile_id = Some(profile_id_from_request_body)
} else {
// This scenario is very unlikely to happen
let inaccessible_profile_ids: Vec<_> = profile_id_from_request_body
.iter()
.filter(|profile_id| !auth_profile_id_list.contains(profile_id))
.collect();
return Err(error_stack::Report::new(
errors::api_error_response::ApiErrorResponse::PreconditionFailed {
message: format!(
"Access not available for the given profile_id {inaccessible_profile_ids:?}",
),
},
));
}
}
}
Ok(Self::List(pi_list_params))
} else {
Ok(payment_intent_constraints)
}
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl behaviour::Conversion for PaymentIntent {
type DstType = DieselPaymentIntent;
type NewDstType = DieselPaymentIntentNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
let Self {
merchant_id,
amount_details,
status,
amount_captured,
customer_id,
description,
return_url,
metadata,
statement_descriptor,
created_at,
modified_at,
last_synced,
setup_future_usage,
active_attempt_id,
active_attempt_id_type,
active_attempts_group_id,
order_details,
allowed_payment_method_types,
connector_metadata,
feature_metadata,
attempt_count,
profile_id,
payment_link_id,
frm_merchant_decision,
updated_by,
request_incremental_authorization,
split_txns_enabled,
authorization_count,
session_expiry,
request_external_three_ds_authentication,
frm_metadata,
customer_details,
merchant_reference_id,
billing_address,
shipping_address,
capture_method,
id,
authentication_type,
prerouting_algorithm,
organization_id,
enable_payment_link,
apply_mit_exemption,
customer_present,
routing_algorithm_id,
payment_link_config,
split_payments,
force_3ds_challenge,
force_3ds_challenge_trigger,
processor_merchant_id,
created_by,
is_iframe_redirection_enabled,
is_payment_id_from_merchant,
enable_partial_authorization,
} = self;
Ok(DieselPaymentIntent {
skip_external_tax_calculation: Some(amount_details.get_external_tax_action_as_bool()),
surcharge_applicable: Some(amount_details.get_surcharge_action_as_bool()),
merchant_id,
status,
amount: amount_details.order_amount,
currency: amount_details.currency,
amount_captured,
customer_id,
description,
return_url,
metadata,
statement_descriptor,
created_at,
modified_at,
last_synced,
setup_future_usage: Some(setup_future_usage),
active_attempt_id,
active_attempt_id_type: Some(active_attempt_id_type),
active_attempts_group_id,
order_details: order_details.map(|order_details| {
order_details
.into_iter()
.map(|order_detail| Secret::new(order_detail.expose()))
.collect::<Vec<_>>()
}),
allowed_payment_method_types: allowed_payment_method_types
.map(|allowed_payment_method_types| {
allowed_payment_method_types
.encode_to_value()
.change_context(ValidationError::InvalidValue {
message: "Failed to serialize allowed_payment_method_types".to_string(),
})
})
.transpose()?
.map(Secret::new),
connector_metadata: connector_metadata
.map(|cm| {
cm.encode_to_value()
.change_context(ValidationError::InvalidValue {
message: "Failed to serialize connector_metadata".to_string(),
})
})
.transpose()?
.map(Secret::new),
feature_metadata,
attempt_count,
profile_id,
frm_merchant_decision,
payment_link_id,
updated_by,
request_incremental_authorization: Some(request_incremental_authorization),
split_txns_enabled: Some(split_txns_enabled),
authorization_count,
session_expiry,
request_external_three_ds_authentication: Some(
request_external_three_ds_authentication.as_bool(),
),
frm_metadata,
customer_details: customer_details.map(Encryption::from),
billing_address: billing_address.map(Encryption::from),
shipping_address: shipping_address.map(Encryption::from),
capture_method: Some(capture_method),
id,
authentication_type,
prerouting_algorithm: prerouting_algorithm
.map(|prerouting_algorithm| {
prerouting_algorithm.encode_to_value().change_context(
ValidationError::InvalidValue {
message: "Failed to serialize prerouting_algorithm".to_string(),
},
)
})
.transpose()?,
merchant_reference_id,
surcharge_amount: amount_details.surcharge_amount,
tax_on_surcharge: amount_details.tax_on_surcharge,
organization_id,
shipping_cost: amount_details.shipping_cost,
tax_details: amount_details.tax_details,
enable_payment_link: Some(enable_payment_link.as_bool()),
apply_mit_exemption: Some(apply_mit_exemption.as_bool()),
customer_present: Some(customer_present.as_bool()),
payment_link_config,
routing_algorithm_id,
psd2_sca_exemption_type: None,
request_extended_authorization: None,
platform_merchant_id: None,
split_payments,
force_3ds_challenge,
force_3ds_challenge_trigger,
processor_merchant_id: Some(processor_merchant_id),
created_by: created_by.map(|cb| cb.to_string()),
is_iframe_redirection_enabled,
is_payment_id_from_merchant,
payment_channel: None,
tax_status: None,
discount_amount: None,
shipping_amount_tax: None,
duty_amount: None,
order_date: None,
enable_partial_authorization,
enable_overcapture: None,
mit_category: None,
})
}
async fn convert_back(
state: &KeyManagerState,
storage_model: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
async {
let decrypted_data = crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::BatchDecrypt(super::EncryptedPaymentIntent::to_encryptable(
super::EncryptedPaymentIntent {
billing_address: storage_model.billing_address,
shipping_address: storage_model.shipping_address,
customer_details: storage_model.customer_details,
},
)),
key_manager_identifier,
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())?;
let data = super::EncryptedPaymentIntent::from_encryptable(decrypted_data)
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Invalid batch operation data")?;
let amount_details = super::AmountDetails {
order_amount: storage_model.amount,
currency: storage_model.currency,
surcharge_amount: storage_model.surcharge_amount,
tax_on_surcharge: storage_model.tax_on_surcharge,
shipping_cost: storage_model.shipping_cost,
tax_details: storage_model.tax_details,
skip_external_tax_calculation: common_enums::TaxCalculationOverride::from(
storage_model.skip_external_tax_calculation,
),
skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::from(
storage_model.surcharge_applicable,
),
amount_captured: storage_model.amount_captured,
};
let billing_address = data
.billing_address
.map(|billing| {
billing.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing Address")?;
let shipping_address = data
.shipping_address
.map(|shipping| {
shipping.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Error while deserializing Address")?;
let allowed_payment_method_types = storage_model
.allowed_payment_method_types
.map(|allowed_payment_method_types| {
allowed_payment_method_types.parse_value("Vec<PaymentMethodType>")
})
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)?;
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
merchant_id: storage_model.merchant_id.clone(),
status: storage_model.status,
amount_details,
amount_captured: storage_model.amount_captured,
customer_id: storage_model.customer_id,
description: storage_model.description,
return_url: storage_model.return_url,
metadata: storage_model.metadata,
statement_descriptor: storage_model.statement_descriptor,
created_at: storage_model.created_at,
modified_at: storage_model.modified_at,
last_synced: storage_model.last_synced,
setup_future_usage: storage_model.setup_future_usage.unwrap_or_default(),
active_attempt_id: storage_model.active_attempt_id,
active_attempt_id_type: storage_model.active_attempt_id_type.unwrap_or_default(),
active_attempts_group_id: storage_model.active_attempts_group_id,
order_details: storage_model.order_details.map(|order_details| {
order_details
.into_iter()
.map(|order_detail| Secret::new(order_detail.expose()))
.collect::<Vec<_>>()
}),
allowed_payment_method_types,
connector_metadata: storage_model
.connector_metadata
.map(|cm| cm.parse_value("ConnectorMetadata"))
.transpose()
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Failed to deserialize connector_metadata")?,
feature_metadata: storage_model.feature_metadata,
attempt_count: storage_model.attempt_count,
profile_id: storage_model.profile_id,
frm_merchant_decision: storage_model.frm_merchant_decision,
payment_link_id: storage_model.payment_link_id,
updated_by: storage_model.updated_by,
request_incremental_authorization: storage_model
.request_incremental_authorization
.unwrap_or_default(),
split_txns_enabled: storage_model.split_txns_enabled.unwrap_or_default(),
authorization_count: storage_model.authorization_count,
session_expiry: storage_model.session_expiry,
request_external_three_ds_authentication: storage_model
.request_external_three_ds_authentication
.into(),
frm_metadata: storage_model.frm_metadata,
customer_details: data.customer_details,
billing_address,
shipping_address,
capture_method: storage_model.capture_method.unwrap_or_default(),
id: storage_model.id,
merchant_reference_id: storage_model.merchant_reference_id,
organization_id: storage_model.organization_id,
authentication_type: storage_model.authentication_type,
prerouting_algorithm: storage_model
.prerouting_algorithm
.map(|prerouting_algorithm_value| {
prerouting_algorithm_value
.parse_value("PaymentRoutingInfo")
.change_context(common_utils::errors::CryptoError::DecodingFailed)
})
.transpose()?,
enable_payment_link: storage_model.enable_payment_link.into(),
apply_mit_exemption: storage_model.apply_mit_exemption.into(),
customer_present: storage_model.customer_present.into(),
payment_link_config: storage_model.payment_link_config,
routing_algorithm_id: storage_model.routing_algorithm_id,
split_payments: storage_model.split_payments,
force_3ds_challenge: storage_model.force_3ds_challenge,
force_3ds_challenge_trigger: storage_model.force_3ds_challenge_trigger,
processor_merchant_id: storage_model
.processor_merchant_id
.unwrap_or(storage_model.merchant_id),
created_by: storage_model
.created_by
.and_then(|created_by| created_by.parse::<CreatedBy>().ok()),
is_iframe_redirection_enabled: storage_model.is_iframe_redirection_enabled,
is_payment_id_from_merchant: storage_model.is_payment_id_from_merchant,
enable_partial_authorization: storage_model.enable_partial_authorization,
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting payment intent".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let amount_details = self.amount_details;
Ok(DieselPaymentIntentNew {
surcharge_applicable: Some(amount_details.get_surcharge_action_as_bool()),
skip_external_tax_calculation: Some(amount_details.get_external_tax_action_as_bool()),
merchant_id: self.merchant_id,
status: self.status,
amount: amount_details.order_amount,
currency: amount_details.currency,
amount_captured: self.amount_captured,
customer_id: self.customer_id,
description: self.description,
return_url: self.return_url,
metadata: self.metadata,
statement_descriptor: self.statement_descriptor,
created_at: self.created_at,
modified_at: self.modified_at,
last_synced: self.last_synced,
setup_future_usage: Some(self.setup_future_usage),
active_attempt_id: self.active_attempt_id,
order_details: self.order_details,
allowed_payment_method_types: self
.allowed_payment_method_types
.map(|allowed_payment_method_types| {
allowed_payment_method_types
.encode_to_value()
.change_context(ValidationError::InvalidValue {
message: "Failed to serialize allowed_payment_method_types".to_string(),
})
})
.transpose()?
.map(Secret::new),
connector_metadata: self
.connector_metadata
.map(|cm| {
cm.encode_to_value()
.change_context(ValidationError::InvalidValue {
message: "Failed to serialize connector_metadata".to_string(),
})
})
.transpose()?
.map(Secret::new),
feature_metadata: self.feature_metadata,
attempt_count: self.attempt_count,
profile_id: self.profile_id,
frm_merchant_decision: self.frm_merchant_decision,
payment_link_id: self.payment_link_id,
updated_by: self.updated_by,
request_incremental_authorization: Some(self.request_incremental_authorization),
split_txns_enabled: Some(self.split_txns_enabled),
authorization_count: self.authorization_count,
session_expiry: self.session_expiry,
request_external_three_ds_authentication: Some(
self.request_external_three_ds_authentication.as_bool(),
),
frm_metadata: self.frm_metadata,
customer_details: self.customer_details.map(Encryption::from),
billing_address: self.billing_address.map(Encryption::from),
shipping_address: self.shipping_address.map(Encryption::from),
capture_method: Some(self.capture_method),
id: self.id,
merchant_reference_id: self.merchant_reference_id,
authentication_type: self.authentication_type,
prerouting_algorithm: self
.prerouting_algorithm
.map(|prerouting_algorithm| {
prerouting_algorithm.encode_to_value().change_context(
ValidationError::InvalidValue {
message: "Failed to serialize prerouting_algorithm".to_string(),
},
)
})
.transpose()?,
surcharge_amount: amount_details.surcharge_amount,
tax_on_surcharge: amount_details.tax_on_surcharge,
organization_id: self.organization_id,
shipping_cost: amount_details.shipping_cost,
tax_details: amount_details.tax_details,
enable_payment_link: Some(self.enable_payment_link.as_bool()),
apply_mit_exemption: Some(self.apply_mit_exemption.as_bool()),
platform_merchant_id: None,
force_3ds_challenge: self.force_3ds_challenge,
force_3ds_challenge_trigger: self.force_3ds_challenge_trigger,
processor_merchant_id: Some(self.processor_merchant_id),
created_by: self.created_by.map(|cb| cb.to_string()),
is_iframe_redirection_enabled: self.is_iframe_redirection_enabled,
routing_algorithm_id: self.routing_algorithm_id,
is_payment_id_from_merchant: self.is_payment_id_from_merchant,
payment_channel: None,
tax_status: None,
discount_amount: None,
mit_category: None,
shipping_amount_tax: None,
duty_amount: None,
order_date: None,
enable_partial_authorization: self.enable_partial_authorization,
})
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl behaviour::Conversion for PaymentIntent {
type DstType = DieselPaymentIntent;
type NewDstType = DieselPaymentIntentNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(DieselPaymentIntent {
payment_id: self.payment_id,
merchant_id: self.merchant_id,
status: self.status,
amount: self.amount,
currency: self.currency,
amount_captured: self.amount_captured,
customer_id: self.customer_id,
description: self.description,
return_url: None, // deprecated
metadata: self.metadata,
connector_id: self.connector_id,
shipping_address_id: self.shipping_address_id,
billing_address_id: self.billing_address_id,
statement_descriptor_name: self.statement_descriptor_name,
statement_descriptor_suffix: self.statement_descriptor_suffix,
created_at: self.created_at,
modified_at: self.modified_at,
last_synced: self.last_synced,
setup_future_usage: self.setup_future_usage,
off_session: self.off_session,
client_secret: self.client_secret,
active_attempt_id: self.active_attempt.get_id(),
business_country: self.business_country,
business_label: self.business_label,
order_details: self.order_details,
allowed_payment_method_types: self.allowed_payment_method_types,
connector_metadata: self.connector_metadata,
feature_metadata: self.feature_metadata,
attempt_count: self.attempt_count,
profile_id: self.profile_id,
merchant_decision: self.merchant_decision,
payment_link_id: self.payment_link_id,
payment_confirm_source: self.payment_confirm_source,
updated_by: self.updated_by,
surcharge_applicable: self.surcharge_applicable,
request_incremental_authorization: self.request_incremental_authorization,
incremental_authorization_allowed: self.incremental_authorization_allowed,
authorization_count: self.authorization_count,
fingerprint_id: self.fingerprint_id,
session_expiry: self.session_expiry,
request_external_three_ds_authentication: self.request_external_three_ds_authentication,
charges: None,
split_payments: self.split_payments,
frm_metadata: self.frm_metadata,
customer_details: self.customer_details.map(Encryption::from),
billing_details: self.billing_details.map(Encryption::from),
merchant_order_reference_id: self.merchant_order_reference_id,
shipping_details: self.shipping_details.map(Encryption::from),
is_payment_processor_token_flow: self.is_payment_processor_token_flow,
organization_id: self.organization_id,
shipping_cost: self.shipping_cost,
tax_details: self.tax_details,
skip_external_tax_calculation: self.skip_external_tax_calculation,
request_extended_authorization: self.request_extended_authorization,
psd2_sca_exemption_type: self.psd2_sca_exemption_type,
platform_merchant_id: None,
processor_merchant_id: Some(self.processor_merchant_id),
created_by: self.created_by.map(|cb| cb.to_string()),
force_3ds_challenge: self.force_3ds_challenge,
force_3ds_challenge_trigger: self.force_3ds_challenge_trigger,
is_iframe_redirection_enabled: self.is_iframe_redirection_enabled,
extended_return_url: self.return_url,
is_payment_id_from_merchant: self.is_payment_id_from_merchant,
payment_channel: self.payment_channel,
tax_status: self.tax_status,
discount_amount: self.discount_amount,
order_date: self.order_date,
shipping_amount_tax: self.shipping_amount_tax,
duty_amount: self.duty_amount,
enable_partial_authorization: self.enable_partial_authorization,
enable_overcapture: self.enable_overcapture,
mit_category: self.mit_category,
})
}
async fn convert_back(
state: &KeyManagerState,
storage_model: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
async {
let decrypted_data = crypto_operation(
state,
type_name!(Self::DstType),
CryptoOperation::BatchDecrypt(super::EncryptedPaymentIntent::to_encryptable(
super::EncryptedPaymentIntent {
billing_details: storage_model.billing_details,
shipping_details: storage_model.shipping_details,
customer_details: storage_model.customer_details,
},
)),
key_manager_identifier,
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())?;
let data = super::EncryptedPaymentIntent::from_encryptable(decrypted_data)
.change_context(common_utils::errors::CryptoError::DecodingFailed)
.attach_printable("Invalid batch operation data")?;
Ok::<Self, error_stack::Report<common_utils::errors::CryptoError>>(Self {
payment_id: storage_model.payment_id,
merchant_id: storage_model.merchant_id.clone(),
status: storage_model.status,
amount: storage_model.amount,
currency: storage_model.currency,
amount_captured: storage_model.amount_captured,
customer_id: storage_model.customer_id,
description: storage_model.description,
return_url: storage_model
.extended_return_url
.or(storage_model.return_url), // fallback to legacy
metadata: storage_model.metadata,
connector_id: storage_model.connector_id,
shipping_address_id: storage_model.shipping_address_id,
billing_address_id: storage_model.billing_address_id,
statement_descriptor_name: storage_model.statement_descriptor_name,
statement_descriptor_suffix: storage_model.statement_descriptor_suffix,
created_at: storage_model.created_at,
modified_at: storage_model.modified_at,
last_synced: storage_model.last_synced,
setup_future_usage: storage_model.setup_future_usage,
off_session: storage_model.off_session,
client_secret: storage_model.client_secret,
active_attempt: RemoteStorageObject::ForeignID(storage_model.active_attempt_id),
business_country: storage_model.business_country,
business_label: storage_model.business_label,
order_details: storage_model.order_details,
allowed_payment_method_types: storage_model.allowed_payment_method_types,
connector_metadata: storage_model.connector_metadata,
feature_metadata: storage_model.feature_metadata,
attempt_count: storage_model.attempt_count,
profile_id: storage_model.profile_id,
merchant_decision: storage_model.merchant_decision,
payment_link_id: storage_model.payment_link_id,
payment_confirm_source: storage_model.payment_confirm_source,
updated_by: storage_model.updated_by,
surcharge_applicable: storage_model.surcharge_applicable,
request_incremental_authorization: storage_model.request_incremental_authorization,
incremental_authorization_allowed: storage_model.incremental_authorization_allowed,
authorization_count: storage_model.authorization_count,
fingerprint_id: storage_model.fingerprint_id,
session_expiry: storage_model.session_expiry,
request_external_three_ds_authentication: storage_model
.request_external_three_ds_authentication,
split_payments: storage_model.split_payments,
frm_metadata: storage_model.frm_metadata,
shipping_cost: storage_model.shipping_cost,
tax_details: storage_model.tax_details,
customer_details: data.customer_details,
billing_details: data.billing_details,
merchant_order_reference_id: storage_model.merchant_order_reference_id,
shipping_details: data.shipping_details,
is_payment_processor_token_flow: storage_model.is_payment_processor_token_flow,
organization_id: storage_model.organization_id,
skip_external_tax_calculation: storage_model.skip_external_tax_calculation,
request_extended_authorization: storage_model.request_extended_authorization,
psd2_sca_exemption_type: storage_model.psd2_sca_exemption_type,
processor_merchant_id: storage_model
.processor_merchant_id
.unwrap_or(storage_model.merchant_id),
created_by: storage_model
.created_by
.and_then(|created_by| created_by.parse::<CreatedBy>().ok()),
force_3ds_challenge: storage_model.force_3ds_challenge,
force_3ds_challenge_trigger: storage_model.force_3ds_challenge_trigger,
is_iframe_redirection_enabled: storage_model.is_iframe_redirection_enabled,
is_payment_id_from_merchant: storage_model.is_payment_id_from_merchant,
payment_channel: storage_model.payment_channel,
tax_status: storage_model.tax_status,
discount_amount: storage_model.discount_amount,
shipping_amount_tax: storage_model.shipping_amount_tax,
duty_amount: storage_model.duty_amount,
order_date: storage_model.order_date,
enable_partial_authorization: storage_model.enable_partial_authorization,
enable_overcapture: storage_model.enable_overcapture,
mit_category: storage_model.mit_category,
})
}
.await
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting payment intent".to_string(),
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
Ok(DieselPaymentIntentNew {
payment_id: self.payment_id,
merchant_id: self.merchant_id,
status: self.status,
amount: self.amount,
currency: self.currency,
amount_captured: self.amount_captured,
customer_id: self.customer_id,
description: self.description,
return_url: None, // deprecated
metadata: self.metadata,
connector_id: self.connector_id,
shipping_address_id: self.shipping_address_id,
billing_address_id: self.billing_address_id,
statement_descriptor_name: self.statement_descriptor_name,
statement_descriptor_suffix: self.statement_descriptor_suffix,
created_at: self.created_at,
modified_at: self.modified_at,
last_synced: self.last_synced,
setup_future_usage: self.setup_future_usage,
off_session: self.off_session,
client_secret: self.client_secret,
active_attempt_id: self.active_attempt.get_id(),
business_country: self.business_country,
business_label: self.business_label,
order_details: self.order_details,
allowed_payment_method_types: self.allowed_payment_method_types,
connector_metadata: self.connector_metadata,
feature_metadata: self.feature_metadata,
attempt_count: self.attempt_count,
profile_id: self.profile_id,
merchant_decision: self.merchant_decision,
payment_link_id: self.payment_link_id,
payment_confirm_source: self.payment_confirm_source,
updated_by: self.updated_by,
surcharge_applicable: self.surcharge_applicable,
request_incremental_authorization: self.request_incremental_authorization,
incremental_authorization_allowed: self.incremental_authorization_allowed,
authorization_count: self.authorization_count,
fingerprint_id: self.fingerprint_id,
session_expiry: self.session_expiry,
request_external_three_ds_authentication: self.request_external_three_ds_authentication,
charges: None,
split_payments: self.split_payments,
frm_metadata: self.frm_metadata,
customer_details: self.customer_details.map(Encryption::from),
billing_details: self.billing_details.map(Encryption::from),
merchant_order_reference_id: self.merchant_order_reference_id,
shipping_details: self.shipping_details.map(Encryption::from),
is_payment_processor_token_flow: self.is_payment_processor_token_flow,
organization_id: self.organization_id,
shipping_cost: self.shipping_cost,
tax_details: self.tax_details,
skip_external_tax_calculation: self.skip_external_tax_calculation,
request_extended_authorization: self.request_extended_authorization,
psd2_sca_exemption_type: self.psd2_sca_exemption_type,
platform_merchant_id: None,
processor_merchant_id: Some(self.processor_merchant_id),
created_by: self.created_by.map(|cb| cb.to_string()),
force_3ds_challenge: self.force_3ds_challenge,
force_3ds_challenge_trigger: self.force_3ds_challenge_trigger,
is_iframe_redirection_enabled: self.is_iframe_redirection_enabled,
extended_return_url: self.return_url,
is_payment_id_from_merchant: self.is_payment_id_from_merchant,
payment_channel: self.payment_channel,
tax_status: self.tax_status,
discount_amount: self.discount_amount,
order_date: self.order_date,
shipping_amount_tax: self.shipping_amount_tax,
duty_amount: self.duty_amount,
enable_partial_authorization: self.enable_partial_authorization,
enable_overcapture: self.enable_overcapture,
mit_category: self.mit_category,
})
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/payments/payment_intent.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 4,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-4318913115260174162
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs
// Contains: 5 structs, 1 enums
use api_models::payments::Address;
use common_utils::id_type;
use crate::connector_endpoints;
#[derive(Debug, Clone)]
pub struct SubscriptionItem {
pub item_price_id: String,
pub quantity: Option<u32>,
}
#[derive(Debug, Clone)]
pub struct SubscriptionCreateRequest {
pub customer_id: id_type::CustomerId,
pub subscription_id: id_type::SubscriptionId,
pub subscription_items: Vec<SubscriptionItem>,
pub billing_address: Address,
pub auto_collection: SubscriptionAutoCollection,
pub connector_params: connector_endpoints::ConnectorParams,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SubscriptionAutoCollection {
On,
Off,
}
#[derive(Debug, Clone)]
pub struct GetSubscriptionPlansRequest {
pub limit: Option<u32>,
pub offset: Option<u32>,
}
impl GetSubscriptionPlansRequest {
pub fn new(limit: Option<u32>, offset: Option<u32>) -> Self {
Self { limit, offset }
}
}
impl Default for GetSubscriptionPlansRequest {
fn default() -> Self {
Self {
limit: Some(10),
offset: Some(0),
}
}
}
#[derive(Debug, Clone)]
pub struct GetSubscriptionPlanPricesRequest {
pub plan_price_id: String,
}
#[derive(Debug, Clone)]
pub struct GetSubscriptionEstimateRequest {
pub price_id: String,
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 5,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_6057721076325418417
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
// Contains: 10 structs, 2 enums
use api_models;
use common_enums;
use common_utils::{
events::{ApiEventMetric, ApiEventsType},
pii::Email,
};
use diesel_models::types::OrderDetailsWithAmount;
use masking::Secret;
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::router_request_types;
#[derive(Debug, Clone)]
pub struct FraudCheckSaleData {
pub amount: i64,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub currency: Option<common_enums::Currency>,
pub email: Option<Email>,
}
#[derive(Debug, Clone)]
pub struct FraudCheckCheckoutData {
pub amount: i64,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub currency: Option<common_enums::Currency>,
pub browser_info: Option<router_request_types::BrowserInformation>,
pub payment_method_data: Option<api_models::payments::AdditionalPaymentData>,
pub email: Option<Email>,
pub gateway: Option<String>,
}
#[derive(Debug, Clone)]
pub struct FraudCheckTransactionData {
pub amount: i64,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub currency: Option<common_enums::Currency>,
pub payment_method: Option<common_enums::PaymentMethod>,
pub error_code: Option<String>,
pub error_message: Option<String>,
pub connector_transaction_id: Option<String>,
//The name of the payment gateway or financial institution that processed the transaction.
pub connector: Option<String>,
}
#[derive(Debug, Clone)]
pub struct FraudCheckRecordReturnData {
pub amount: i64,
pub currency: Option<common_enums::Currency>,
pub refund_method: RefundMethod,
pub refund_transaction_id: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum RefundMethod {
StoreCredit,
OriginalPaymentInstrument,
NewPaymentInstrument,
}
#[derive(Debug, Clone)]
pub struct FraudCheckFulfillmentData {
pub amount: i64,
pub order_details: Option<Vec<Secret<serde_json::Value>>>,
pub fulfillment_req: FrmFulfillmentRequest,
}
#[derive(Debug, Deserialize, Serialize, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "snake_case")]
pub struct FrmFulfillmentRequest {
///unique payment_id for the transaction
#[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
pub payment_id: common_utils::id_type::PaymentId,
///unique order_id for the order_details in the transaction
#[schema(max_length = 255, example = "pay_qiYfHcDou1ycIaxVXKHF")]
pub order_id: String,
///denotes the status of the fulfillment... can be one of PARTIAL, COMPLETE, REPLACEMENT, CANCELED
#[schema(value_type = Option<FulfillmentStatus>, example = "COMPLETE")]
pub fulfillment_status: Option<FulfillmentStatus>,
///contains details of the fulfillment
#[schema(value_type = Vec<Fulfillments>)]
pub fulfillments: Vec<Fulfillments>,
//name of the tracking Company
#[schema(max_length = 255, example = "fedex")]
pub tracking_company: Option<String>,
//tracking ID of the product
#[schema(example = r#"["track_8327446667", "track_8327446668"]"#)]
pub tracking_numbers: Option<Vec<String>>,
//tracking_url for tracking the product
pub tracking_urls: Option<Vec<String>>,
// The name of the Shipper.
pub carrier: Option<String>,
// Fulfillment method for the shipment.
pub fulfillment_method: Option<String>,
// Statuses to indicate shipment state.
pub shipment_status: Option<String>,
// The date and time items are ready to be shipped.
pub shipped_at: Option<String>,
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "snake_case")]
pub struct Fulfillments {
///shipment_id of the shipped items
#[schema(max_length = 255, example = "ship_101")]
pub shipment_id: String,
///products sent in the shipment
#[schema(value_type = Option<Vec<Product>>)]
pub products: Option<Vec<Product>>,
///destination address of the shipment
#[schema(value_type = Destination)]
pub destination: Destination,
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde(untagged)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "snake_case")]
pub enum FulfillmentStatus {
PARTIAL,
COMPLETE,
REPLACEMENT,
CANCELED,
}
#[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "snake_case")]
pub struct Product {
pub item_name: String,
pub item_quantity: i64,
pub item_id: String,
}
#[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "snake_case")]
pub struct Destination {
pub full_name: Secret<String>,
pub organization: Option<String>,
pub email: Option<Email>,
pub address: Address,
}
#[derive(Debug, Serialize, Eq, PartialEq, Deserialize, Clone)]
#[serde_with::skip_serializing_none]
#[serde(rename_all = "snake_case")]
pub struct Address {
pub street_address: Secret<String>,
pub unit: Option<Secret<String>>,
pub postal_code: Secret<String>,
pub city: String,
pub province_code: Secret<String>,
pub country_code: common_enums::CountryAlpha2,
}
impl ApiEventMetric for FrmFulfillmentRequest {
fn get_api_event_type(&self) -> Option<ApiEventsType> {
Some(ApiEventsType::FraudCheck)
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 10,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-3978897963357548038
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs
// Contains: 16 structs, 1 enums
use api_models::payments::DeviceChannel;
use common_enums::MerchantCategoryCode;
use common_types::payments::MerchantCountryCode;
use common_utils::types::MinorUnit;
use masking::Secret;
use crate::address::Address;
#[derive(Clone, Debug)]
pub struct UasPreAuthenticationRequestData {
pub service_details: Option<CtpServiceDetails>,
pub transaction_details: Option<TransactionDetails>,
pub payment_details: Option<PaymentDetails>,
pub authentication_info: Option<AuthenticationInfo>,
pub merchant_details: Option<MerchantDetails>,
pub billing_address: Option<Address>,
pub acquirer_bin: Option<String>,
pub acquirer_merchant_id: Option<String>,
}
#[derive(Debug, Clone)]
pub struct MerchantDetails {
pub merchant_id: Option<String>,
pub merchant_name: Option<String>,
pub merchant_category_code: Option<MerchantCategoryCode>,
pub merchant_country_code: Option<MerchantCountryCode>,
pub endpoint_prefix: Option<String>,
pub three_ds_requestor_url: Option<String>,
pub three_ds_requestor_id: Option<String>,
pub three_ds_requestor_name: Option<String>,
pub notification_url: Option<url::Url>,
}
#[derive(Clone, Debug, PartialEq, serde::Serialize)]
pub struct AuthenticationInfo {
pub authentication_type: Option<String>,
pub authentication_reasons: Option<Vec<String>>,
pub consent_received: bool,
pub is_authenticated: bool,
pub locale: Option<String>,
pub supported_card_brands: Option<String>,
pub encrypted_payload: Option<Secret<String>>,
}
#[derive(Clone, Debug)]
pub struct UasAuthenticationRequestData {
pub browser_details: Option<super::BrowserInformation>,
pub transaction_details: TransactionDetails,
pub pre_authentication_data: super::authentication::PreAuthenticationData,
pub return_url: Option<String>,
pub sdk_information: Option<api_models::payments::SdkInformation>,
pub email: Option<common_utils::pii::Email>,
pub threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator,
pub webhook_url: String,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct CtpServiceDetails {
pub service_session_ids: Option<ServiceSessionIds>,
pub payment_details: Option<PaymentDetails>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct PaymentDetails {
pub pan: cards::CardNumber,
pub digital_card_id: Option<String>,
pub payment_data_type: Option<common_enums::PaymentMethodType>,
pub encrypted_src_card_details: Option<String>,
pub card_expiry_month: Secret<String>,
pub card_expiry_year: Secret<String>,
pub cardholder_name: Option<Secret<String>>,
pub card_token_number: Option<Secret<String>>,
pub account_type: Option<common_enums::PaymentMethodType>,
pub card_cvc: Option<Secret<String>>,
}
#[derive(Clone, serde::Deserialize, Debug, serde::Serialize)]
pub struct ServiceSessionIds {
pub correlation_id: Option<String>,
pub merchant_transaction_id: Option<String>,
pub x_src_flow_id: Option<String>,
}
#[derive(Debug, serde::Serialize, serde::Deserialize, Clone)]
pub struct TransactionDetails {
pub amount: Option<MinorUnit>,
pub currency: Option<common_enums::Currency>,
pub device_channel: Option<DeviceChannel>,
pub message_category: Option<super::authentication::MessageCategory>,
}
#[derive(Clone, Debug)]
pub struct UasPostAuthenticationRequestData {
pub threeds_server_transaction_id: Option<String>,
}
#[derive(Debug, Clone)]
pub enum UasAuthenticationResponseData {
PreAuthentication {
authentication_details: PreAuthenticationDetails,
},
Authentication {
authentication_details: AuthenticationDetails,
},
PostAuthentication {
authentication_details: PostAuthenticationDetails,
},
Confirmation {},
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct PreAuthenticationDetails {
pub threeds_server_transaction_id: Option<String>,
pub maximum_supported_3ds_version: Option<common_utils::types::SemanticVersion>,
pub connector_authentication_id: Option<String>,
pub three_ds_method_data: Option<String>,
pub three_ds_method_url: Option<String>,
pub message_version: Option<common_utils::types::SemanticVersion>,
pub connector_metadata: Option<serde_json::Value>,
pub directory_server_id: Option<String>,
}
#[derive(Debug, Clone)]
pub struct AuthenticationDetails {
pub authn_flow_type: super::authentication::AuthNFlowType,
pub authentication_value: Option<Secret<String>>,
pub trans_status: common_enums::TransactionStatus,
pub connector_metadata: Option<serde_json::Value>,
pub ds_trans_id: Option<String>,
pub eci: Option<String>,
pub challenge_code: Option<String>,
pub challenge_cancel: Option<String>,
pub challenge_code_reason: Option<String>,
pub message_extension: Option<common_utils::pii::SecretSerdeValue>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct PostAuthenticationDetails {
pub eci: Option<String>,
pub token_details: Option<TokenDetails>,
pub dynamic_data_details: Option<DynamicData>,
pub trans_status: Option<common_enums::TransactionStatus>,
pub challenge_cancel: Option<String>,
pub challenge_code_reason: Option<String>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct TokenDetails {
pub payment_token: cards::CardNumber,
pub payment_account_reference: String,
pub token_expiration_month: Secret<String>,
pub token_expiration_year: Secret<String>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct DynamicData {
pub dynamic_data_value: Option<Secret<String>>,
pub dynamic_data_type: Option<String>,
pub ds_trans_id: Option<String>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct UasConfirmationRequestData {
pub x_src_flow_id: Option<String>,
pub transaction_amount: MinorUnit,
pub transaction_currency: common_enums::Currency,
// Type of event associated with the checkout. Valid values are: - 01 - Authorise - 02 - Capture - 03 - Refund - 04 - Cancel - 05 - Fraud - 06 - Chargeback - 07 - Other
pub checkout_event_type: Option<String>,
pub checkout_event_status: Option<String>,
pub confirmation_status: Option<String>,
pub confirmation_reason: Option<String>,
pub confirmation_timestamp: Option<String>,
// Authorisation code associated with an approved transaction.
pub network_authorization_code: Option<String>,
// The unique authorisation related tracing value assigned by a Payment Network and provided in an authorisation response. Required only when checkoutEventType=01. If checkoutEventType=01 and the value of networkTransactionIdentifier is unknown, please pass UNAVLB
pub network_transaction_identifier: Option<String>,
pub correlation_id: Option<String>,
pub merchant_transaction_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ThreeDsMetaData {
pub merchant_category_code: Option<MerchantCategoryCode>,
pub merchant_country_code: Option<MerchantCountryCode>,
pub merchant_name: Option<String>,
pub endpoint_prefix: Option<String>,
pub three_ds_requestor_name: Option<String>,
pub three_ds_requestor_id: Option<String>,
pub merchant_configuration_id: Option<String>,
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 16,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-6849505012808556064
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_request_types/revenue_recovery.rs
// Contains: 3 structs, 0 enums
use common_enums::enums;
use crate::connector_endpoints;
#[derive(Debug, Clone)]
pub struct BillingConnectorPaymentsSyncRequest {
/// unique id for making billing connector psync call
pub billing_connector_psync_id: String,
/// connector params of the connector
pub connector_params: connector_endpoints::ConnectorParams,
}
#[derive(Debug, Clone)]
pub struct InvoiceRecordBackRequest {
pub merchant_reference_id: common_utils::id_type::PaymentReferenceId,
pub amount: common_utils::types::MinorUnit,
pub currency: enums::Currency,
pub payment_method_type: Option<common_enums::PaymentMethodType>,
pub attempt_status: common_enums::AttemptStatus,
pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>,
pub connector_params: connector_endpoints::ConnectorParams,
}
#[derive(Debug, Clone)]
pub struct BillingConnectorInvoiceSyncRequest {
/// Invoice id
pub billing_connector_invoice_id: String,
/// connector params of the connector
pub connector_params: connector_endpoints::ConnectorParams,
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_request_types/revenue_recovery.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 3,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_6855469832817264121
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_request_types/authentication.rs
// Contains: 10 structs, 2 enums
use common_utils::{ext_traits::OptionExt, pii::Email};
use error_stack::{Report, ResultExt};
use serde::{Deserialize, Serialize};
use crate::{
address,
errors::api_error_response::ApiErrorResponse,
payment_method_data::{Card, PaymentMethodData},
router_request_types::BrowserInformation,
};
#[derive(Clone, Debug, Serialize, Deserialize)]
pub struct ChallengeParams {
pub acs_url: Option<url::Url>,
pub challenge_request: Option<String>,
pub challenge_request_key: Option<String>,
pub acs_reference_number: Option<String>,
pub acs_trans_id: Option<String>,
pub three_dsserver_trans_id: Option<String>,
pub acs_signed_content: Option<String>,
}
#[derive(Clone, Debug, Serialize, Deserialize)]
pub enum AuthNFlowType {
Challenge(Box<ChallengeParams>),
Frictionless,
}
impl AuthNFlowType {
pub fn get_acs_url(&self) -> Option<String> {
if let Self::Challenge(challenge_params) = self {
challenge_params.acs_url.as_ref().map(ToString::to_string)
} else {
None
}
}
pub fn get_challenge_request(&self) -> Option<String> {
if let Self::Challenge(challenge_params) = self {
challenge_params.challenge_request.clone()
} else {
None
}
}
pub fn get_challenge_request_key(&self) -> Option<String> {
if let Self::Challenge(challenge_params) = self {
challenge_params.challenge_request_key.clone()
} else {
None
}
}
pub fn get_acs_reference_number(&self) -> Option<String> {
if let Self::Challenge(challenge_params) = self {
challenge_params.acs_reference_number.clone()
} else {
None
}
}
pub fn get_acs_trans_id(&self) -> Option<String> {
if let Self::Challenge(challenge_params) = self {
challenge_params.acs_trans_id.clone()
} else {
None
}
}
pub fn get_acs_signed_content(&self) -> Option<String> {
if let Self::Challenge(challenge_params) = self {
challenge_params.acs_signed_content.clone()
} else {
None
}
}
pub fn get_decoupled_authentication_type(&self) -> common_enums::DecoupledAuthenticationType {
match self {
Self::Challenge(_) => common_enums::DecoupledAuthenticationType::Challenge,
Self::Frictionless => common_enums::DecoupledAuthenticationType::Frictionless,
}
}
}
#[derive(Serialize, Deserialize, Debug, Clone)]
#[serde(rename_all = "camelCase")]
pub struct MessageExtensionAttribute {
pub id: String,
pub name: String,
pub criticality_indicator: bool,
pub data: serde_json::Value,
}
#[derive(Clone, Default, Debug)]
pub struct PreAuthNRequestData {
// card data
pub card: Card,
}
#[derive(Clone, Debug)]
pub struct ConnectorAuthenticationRequestData {
pub payment_method_data: PaymentMethodData,
pub billing_address: address::Address,
pub shipping_address: Option<address::Address>,
pub browser_details: Option<BrowserInformation>,
pub amount: Option<i64>,
pub currency: Option<common_enums::Currency>,
pub message_category: MessageCategory,
pub device_channel: api_models::payments::DeviceChannel,
pub pre_authentication_data: PreAuthenticationData,
pub return_url: Option<String>,
pub sdk_information: Option<api_models::payments::SdkInformation>,
pub email: Option<Email>,
pub threeds_method_comp_ind: api_models::payments::ThreeDsCompletionIndicator,
pub three_ds_requestor_url: String,
pub webhook_url: String,
pub force_3ds_challenge: bool,
}
#[derive(Clone, serde::Deserialize, Debug, serde::Serialize, PartialEq, Eq)]
pub enum MessageCategory {
Payment,
NonPayment,
}
#[derive(Clone, Debug)]
pub struct ConnectorPostAuthenticationRequestData {
pub threeds_server_transaction_id: String,
}
#[derive(Clone, Debug)]
pub struct PreAuthenticationData {
pub threeds_server_transaction_id: String,
pub message_version: common_utils::types::SemanticVersion,
pub acquirer_bin: Option<String>,
pub acquirer_merchant_id: Option<String>,
pub acquirer_country_code: Option<String>,
pub connector_metadata: Option<serde_json::Value>,
}
impl TryFrom<&diesel_models::authentication::Authentication> for PreAuthenticationData {
type Error = Report<ApiErrorResponse>;
fn try_from(
authentication: &diesel_models::authentication::Authentication,
) -> Result<Self, Self::Error> {
let error_message = ApiErrorResponse::UnprocessableEntity { message: "Pre Authentication must be completed successfully before Authentication can be performed".to_string() };
let threeds_server_transaction_id = authentication
.threeds_server_transaction_id
.clone()
.get_required_value("threeds_server_transaction_id")
.change_context(error_message.clone())?;
let message_version = authentication
.message_version
.clone()
.get_required_value("message_version")
.change_context(error_message)?;
Ok(Self {
threeds_server_transaction_id,
message_version,
acquirer_bin: authentication.acquirer_bin.clone(),
acquirer_merchant_id: authentication.acquirer_merchant_id.clone(),
connector_metadata: authentication.connector_metadata.clone(),
acquirer_country_code: authentication.acquirer_country_code.clone(),
})
}
}
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
pub struct ThreeDsMethodData {
pub three_ds_method_data_submission: bool,
pub three_ds_method_data: String,
pub three_ds_method_url: Option<String>,
}
#[derive(Clone, Default, Debug, Serialize, Deserialize)]
pub struct AcquirerDetails {
pub acquirer_bin: String,
pub acquirer_merchant_id: String,
pub acquirer_country_code: Option<String>,
}
#[derive(Clone, Debug, Deserialize)]
pub struct ExternalThreeDSConnectorMetadata {
pub pull_mechanism_for_external_3ds_enabled: Option<bool>,
}
#[derive(Clone, Debug)]
pub struct AuthenticationStore {
pub cavv: Option<masking::Secret<String>>,
pub authentication: diesel_models::authentication::Authentication,
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_request_types/authentication.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 10,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_4768405274281169799
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs
// Contains: 8 structs, 2 enums
use common_enums::Currency;
use common_utils::{id_type, types::MinorUnit};
use time::PrimitiveDateTime;
#[derive(Debug, Clone)]
pub struct SubscriptionCreateResponse {
pub subscription_id: id_type::SubscriptionId,
pub status: SubscriptionStatus,
pub customer_id: id_type::CustomerId,
pub currency_code: Currency,
pub total_amount: MinorUnit,
pub next_billing_at: Option<PrimitiveDateTime>,
pub created_at: Option<PrimitiveDateTime>,
pub invoice_details: Option<SubscriptionInvoiceData>,
}
#[derive(Debug, Clone, serde::Serialize)]
pub struct SubscriptionInvoiceData {
pub id: id_type::InvoiceId,
pub total: MinorUnit,
pub currency_code: Currency,
pub status: Option<common_enums::connector_enums::InvoiceStatus>,
pub billing_address: Option<api_models::payments::Address>,
}
#[derive(Debug, Clone, PartialEq, Eq, Copy)]
pub enum SubscriptionStatus {
Pending,
Trial,
Active,
Paused,
Unpaid,
Onetime,
Cancelled,
Failed,
Created,
}
impl From<SubscriptionStatus> for api_models::subscription::SubscriptionStatus {
fn from(status: SubscriptionStatus) -> Self {
match status {
SubscriptionStatus::Pending => Self::Pending,
SubscriptionStatus::Trial => Self::Trial,
SubscriptionStatus::Active => Self::Active,
SubscriptionStatus::Paused => Self::Paused,
SubscriptionStatus::Unpaid => Self::Unpaid,
SubscriptionStatus::Onetime => Self::Onetime,
SubscriptionStatus::Cancelled => Self::Cancelled,
SubscriptionStatus::Failed => Self::Failed,
SubscriptionStatus::Created => Self::Created,
}
}
}
#[derive(Debug, Clone)]
pub struct GetSubscriptionPlansResponse {
pub list: Vec<SubscriptionPlans>,
}
#[derive(Debug, Clone)]
pub struct SubscriptionPlans {
pub subscription_provider_plan_id: String,
pub name: String,
pub description: Option<String>,
}
#[derive(Debug, Clone)]
pub struct GetSubscriptionPlanPricesResponse {
pub list: Vec<SubscriptionPlanPrices>,
}
#[derive(Debug, Clone)]
pub struct SubscriptionPlanPrices {
pub price_id: String,
pub plan_id: Option<String>,
pub amount: MinorUnit,
pub currency: Currency,
pub interval: PeriodUnit,
pub interval_count: i64,
pub trial_period: Option<i64>,
pub trial_period_unit: Option<PeriodUnit>,
}
impl From<SubscriptionPlanPrices> for api_models::subscription::SubscriptionPlanPrices {
fn from(item: SubscriptionPlanPrices) -> Self {
Self {
price_id: item.price_id,
plan_id: item.plan_id,
amount: item.amount,
currency: item.currency,
interval: item.interval.into(),
interval_count: item.interval_count,
trial_period: item.trial_period,
trial_period_unit: item.trial_period_unit.map(Into::into),
}
}
}
#[derive(Debug, Clone)]
pub enum PeriodUnit {
Day,
Week,
Month,
Year,
}
impl From<PeriodUnit> for api_models::subscription::PeriodUnit {
fn from(unit: PeriodUnit) -> Self {
match unit {
PeriodUnit::Day => Self::Day,
PeriodUnit::Week => Self::Week,
PeriodUnit::Month => Self::Month,
PeriodUnit::Year => Self::Year,
}
}
}
#[derive(Debug, Clone)]
pub struct GetSubscriptionEstimateResponse {
pub sub_total: MinorUnit,
pub total: MinorUnit,
pub credits_applied: Option<MinorUnit>,
pub amount_paid: Option<MinorUnit>,
pub amount_due: Option<MinorUnit>,
pub currency: Currency,
pub next_billing_at: Option<PrimitiveDateTime>,
pub line_items: Vec<SubscriptionLineItem>,
pub customer_id: Option<id_type::CustomerId>,
}
impl From<GetSubscriptionEstimateResponse>
for api_models::subscription::EstimateSubscriptionResponse
{
fn from(value: GetSubscriptionEstimateResponse) -> Self {
Self {
amount: value.total,
currency: value.currency,
plan_id: None,
item_price_id: None,
coupon_code: None,
customer_id: value.customer_id,
line_items: value
.line_items
.into_iter()
.map(api_models::subscription::SubscriptionLineItem::from)
.collect(),
}
}
}
#[derive(Debug, Clone)]
pub struct SubscriptionLineItem {
pub item_id: String,
pub item_type: String,
pub description: String,
pub amount: MinorUnit,
pub currency: Currency,
pub unit_amount: Option<MinorUnit>,
pub quantity: i64,
pub pricing_model: Option<String>,
}
impl From<SubscriptionLineItem> for api_models::subscription::SubscriptionLineItem {
fn from(value: SubscriptionLineItem) -> Self {
Self {
item_id: value.item_id,
description: value.description,
item_type: value.item_type,
amount: value.amount,
currency: value.currency,
quantity: value.quantity,
}
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_response_types/subscriptions.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 2,
"num_structs": 8,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-784208565246665644
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_response_types/disputes.rs
// Contains: 4 structs, 0 enums
#[derive(Default, Clone, Debug)]
pub struct AcceptDisputeResponse {
pub dispute_status: api_models::enums::DisputeStatus,
pub connector_status: Option<String>,
}
#[derive(Default, Clone, Debug)]
pub struct SubmitEvidenceResponse {
pub dispute_status: api_models::enums::DisputeStatus,
pub connector_status: Option<String>,
}
#[derive(Default, Debug, Clone)]
pub struct DefendDisputeResponse {
pub dispute_status: api_models::enums::DisputeStatus,
pub connector_status: Option<String>,
}
pub struct FileInfo {
pub file_data: Option<Vec<u8>>,
pub provider_file_id: Option<String>,
pub file_type: Option<String>,
}
#[derive(serde::Serialize, serde::Deserialize, Clone, Debug)]
pub struct DisputeSyncResponse {
pub object_reference_id: api_models::webhooks::ObjectReferenceId,
pub amount: common_utils::types::StringMinorUnit,
pub currency: common_enums::enums::Currency,
pub dispute_stage: common_enums::enums::DisputeStage,
pub dispute_status: api_models::enums::DisputeStatus,
pub connector_status: String,
pub connector_dispute_id: String,
pub connector_reason: Option<String>,
pub connector_reason_code: Option<String>,
pub challenge_required_by: Option<time::PrimitiveDateTime>,
pub created_at: Option<time::PrimitiveDateTime>,
pub updated_at: Option<time::PrimitiveDateTime>,
}
pub type FetchDisputesResponse = Vec<DisputeSyncResponse>;
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_response_types/disputes.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 4,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-7115952912185092231
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs
// Contains: 3 structs, 0 enums
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>,
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_response_types/revenue_recovery.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 3,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-4734875438649054991
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_flow_types/dispute.rs
// Contains: 5 structs, 0 enums
#[derive(Debug, Clone)]
pub struct Accept;
#[derive(Debug, Clone)]
pub struct Evidence;
#[derive(Debug, Clone)]
pub struct Defend;
#[derive(Debug, Clone)]
pub struct Fetch;
#[derive(Debug, Clone)]
pub struct Dsync;
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_flow_types/dispute.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 5,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-284867466456192538
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_flow_types/refunds.rs
// Contains: 2 structs, 0 enums
#[derive(Debug, Clone)]
pub struct Execute;
#[derive(Debug, Clone)]
pub struct RSync;
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_flow_types/refunds.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_4418811297976577783
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs
// Contains: 5 structs, 0 enums
use common_enums::connector_enums::InvoiceStatus;
#[derive(Debug, Clone)]
pub struct SubscriptionCreate;
#[derive(Debug, Clone)]
pub struct GetSubscriptionPlans;
#[derive(Debug, Clone)]
pub struct GetSubscriptionPlanPrices;
#[derive(Debug, Clone)]
pub struct GetSubscriptionEstimate;
/// Generic structure for subscription MIT (Merchant Initiated Transaction) payment data
#[derive(Debug, Clone)]
pub struct SubscriptionMitPaymentData {
pub invoice_id: common_utils::id_type::InvoiceId,
pub amount_due: common_utils::types::MinorUnit,
pub currency_code: common_enums::enums::Currency,
pub status: Option<InvoiceStatus>,
pub customer_id: common_utils::id_type::CustomerId,
pub subscription_id: common_utils::id_type::SubscriptionId,
pub first_invoice: bool,
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 5,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-7442832212624778368
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_flow_types/payouts.rs
// Contains: 8 structs, 0 enums
#[derive(Debug, Clone)]
pub struct PoCancel;
#[derive(Debug, Clone)]
pub struct PoCreate;
#[derive(Debug, Clone)]
pub struct PoEligibility;
#[derive(Debug, Clone)]
pub struct PoFulfill;
#[derive(Debug, Clone)]
pub struct PoQuote;
#[derive(Debug, Clone)]
pub struct PoRecipient;
#[derive(Debug, Clone)]
pub struct PoRecipientAccount;
#[derive(Debug, Clone)]
pub struct PoSync;
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_flow_types/payouts.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 8,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_2307384873635453596
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_flow_types/fraud_check.rs
// Contains: 5 structs, 0 enums
#[derive(Debug, Clone)]
pub struct Sale;
#[derive(Debug, Clone)]
pub struct Checkout;
#[derive(Debug, Clone)]
pub struct Transaction;
#[derive(Debug, Clone)]
pub struct Fulfillment;
#[derive(Debug, Clone)]
pub struct RecordReturn;
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_flow_types/fraud_check.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 5,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-6759040792034943127
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_flow_types/access_token_auth.rs
// Contains: 2 structs, 0 enums
#[derive(Clone, Debug)]
pub struct AccessTokenAuthentication;
#[derive(Clone, Debug)]
pub struct AccessTokenAuth;
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_flow_types/access_token_auth.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-8382699451246361345
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
// Contains: 31 structs, 0 enums
// Core related api layer.
#[derive(Debug, Clone)]
pub struct Authorize;
#[derive(Debug, Clone)]
pub struct AuthorizeSessionToken;
#[derive(Debug, Clone)]
pub struct CompleteAuthorize;
#[derive(Debug, Clone)]
pub struct Approve;
// Used in gift cards balance check
#[derive(Debug, Clone)]
pub struct Balance;
#[derive(Debug, Clone)]
pub struct InitPayment;
#[derive(Debug, Clone)]
pub struct Capture;
#[derive(Debug, Clone)]
pub struct PSync;
#[derive(Debug, Clone)]
pub struct Void;
#[derive(Debug, Clone)]
pub struct PostCaptureVoid;
#[derive(Debug, Clone)]
pub struct Reject;
#[derive(Debug, Clone)]
pub struct Session;
#[derive(Debug, Clone)]
pub struct PaymentMethodToken;
#[derive(Debug, Clone)]
pub struct CreateConnectorCustomer;
#[derive(Debug, Clone)]
pub struct SetupMandate;
#[derive(Debug, Clone)]
pub struct PreProcessing;
#[derive(Debug, Clone)]
pub struct IncrementalAuthorization;
#[derive(Debug, Clone)]
pub struct ExtendAuthorization;
#[derive(Debug, Clone)]
pub struct PostProcessing;
#[derive(Debug, Clone)]
pub struct CalculateTax;
#[derive(Debug, Clone)]
pub struct SdkSessionUpdate;
#[derive(Debug, Clone)]
pub struct PaymentCreateIntent;
#[derive(Debug, Clone)]
pub struct PaymentGetIntent;
#[derive(Debug, Clone)]
pub struct PaymentUpdateIntent;
#[derive(Debug, Clone)]
pub struct PostSessionTokens;
#[derive(Debug, Clone)]
pub struct RecordAttempt;
#[derive(Debug, Clone)]
pub struct UpdateMetadata;
#[derive(Debug, Clone)]
pub struct CreateOrder;
#[derive(Debug, Clone)]
pub struct PaymentGetListAttempts;
#[derive(Debug, Clone)]
pub struct ExternalVaultProxy;
#[derive(Debug, Clone)]
pub struct GiftCardBalanceCheck;
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_flow_types/payments.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 31,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-62475329344822140
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_flow_types/unified_authentication_service.rs
// Contains: 4 structs, 0 enums
#[derive(Debug, Clone)]
pub struct PreAuthenticate;
#[derive(Debug, Clone)]
pub struct PostAuthenticate;
#[derive(Debug, Clone)]
pub struct AuthenticationConfirmation;
#[derive(Debug, Clone)]
pub struct Authenticate;
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_flow_types/unified_authentication_service.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 4,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-7337108432357466367
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_flow_types/files.rs
// Contains: 2 structs, 0 enums
#[derive(Debug, Clone)]
pub struct Retrieve;
#[derive(Debug, Clone)]
pub struct Upload;
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_flow_types/files.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 2,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-8390111168554009448
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_flow_types/mandate_revoke.rs
// Contains: 1 structs, 0 enums
#[derive(Clone, Debug)]
pub struct MandateRevoke;
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_flow_types/mandate_revoke.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-4839234785668828614
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_flow_types/webhooks.rs
// Contains: 3 structs, 0 enums
use serde::Serialize;
#[derive(Clone, Debug)]
pub struct VerifyWebhookSource;
#[derive(Debug, Clone, Serialize)]
pub struct ConnectorMandateDetails {
pub connector_mandate_id: masking::Secret<String>,
}
#[derive(Debug, Clone, Serialize)]
pub struct ConnectorNetworkTxnId(masking::Secret<String>);
impl ConnectorNetworkTxnId {
pub fn new(txn_id: masking::Secret<String>) -> Self {
Self(txn_id)
}
pub fn get_id(&self) -> &masking::Secret<String> {
&self.0
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_flow_types/webhooks.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 3,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_8601665996697039034
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_flow_types/revenue_recovery.rs
// Contains: 3 structs, 0 enums
#[derive(Debug, Clone)]
pub struct BillingConnectorPaymentsSync;
#[derive(Debug, Clone)]
pub struct InvoiceRecordBack;
#[derive(Debug, Clone)]
pub struct BillingConnectorInvoiceSync;
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_flow_types/revenue_recovery.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 3,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_7000746761690169448
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_flow_types/authentication.rs
// Contains: 4 structs, 0 enums
#[derive(Debug, Clone)]
pub struct PreAuthentication;
#[derive(Debug, Clone)]
pub struct PreAuthenticationVersionCall;
#[derive(Debug, Clone)]
pub struct Authentication;
#[derive(Debug, Clone)]
pub struct PostAuthentication;
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_flow_types/authentication.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 4,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_4191696930512852991
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_flow_types/vault.rs
// Contains: 4 structs, 0 enums
#[derive(Debug, Clone)]
pub struct ExternalVaultInsertFlow;
#[derive(Debug, Clone)]
pub struct ExternalVaultRetrieveFlow;
#[derive(Debug, Clone)]
pub struct ExternalVaultDeleteFlow;
#[derive(Debug, Clone)]
pub struct ExternalVaultCreateFlow;
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_flow_types/vault.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 4,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_6670128894405129850
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
// Contains: 23 structs, 0 enums
use common_utils::{pii, types::MinorUnit};
use crate::{
payment_address::PaymentAddress,
payment_method_data::ApplePayFlow,
router_data::{
AccessToken, ConnectorResponseData, PaymentMethodBalance, PaymentMethodToken,
RecurringMandatePaymentData,
},
};
#[derive(Debug, Clone)]
pub struct PaymentFlowData {
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub connector_customer: Option<String>,
pub connector: String,
pub payment_id: String,
pub attempt_id: String,
pub status: common_enums::AttemptStatus,
pub payment_method: common_enums::PaymentMethod,
pub description: Option<String>,
pub address: PaymentAddress,
pub auth_type: common_enums::AuthenticationType,
pub connector_meta_data: Option<pii::SecretSerdeValue>,
pub amount_captured: Option<i64>,
// minor amount for amount framework
pub minor_amount_captured: Option<MinorUnit>,
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 a reference ID that should be sent in the connector request
pub connector_request_reference_id: 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<ApplePayFlow>,
/// 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>,
}
#[derive(Debug, Clone)]
pub struct RefundFlowData {
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub payment_id: String,
pub attempt_id: String,
pub status: common_enums::AttemptStatus,
pub payment_method: common_enums::PaymentMethod,
pub connector_meta_data: Option<pii::SecretSerdeValue>,
pub amount_captured: Option<i64>,
// minor amount for amount framework
pub minor_amount_captured: Option<MinorUnit>,
/// Contains a reference ID that should be sent in the connector request
pub connector_request_reference_id: String,
pub refund_id: String,
}
#[cfg(feature = "payouts")]
#[derive(Debug, Clone)]
pub struct PayoutFlowData {
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub connector_customer: Option<String>,
pub address: PaymentAddress,
pub connector_meta_data: Option<pii::SecretSerdeValue>,
pub connector_wallets_details: Option<pii::SecretSerdeValue>,
/// Contains a reference ID that should be sent in the connector request
pub connector_request_reference_id: String,
pub payout_method_data: Option<api_models::payouts::PayoutMethodData>,
pub quote_id: Option<String>,
}
#[cfg(feature = "frm")]
#[derive(Debug, Clone)]
pub struct FrmFlowData {
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: String,
pub attempt_id: String,
pub payment_method: common_enums::enums::PaymentMethod,
pub connector_request_reference_id: String,
pub auth_type: common_enums::enums::AuthenticationType,
pub connector_wallets_details: Option<pii::SecretSerdeValue>,
pub connector_meta_data: Option<pii::SecretSerdeValue>,
pub amount_captured: Option<i64>,
// minor amount for amount framework
pub minor_amount_captured: Option<MinorUnit>,
}
#[derive(Debug, Clone)]
pub struct ExternalAuthenticationFlowData {
pub merchant_id: common_utils::id_type::MerchantId,
pub connector_meta_data: Option<pii::SecretSerdeValue>,
pub address: PaymentAddress,
}
#[derive(Debug, Clone)]
pub struct DisputesFlowData {
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: String,
pub attempt_id: String,
pub payment_method: common_enums::enums::PaymentMethod,
pub connector_meta_data: Option<pii::SecretSerdeValue>,
pub amount_captured: Option<i64>,
// minor amount for amount framework
pub minor_amount_captured: Option<MinorUnit>,
/// Contains a reference ID that should be sent in the connector request
pub connector_request_reference_id: String,
pub dispute_id: String,
}
#[derive(Debug, Clone)]
pub struct MandateRevokeFlowData {
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: common_utils::id_type::CustomerId,
pub payment_id: Option<String>,
}
#[derive(Debug, Clone)]
pub struct WebhookSourceVerifyData {
pub merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Debug, Clone)]
pub struct AuthenticationTokenFlowData {}
#[derive(Debug, Clone)]
pub struct AccessTokenFlowData {}
#[derive(Debug, Clone)]
pub struct FilesFlowData {
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: String,
pub attempt_id: String,
pub connector_meta_data: Option<pii::SecretSerdeValue>,
pub connector_request_reference_id: String,
}
#[derive(Debug, Clone)]
pub struct InvoiceRecordBackData {
pub connector_meta_data: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Clone)]
pub struct SubscriptionCustomerData {
pub connector_meta_data: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Clone)]
pub struct SubscriptionCreateData {
pub connector_meta_data: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Clone)]
pub struct GetSubscriptionPlansData {
pub connector_meta_data: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Clone)]
pub struct GetSubscriptionPlanPricesData {
pub connector_meta_data: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Clone)]
pub struct GetSubscriptionEstimateData {
pub connector_meta_data: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Clone)]
pub struct UasFlowData {
pub authenticate_by: String,
pub source_authentication_id: common_utils::id_type::AuthenticationId,
}
#[derive(Debug, Clone)]
pub struct BillingConnectorPaymentsSyncFlowData;
#[derive(Debug, Clone)]
pub struct BillingConnectorInvoiceSyncFlowData;
#[derive(Debug, Clone)]
pub struct VaultConnectorFlowData {
pub merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Debug, Clone)]
pub struct GiftCardBalanceCheckFlowData;
#[derive(Debug, Clone)]
pub struct ExternalVaultProxyFlowData {
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: Option<common_utils::id_type::CustomerId>,
pub connector_customer: Option<String>,
pub payment_id: String,
pub attempt_id: String,
pub status: common_enums::AttemptStatus,
pub payment_method: common_enums::PaymentMethod,
pub description: Option<String>,
pub address: PaymentAddress,
pub auth_type: common_enums::AuthenticationType,
pub connector_meta_data: Option<pii::SecretSerdeValue>,
pub amount_captured: Option<i64>,
// minor amount for amount framework
pub minor_amount_captured: Option<MinorUnit>,
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 a reference ID that should be sent in the connector request
pub connector_request_reference_id: 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<ApplePayFlow>,
/// 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>,
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 23,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_-7214889085368462814
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/payouts/payouts.rs
// Contains: 3 structs, 1 enums
use common_enums as storage_enums;
use common_utils::{id_type, pii, types::MinorUnit};
use serde::{Deserialize, Serialize};
use storage_enums::MerchantStorageScheme;
use time::PrimitiveDateTime;
use super::payout_attempt::PayoutAttempt;
#[cfg(feature = "olap")]
use super::PayoutFetchConstraints;
#[async_trait::async_trait]
pub trait PayoutsInterface {
type Error;
async fn insert_payout(
&self,
_payout: PayoutsNew,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, Self::Error>;
async fn find_payout_by_merchant_id_payout_id(
&self,
_merchant_id: &id_type::MerchantId,
_payout_id: &id_type::PayoutId,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, Self::Error>;
async fn update_payout(
&self,
_this: &Payouts,
_payout: PayoutsUpdate,
_payout_attempt: &PayoutAttempt,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, Self::Error>;
async fn find_optional_payout_by_merchant_id_payout_id(
&self,
_merchant_id: &id_type::MerchantId,
_payout_id: &id_type::PayoutId,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Option<Payouts>, Self::Error>;
#[cfg(feature = "olap")]
async fn filter_payouts_by_constraints(
&self,
_merchant_id: &id_type::MerchantId,
_filters: &PayoutFetchConstraints,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, Self::Error>;
#[cfg(feature = "olap")]
async fn filter_payouts_and_attempts(
&self,
_merchant_id: &id_type::MerchantId,
_filters: &PayoutFetchConstraints,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<
Vec<(
Payouts,
PayoutAttempt,
Option<diesel_models::Customer>,
Option<diesel_models::Address>,
)>,
Self::Error,
>;
#[cfg(feature = "olap")]
async fn filter_payouts_by_time_range_constraints(
&self,
_merchant_id: &id_type::MerchantId,
_time_range: &common_utils::types::TimeRange,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, Self::Error>;
#[cfg(feature = "olap")]
#[allow(clippy::too_many_arguments)]
async fn get_total_count_of_filtered_payouts(
&self,
_merchant_id: &id_type::MerchantId,
_active_payout_ids: &[id_type::PayoutId],
_connector: Option<Vec<api_models::enums::PayoutConnectors>>,
_currency: Option<Vec<storage_enums::Currency>>,
_status: Option<Vec<storage_enums::PayoutStatus>>,
_payout_method: Option<Vec<storage_enums::PayoutType>>,
) -> error_stack::Result<i64, Self::Error>;
#[cfg(feature = "olap")]
async fn filter_active_payout_ids_by_constraints(
&self,
_merchant_id: &id_type::MerchantId,
_constraints: &PayoutFetchConstraints,
) -> error_stack::Result<Vec<id_type::PayoutId>, Self::Error>;
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Payouts {
pub payout_id: id_type::PayoutId,
pub merchant_id: id_type::MerchantId,
pub customer_id: Option<id_type::CustomerId>,
pub address_id: Option<String>,
pub payout_type: Option<storage_enums::PayoutType>,
pub payout_method_id: Option<String>,
pub amount: MinorUnit,
pub destination_currency: storage_enums::Currency,
pub source_currency: storage_enums::Currency,
pub description: Option<String>,
pub recurring: bool,
pub auto_fulfill: bool,
pub return_url: Option<String>,
pub entity_type: storage_enums::PayoutEntityType,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
pub attempt_count: i16,
pub profile_id: id_type::ProfileId,
pub status: storage_enums::PayoutStatus,
pub confirm: Option<bool>,
pub payout_link_id: Option<String>,
pub client_secret: Option<String>,
pub priority: Option<storage_enums::PayoutSendPriority>,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PayoutsNew {
pub payout_id: id_type::PayoutId,
pub merchant_id: id_type::MerchantId,
pub customer_id: Option<id_type::CustomerId>,
pub address_id: Option<String>,
pub payout_type: Option<storage_enums::PayoutType>,
pub payout_method_id: Option<String>,
pub amount: MinorUnit,
pub destination_currency: storage_enums::Currency,
pub source_currency: storage_enums::Currency,
pub description: Option<String>,
pub recurring: bool,
pub auto_fulfill: bool,
pub return_url: Option<String>,
pub entity_type: storage_enums::PayoutEntityType,
pub metadata: Option<pii::SecretSerdeValue>,
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
pub attempt_count: i16,
pub profile_id: id_type::ProfileId,
pub status: storage_enums::PayoutStatus,
pub confirm: Option<bool>,
pub payout_link_id: Option<String>,
pub client_secret: Option<String>,
pub priority: Option<storage_enums::PayoutSendPriority>,
}
#[derive(Debug, Serialize, Deserialize)]
pub enum PayoutsUpdate {
Update {
amount: MinorUnit,
destination_currency: storage_enums::Currency,
source_currency: storage_enums::Currency,
description: Option<String>,
recurring: bool,
auto_fulfill: bool,
return_url: Option<String>,
entity_type: storage_enums::PayoutEntityType,
metadata: Option<pii::SecretSerdeValue>,
profile_id: Option<id_type::ProfileId>,
status: Option<storage_enums::PayoutStatus>,
confirm: Option<bool>,
payout_type: Option<storage_enums::PayoutType>,
address_id: Option<String>,
customer_id: Option<id_type::CustomerId>,
},
PayoutMethodIdUpdate {
payout_method_id: String,
},
RecurringUpdate {
recurring: bool,
},
AttemptCountUpdate {
attempt_count: i16,
},
StatusUpdate {
status: storage_enums::PayoutStatus,
},
}
#[derive(Clone, Debug, Default)]
pub struct PayoutsUpdateInternal {
pub amount: Option<MinorUnit>,
pub destination_currency: Option<storage_enums::Currency>,
pub source_currency: Option<storage_enums::Currency>,
pub description: Option<String>,
pub recurring: Option<bool>,
pub auto_fulfill: Option<bool>,
pub return_url: Option<String>,
pub entity_type: Option<storage_enums::PayoutEntityType>,
pub metadata: Option<pii::SecretSerdeValue>,
pub payout_method_id: Option<String>,
pub profile_id: Option<id_type::ProfileId>,
pub status: Option<storage_enums::PayoutStatus>,
pub attempt_count: Option<i16>,
pub confirm: Option<bool>,
pub payout_type: Option<common_enums::PayoutType>,
pub address_id: Option<String>,
pub customer_id: Option<id_type::CustomerId>,
}
impl From<PayoutsUpdate> for PayoutsUpdateInternal {
fn from(payout_update: PayoutsUpdate) -> Self {
match payout_update {
PayoutsUpdate::Update {
amount,
destination_currency,
source_currency,
description,
recurring,
auto_fulfill,
return_url,
entity_type,
metadata,
profile_id,
status,
confirm,
payout_type,
address_id,
customer_id,
} => Self {
amount: Some(amount),
destination_currency: Some(destination_currency),
source_currency: Some(source_currency),
description,
recurring: Some(recurring),
auto_fulfill: Some(auto_fulfill),
return_url,
entity_type: Some(entity_type),
metadata,
profile_id,
status,
confirm,
payout_type,
address_id,
customer_id,
..Default::default()
},
PayoutsUpdate::PayoutMethodIdUpdate { payout_method_id } => Self {
payout_method_id: Some(payout_method_id),
..Default::default()
},
PayoutsUpdate::RecurringUpdate { recurring } => Self {
recurring: Some(recurring),
..Default::default()
},
PayoutsUpdate::AttemptCountUpdate { attempt_count } => Self {
attempt_count: Some(attempt_count),
..Default::default()
},
PayoutsUpdate::StatusUpdate { status } => Self {
status: Some(status),
..Default::default()
},
}
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/payouts/payouts.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 3,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_domain_models_5688272445673925536
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_domain_models
// File: crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs
// Contains: 4 structs, 1 enums
use api_models::enums::PayoutConnectors;
use common_enums as storage_enums;
use common_utils::{
id_type, payout_method_utils, pii,
types::{UnifiedCode, UnifiedMessage},
};
use serde::{Deserialize, Serialize};
use storage_enums::MerchantStorageScheme;
use time::PrimitiveDateTime;
use super::payouts::Payouts;
#[async_trait::async_trait]
pub trait PayoutAttemptInterface {
type Error;
async fn insert_payout_attempt(
&self,
_payout_attempt: PayoutAttemptNew,
_payouts: &Payouts,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, Self::Error>;
async fn update_payout_attempt(
&self,
_this: &PayoutAttempt,
_payout_attempt_update: PayoutAttemptUpdate,
_payouts: &Payouts,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, Self::Error>;
async fn find_payout_attempt_by_merchant_id_payout_attempt_id(
&self,
_merchant_id: &id_type::MerchantId,
_payout_attempt_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, Self::Error>;
async fn find_payout_attempt_by_merchant_id_connector_payout_id(
&self,
_merchant_id: &id_type::MerchantId,
_connector_payout_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, Self::Error>;
async fn find_payout_attempt_by_merchant_id_merchant_order_reference_id(
&self,
_merchant_id: &id_type::MerchantId,
_merchant_order_reference_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, Self::Error>;
async fn get_filters_for_payouts(
&self,
_payout: &[Payouts],
_merchant_id: &id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutListFilters, Self::Error>;
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PayoutListFilters {
pub connector: Vec<PayoutConnectors>,
pub currency: Vec<storage_enums::Currency>,
pub status: Vec<storage_enums::PayoutStatus>,
pub payout_method: Vec<storage_enums::PayoutType>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)]
pub struct PayoutAttempt {
pub payout_attempt_id: String,
pub payout_id: id_type::PayoutId,
pub customer_id: Option<id_type::CustomerId>,
pub merchant_id: id_type::MerchantId,
pub address_id: Option<String>,
pub connector: Option<String>,
pub connector_payout_id: Option<String>,
pub payout_token: Option<String>,
pub status: storage_enums::PayoutStatus,
pub is_eligible: Option<bool>,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub last_modified_at: PrimitiveDateTime,
pub profile_id: id_type::ProfileId,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub routing_info: Option<serde_json::Value>,
pub unified_code: Option<UnifiedCode>,
pub unified_message: Option<UnifiedMessage>,
pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>,
pub merchant_order_reference_id: Option<String>,
pub payout_connector_metadata: Option<pii::SecretSerdeValue>,
}
#[derive(Clone, Debug, PartialEq)]
pub struct PayoutAttemptNew {
pub payout_attempt_id: String,
pub payout_id: id_type::PayoutId,
pub customer_id: Option<id_type::CustomerId>,
pub merchant_id: id_type::MerchantId,
pub address_id: Option<String>,
pub connector: Option<String>,
pub connector_payout_id: Option<String>,
pub payout_token: Option<String>,
pub status: storage_enums::PayoutStatus,
pub is_eligible: Option<bool>,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub created_at: PrimitiveDateTime,
pub last_modified_at: PrimitiveDateTime,
pub profile_id: id_type::ProfileId,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub routing_info: Option<serde_json::Value>,
pub unified_code: Option<UnifiedCode>,
pub unified_message: Option<UnifiedMessage>,
pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>,
pub merchant_order_reference_id: Option<String>,
pub payout_connector_metadata: Option<pii::SecretSerdeValue>,
}
#[derive(Debug, Clone)]
pub enum PayoutAttemptUpdate {
StatusUpdate {
connector_payout_id: Option<String>,
status: storage_enums::PayoutStatus,
error_message: Option<String>,
error_code: Option<String>,
is_eligible: Option<bool>,
unified_code: Option<UnifiedCode>,
unified_message: Option<UnifiedMessage>,
payout_connector_metadata: Option<pii::SecretSerdeValue>,
},
PayoutTokenUpdate {
payout_token: String,
},
BusinessUpdate {
business_country: Option<storage_enums::CountryAlpha2>,
business_label: Option<String>,
address_id: Option<String>,
customer_id: Option<id_type::CustomerId>,
},
UpdateRouting {
connector: String,
routing_info: Option<serde_json::Value>,
merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
},
AdditionalPayoutMethodDataUpdate {
additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>,
},
}
#[derive(Clone, Debug, Default)]
pub struct PayoutAttemptUpdateInternal {
pub payout_token: Option<String>,
pub connector_payout_id: Option<String>,
pub status: Option<storage_enums::PayoutStatus>,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub is_eligible: Option<bool>,
pub business_country: Option<storage_enums::CountryAlpha2>,
pub business_label: Option<String>,
pub connector: Option<String>,
pub routing_info: Option<serde_json::Value>,
pub address_id: Option<String>,
pub customer_id: Option<id_type::CustomerId>,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub unified_code: Option<UnifiedCode>,
pub unified_message: Option<UnifiedMessage>,
pub additional_payout_method_data: Option<payout_method_utils::AdditionalPayoutMethodData>,
pub payout_connector_metadata: Option<pii::SecretSerdeValue>,
}
impl From<PayoutAttemptUpdate> for PayoutAttemptUpdateInternal {
fn from(payout_update: PayoutAttemptUpdate) -> Self {
match payout_update {
PayoutAttemptUpdate::PayoutTokenUpdate { payout_token } => Self {
payout_token: Some(payout_token),
..Default::default()
},
PayoutAttemptUpdate::StatusUpdate {
connector_payout_id,
status,
error_message,
error_code,
is_eligible,
unified_code,
unified_message,
payout_connector_metadata,
} => Self {
connector_payout_id,
status: Some(status),
error_message,
error_code,
is_eligible,
unified_code,
unified_message,
payout_connector_metadata,
..Default::default()
},
PayoutAttemptUpdate::BusinessUpdate {
business_country,
business_label,
address_id,
customer_id,
} => Self {
business_country,
business_label,
address_id,
customer_id,
..Default::default()
},
PayoutAttemptUpdate::UpdateRouting {
connector,
routing_info,
merchant_connector_id,
} => Self {
connector: Some(connector),
routing_info,
merchant_connector_id,
..Default::default()
},
PayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate {
additional_payout_method_data,
} => Self {
additional_payout_method_data,
..Default::default()
},
}
}
}
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/payouts/payout_attempt.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 4,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_connectors_-65221097743698339
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_connectors
// File: crates/hyperswitch_connectors/src/utils.rs
// Contains: 3 structs, 1 enums
use std::{
collections::{HashMap, HashSet},
marker::PhantomData,
str::FromStr,
sync::LazyLock,
};
use api_models::payments;
#[cfg(feature = "payouts")]
use api_models::payouts::PayoutVendorAccountDetails;
use base64::Engine;
use common_enums::{
enums,
enums::{
AlbaniaStatesAbbreviation, AndorraStatesAbbreviation, AttemptStatus,
AustraliaStatesAbbreviation, AustriaStatesAbbreviation, BelarusStatesAbbreviation,
BelgiumStatesAbbreviation, BosniaAndHerzegovinaStatesAbbreviation,
BrazilStatesAbbreviation, BulgariaStatesAbbreviation, CanadaStatesAbbreviation,
CroatiaStatesAbbreviation, CzechRepublicStatesAbbreviation, DenmarkStatesAbbreviation,
FinlandStatesAbbreviation, FranceStatesAbbreviation, FutureUsage,
GermanyStatesAbbreviation, GreeceStatesAbbreviation, HungaryStatesAbbreviation,
IcelandStatesAbbreviation, IndiaStatesAbbreviation, IrelandStatesAbbreviation,
ItalyStatesAbbreviation, JapanStatesAbbreviation, LatviaStatesAbbreviation,
LiechtensteinStatesAbbreviation, LithuaniaStatesAbbreviation, LuxembourgStatesAbbreviation,
MaltaStatesAbbreviation, MoldovaStatesAbbreviation, MonacoStatesAbbreviation,
MontenegroStatesAbbreviation, NetherlandsStatesAbbreviation, NewZealandStatesAbbreviation,
NorthMacedoniaStatesAbbreviation, NorwayStatesAbbreviation, PhilippinesStatesAbbreviation,
PolandStatesAbbreviation, PortugalStatesAbbreviation, RomaniaStatesAbbreviation,
RussiaStatesAbbreviation, SanMarinoStatesAbbreviation, SerbiaStatesAbbreviation,
SingaporeStatesAbbreviation, SlovakiaStatesAbbreviation, SloveniaStatesAbbreviation,
SpainStatesAbbreviation, SwedenStatesAbbreviation, SwitzerlandStatesAbbreviation,
ThailandStatesAbbreviation, UkraineStatesAbbreviation, UnitedKingdomStatesAbbreviation,
UsStatesAbbreviation,
},
};
use common_utils::{
consts::BASE64_ENGINE,
errors::{CustomResult, ParsingError, ReportSwitchExt},
ext_traits::{OptionExt, StringExt, ValueExt},
id_type,
pii::{self, Email, IpAddress},
types::{AmountConvertor, MinorUnit},
};
use error_stack::{report, ResultExt};
#[cfg(feature = "frm")]
use hyperswitch_domain_models::router_request_types::fraud_check::{
FraudCheckCheckoutData, FraudCheckRecordReturnData, FraudCheckSaleData,
FraudCheckTransactionData,
};
use hyperswitch_domain_models::{
address::{Address, AddressDetails, PhoneDetails},
mandates,
network_tokenization::NetworkTokenNumber,
payment_method_data::{
self, Card, CardDetailsForNetworkTransactionId, GooglePayPaymentMethodInfo,
PaymentMethodData,
},
router_data::{
ErrorResponse, L2L3Data, PaymentMethodToken, RecurringMandatePaymentData,
RouterData as ConnectorRouterData,
},
router_request_types::{
AuthenticationData, AuthoriseIntegrityObject, BrowserInformation, CaptureIntegrityObject,
CompleteAuthorizeData, ConnectorCustomerData, ExternalVaultProxyPaymentsData,
MandateRevokeRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsPostSessionTokensData,
PaymentsPreProcessingData, PaymentsSyncData, RefundIntegrityObject, RefundsData,
ResponseId, SetupMandateRequestData, SyncIntegrityObject,
},
router_response_types::{CaptureSyncResponse, PaymentsResponseData},
types::{OrderDetailsWithAmount, SetupMandateRouterData},
};
use hyperswitch_interfaces::{api, consts, errors, types::Response};
use image::{DynamicImage, ImageBuffer, ImageFormat, Luma, Rgba};
use masking::{ExposeInterface, PeekInterface, Secret};
use quick_xml::{
events::{BytesDecl, BytesText, Event},
Writer,
};
use rand::Rng;
use regex::Regex;
use router_env::logger;
use serde::{Deserialize, Serialize};
use serde_json::Value;
use time::PrimitiveDateTime;
use unicode_normalization::UnicodeNormalization;
#[cfg(feature = "frm")]
use crate::types::FrmTransactionRouterData;
use crate::{constants::UNSUPPORTED_ERROR_MESSAGE, types::RefreshTokenRouterData};
type Error = error_stack::Report<errors::ConnectorError>;
pub(crate) fn construct_not_supported_error_report(
capture_method: enums::CaptureMethod,
connector_name: &'static str,
) -> error_stack::Report<errors::ConnectorError> {
errors::ConnectorError::NotSupported {
message: capture_method.to_string(),
connector: connector_name,
}
.into()
}
pub(crate) fn to_currency_base_unit_with_zero_decimal_check(
amount: i64,
currency: enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_base_unit_with_zero_decimal_check(amount)
.change_context(errors::ConnectorError::RequestEncodingFailed)
}
pub(crate) fn get_timestamp_in_milliseconds(datetime: &PrimitiveDateTime) -> i64 {
let utc_datetime = datetime.assume_utc();
utc_datetime.unix_timestamp() * 1000
}
pub(crate) fn get_amount_as_string(
currency_unit: &api::CurrencyUnit,
amount: i64,
currency: enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
let amount = match currency_unit {
api::CurrencyUnit::Minor => amount.to_string(),
api::CurrencyUnit::Base => to_currency_base_unit(amount, currency)?,
};
Ok(amount)
}
pub(crate) fn base64_decode(data: String) -> Result<Vec<u8>, Error> {
BASE64_ENGINE
.decode(data)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
}
pub(crate) fn to_currency_base_unit(
amount: i64,
currency: enums::Currency,
) -> Result<String, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_base_unit(amount)
.change_context(errors::ConnectorError::ParsingFailed)
}
pub trait ConnectorErrorTypeMapping {
fn get_connector_error_type(
&self,
_error_code: String,
_error_message: String,
) -> ConnectorErrorType {
ConnectorErrorType::UnknownError
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ErrorCodeAndMessage {
pub error_code: String,
pub error_message: String,
}
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Debug)]
//Priority of connector_error_type
pub enum ConnectorErrorType {
UserError = 2,
BusinessError = 3,
TechnicalError = 4,
UnknownError = 1,
}
pub(crate) fn get_error_code_error_message_based_on_priority(
connector: impl ConnectorErrorTypeMapping,
error_list: Vec<ErrorCodeAndMessage>,
) -> Option<ErrorCodeAndMessage> {
let error_type_list = error_list
.iter()
.map(|error| {
connector
.get_connector_error_type(error.error_code.clone(), error.error_message.clone())
})
.collect::<Vec<ConnectorErrorType>>();
let mut error_zip_list = error_list
.iter()
.zip(error_type_list.iter())
.collect::<Vec<(&ErrorCodeAndMessage, &ConnectorErrorType)>>();
error_zip_list.sort_by_key(|&(_, error_type)| error_type);
error_zip_list
.first()
.map(|&(error_code_message, _)| error_code_message)
.cloned()
}
pub trait MultipleCaptureSyncResponse {
fn get_connector_capture_id(&self) -> String;
fn get_capture_attempt_status(&self) -> AttemptStatus;
fn is_capture_response(&self) -> bool;
fn get_connector_reference_id(&self) -> Option<String> {
None
}
fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>>;
}
pub(crate) fn construct_captures_response_hashmap<T>(
capture_sync_response_list: Vec<T>,
) -> CustomResult<HashMap<String, CaptureSyncResponse>, errors::ConnectorError>
where
T: MultipleCaptureSyncResponse,
{
let mut hashmap = HashMap::new();
for capture_sync_response in capture_sync_response_list {
let connector_capture_id = capture_sync_response.get_connector_capture_id();
if capture_sync_response.is_capture_response() {
hashmap.insert(
connector_capture_id.clone(),
CaptureSyncResponse::Success {
resource_id: ResponseId::ConnectorTransactionId(connector_capture_id),
status: capture_sync_response.get_capture_attempt_status(),
connector_response_reference_id: capture_sync_response
.get_connector_reference_id(),
amount: capture_sync_response
.get_amount_captured()
.change_context(errors::ConnectorError::AmountConversionFailed)
.attach_printable(
"failed to convert back captured response amount to minor unit",
)?,
},
);
}
}
Ok(hashmap)
}
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "camelCase")]
pub struct GooglePayWalletData {
#[serde(rename = "type")]
pub pm_type: String,
pub description: String,
pub info: GooglePayPaymentMethodInfo,
pub tokenization_data: common_types::payments::GpayTokenizationData,
}
#[derive(Debug, Serialize)]
pub struct CardMandateInfo {
pub card_exp_month: Secret<String>,
pub card_exp_year: Secret<String>,
}
impl TryFrom<payment_method_data::GooglePayWalletData> for GooglePayWalletData {
type Error = common_utils::errors::ValidationError;
fn try_from(data: payment_method_data::GooglePayWalletData) -> Result<Self, Self::Error> {
let tokenization_data = match data.tokenization_data {
common_types::payments::GpayTokenizationData::Encrypted(encrypted_data) => {
common_types::payments::GpayTokenizationData::Encrypted(
common_types::payments::GpayEcryptedTokenizationData {
token_type: encrypted_data.token_type,
token: encrypted_data.token,
},
)
}
common_types::payments::GpayTokenizationData::Decrypted(_) => {
return Err(common_utils::errors::ValidationError::InvalidValue {
message: "Expected encrypted tokenization data, got decrypted".to_string(),
});
}
};
Ok(Self {
pm_type: data.pm_type,
description: data.description,
info: GooglePayPaymentMethodInfo {
card_network: data.info.card_network,
card_details: data.info.card_details,
assurance_details: data.info.assurance_details,
card_funding_source: data.info.card_funding_source,
},
tokenization_data,
})
}
}
pub(crate) fn get_amount_as_f64(
currency_unit: &api::CurrencyUnit,
amount: i64,
currency: enums::Currency,
) -> Result<f64, error_stack::Report<errors::ConnectorError>> {
let amount = match currency_unit {
api::CurrencyUnit::Base => to_currency_base_unit_asf64(amount, currency)?,
api::CurrencyUnit::Minor => u32::try_from(amount)
.change_context(errors::ConnectorError::ParsingFailed)?
.into(),
};
Ok(amount)
}
pub(crate) fn to_currency_base_unit_asf64(
amount: i64,
currency: enums::Currency,
) -> Result<f64, error_stack::Report<errors::ConnectorError>> {
currency
.to_currency_base_unit_asf64(amount)
.change_context(errors::ConnectorError::ParsingFailed)
}
pub(crate) fn to_connector_meta_from_secret<T>(
connector_meta: Option<Secret<Value>>,
) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
let connector_meta_secret =
connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?;
let json = connector_meta_secret.expose();
json.parse_value(std::any::type_name::<T>()).switch()
}
pub(crate) fn is_manual_capture(capture_method: Option<enums::CaptureMethod>) -> bool {
capture_method == Some(enums::CaptureMethod::Manual)
|| capture_method == Some(enums::CaptureMethod::ManualMultiple)
}
pub(crate) fn generate_random_bytes(length: usize) -> Vec<u8> {
// returns random bytes of length n
let mut rng = rand::thread_rng();
(0..length).map(|_| Rng::gen(&mut rng)).collect()
}
pub(crate) fn missing_field_err(
message: &'static str,
) -> Box<dyn Fn() -> error_stack::Report<errors::ConnectorError> + 'static> {
Box::new(move || {
errors::ConnectorError::MissingRequiredField {
field_name: message,
}
.into()
})
}
pub(crate) fn handle_json_response_deserialization_failure(
res: Response,
connector: &'static str,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
crate::metrics::CONNECTOR_RESPONSE_DESERIALIZATION_FAILURE
.add(1, router_env::metric_attributes!(("connector", connector)));
let response_data = String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
// check for whether the response is in json format
match serde_json::from_str::<Value>(&response_data) {
// in case of unexpected response but in json format
Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?,
// in case of unexpected response but in html or string format
Err(error_msg) => {
logger::error!(deserialization_error=?error_msg);
logger::error!("UNEXPECTED RESPONSE FROM CONNECTOR: {}", response_data);
Ok(ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
message: UNSUPPORTED_ERROR_MESSAGE.to_string(),
reason: Some(response_data),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
}
pub(crate) fn construct_not_implemented_error_report(
capture_method: enums::CaptureMethod,
connector_name: &str,
) -> error_stack::Report<errors::ConnectorError> {
errors::ConnectorError::NotImplemented(format!("{capture_method} for {connector_name}")).into()
}
pub(crate) const SELECTED_PAYMENT_METHOD: &str = "Selected payment method";
pub(crate) fn get_unimplemented_payment_method_error_message(connector: &str) -> String {
format!("{SELECTED_PAYMENT_METHOD} through {connector}")
}
pub(crate) fn to_connector_meta<T>(connector_meta: Option<Value>) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
let json = connector_meta.ok_or_else(missing_field_err("connector_meta_data"))?;
json.parse_value(std::any::type_name::<T>()).switch()
}
#[cfg(feature = "payouts")]
pub(crate) fn to_payout_connector_meta<T>(connector_meta: Option<Value>) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
let json = connector_meta.ok_or_else(missing_field_err("payout_connector_meta_data"))?;
json.parse_value(std::any::type_name::<T>()).switch()
}
pub(crate) fn convert_amount<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
amount: MinorUnit,
currency: enums::Currency,
) -> Result<T, error_stack::Report<errors::ConnectorError>> {
amount_convertor
.convert(amount, currency)
.change_context(errors::ConnectorError::AmountConversionFailed)
}
pub(crate) fn validate_currency(
request_currency: enums::Currency,
merchant_config_currency: Option<enums::Currency>,
) -> Result<(), errors::ConnectorError> {
let merchant_config_currency =
merchant_config_currency.ok_or(errors::ConnectorError::NoConnectorMetaData)?;
if request_currency != merchant_config_currency {
Err(errors::ConnectorError::NotSupported {
message: format!(
"currency {request_currency} is not supported for this merchant account",
),
connector: "Braintree",
})?
}
Ok(())
}
pub(crate) fn convert_back_amount_to_minor_units<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
amount: T,
currency: enums::Currency,
) -> Result<MinorUnit, error_stack::Report<errors::ConnectorError>> {
amount_convertor
.convert_back(amount, currency)
.change_context(errors::ConnectorError::AmountConversionFailed)
}
pub(crate) fn is_payment_failure(status: AttemptStatus) -> bool {
match status {
AttemptStatus::AuthenticationFailed
| AttemptStatus::AuthorizationFailed
| AttemptStatus::CaptureFailed
| AttemptStatus::VoidFailed
| AttemptStatus::Failure
| AttemptStatus::Expired => true,
AttemptStatus::Started
| AttemptStatus::RouterDeclined
| AttemptStatus::AuthenticationPending
| AttemptStatus::AuthenticationSuccessful
| AttemptStatus::Authorized
| AttemptStatus::Charged
| AttemptStatus::Authorizing
| AttemptStatus::CodInitiated
| AttemptStatus::Voided
| AttemptStatus::VoidedPostCharge
| AttemptStatus::VoidInitiated
| AttemptStatus::CaptureInitiated
| AttemptStatus::AutoRefunded
| AttemptStatus::PartialCharged
| AttemptStatus::PartialChargedAndChargeable
| AttemptStatus::Unresolved
| AttemptStatus::Pending
| AttemptStatus::PaymentMethodAwaited
| AttemptStatus::ConfirmationAwaited
| AttemptStatus::DeviceDataCollectionPending
| AttemptStatus::IntegrityFailure
| AttemptStatus::PartiallyAuthorized => false,
}
}
pub fn is_refund_failure(status: enums::RefundStatus) -> bool {
match status {
common_enums::RefundStatus::Failure | common_enums::RefundStatus::TransactionFailure => {
true
}
common_enums::RefundStatus::ManualReview
| common_enums::RefundStatus::Pending
| common_enums::RefundStatus::Success => false,
}
}
// TODO: Make all traits as `pub(crate) trait` once all connectors are moved.
pub trait RouterData {
fn get_billing(&self) -> Result<&Address, Error>;
fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error>;
fn get_billing_phone(&self) -> Result<&PhoneDetails, Error>;
fn get_description(&self) -> Result<String, Error>;
fn get_billing_address(&self) -> Result<&AddressDetails, Error>;
fn get_shipping_address(&self) -> Result<&AddressDetails, Error>;
fn get_shipping_address_with_phone_number(&self) -> Result<&Address, Error>;
fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error>;
fn get_session_token(&self) -> Result<String, Error>;
fn get_billing_first_name(&self) -> Result<Secret<String>, Error>;
fn get_billing_full_name(&self) -> Result<Secret<String>, Error>;
fn get_billing_last_name(&self) -> Result<Secret<String>, Error>;
fn get_billing_line1(&self) -> Result<Secret<String>, Error>;
fn get_billing_line2(&self) -> Result<Secret<String>, Error>;
fn get_billing_zip(&self) -> Result<Secret<String>, Error>;
fn get_billing_state(&self) -> Result<Secret<String>, Error>;
fn get_billing_state_code(&self) -> Result<Secret<String>, Error>;
fn get_billing_city(&self) -> Result<String, Error>;
fn get_billing_email(&self) -> Result<Email, Error>;
fn get_billing_phone_number(&self) -> Result<Secret<String>, Error>;
fn to_connector_meta<T>(&self) -> Result<T, Error>
where
T: serde::de::DeserializeOwned;
fn is_three_ds(&self) -> bool;
fn get_payment_method_token(&self) -> Result<PaymentMethodToken, Error>;
fn get_customer_id(&self) -> Result<id_type::CustomerId, Error>;
fn get_optional_customer_id(&self) -> Option<id_type::CustomerId>;
fn get_connector_customer_id(&self) -> Result<String, Error>;
fn get_preprocessing_id(&self) -> Result<String, Error>;
fn get_recurring_mandate_payment_data(&self) -> Result<RecurringMandatePaymentData, Error>;
#[cfg(feature = "payouts")]
fn get_payout_method_data(&self) -> Result<api_models::payouts::PayoutMethodData, Error>;
#[cfg(feature = "payouts")]
fn get_quote_id(&self) -> Result<String, Error>;
fn get_optional_billing(&self) -> Option<&Address>;
fn get_optional_shipping(&self) -> Option<&Address>;
fn get_optional_shipping_line1(&self) -> Option<Secret<String>>;
fn get_optional_shipping_line2(&self) -> Option<Secret<String>>;
fn get_optional_shipping_line3(&self) -> Option<Secret<String>>;
fn get_optional_shipping_city(&self) -> Option<String>;
fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2>;
fn get_optional_shipping_zip(&self) -> Option<Secret<String>>;
fn get_optional_shipping_state(&self) -> Option<Secret<String>>;
fn get_optional_shipping_first_name(&self) -> Option<Secret<String>>;
fn get_optional_shipping_last_name(&self) -> Option<Secret<String>>;
fn get_optional_shipping_full_name(&self) -> Option<Secret<String>>;
fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>>;
fn get_optional_shipping_phone_number_without_country_code(&self) -> Option<Secret<String>>;
fn get_optional_shipping_email(&self) -> Option<Email>;
fn get_required_shipping_full_name(&self) -> Result<Secret<String>, Error>;
fn get_required_shipping_line1(&self) -> Result<Secret<String>, Error>;
fn get_required_shipping_city(&self) -> Result<String, Error>;
fn get_required_shipping_state(&self) -> Result<Secret<String>, Error>;
fn get_required_shipping_zip(&self) -> Result<Secret<String>, Error>;
fn get_required_shipping_phone_number(&self) -> Result<Secret<String>, Error>;
fn get_optional_billing_full_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_line1(&self) -> Option<Secret<String>>;
fn get_optional_billing_line3(&self) -> Option<Secret<String>>;
fn get_optional_billing_line2(&self) -> Option<Secret<String>>;
fn get_optional_billing_city(&self) -> Option<String>;
fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2>;
fn get_optional_billing_zip(&self) -> Option<Secret<String>>;
fn get_optional_billing_state(&self) -> Option<Secret<String>>;
fn get_optional_billing_state_code(&self) -> Option<Secret<String>>;
fn get_optional_billing_state_2_digit(&self) -> Option<Secret<String>>;
fn get_optional_billing_first_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_last_name(&self) -> Option<Secret<String>>;
fn get_optional_billing_phone_number(&self) -> Option<Secret<String>>;
fn get_optional_billing_email(&self) -> Option<Email>;
fn get_optional_l2_l3_data(&self) -> Option<Box<L2L3Data>>;
}
impl<Flow, Request, Response> RouterData
for hyperswitch_domain_models::router_data::RouterData<Flow, Request, Response>
{
fn get_billing(&self) -> Result<&Address, Error> {
self.address
.get_payment_method_billing()
.ok_or_else(missing_field_err("billing"))
}
fn get_billing_country(&self) -> Result<api_models::enums::CountryAlpha2, Error> {
self.address
.get_payment_method_billing()
.and_then(|a| a.address.as_ref())
.and_then(|ad| ad.country)
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.country",
))
}
fn get_billing_phone(&self) -> Result<&PhoneDetails, Error> {
self.address
.get_payment_method_billing()
.and_then(|a| a.phone.as_ref())
.ok_or_else(missing_field_err("billing.phone"))
}
fn get_optional_billing(&self) -> Option<&Address> {
self.address.get_payment_method_billing()
}
fn get_optional_shipping(&self) -> Option<&Address> {
self.address.get_shipping()
}
fn get_optional_shipping_first_name(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.first_name)
})
}
fn get_optional_shipping_last_name(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.last_name)
})
}
fn get_optional_shipping_full_name(&self) -> Option<Secret<String>> {
self.get_optional_shipping()
.and_then(|shipping_details| shipping_details.address.as_ref())
.and_then(|shipping_address| shipping_address.get_optional_full_name())
}
fn get_optional_shipping_line1(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.line1)
})
}
fn get_optional_shipping_line2(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.line2)
})
}
fn get_optional_shipping_line3(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.line3)
})
}
fn get_optional_shipping_city(&self) -> Option<String> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.city)
})
}
fn get_optional_shipping_state(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.state)
})
}
fn get_optional_shipping_country(&self) -> Option<enums::CountryAlpha2> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.country)
})
}
fn get_optional_shipping_zip(&self) -> Option<Secret<String>> {
self.address.get_shipping().and_then(|shipping_address| {
shipping_address
.clone()
.address
.and_then(|shipping_details| shipping_details.zip)
})
}
fn get_optional_shipping_email(&self) -> Option<Email> {
self.address
.get_shipping()
.and_then(|shipping_address| shipping_address.clone().email)
}
fn get_optional_shipping_phone_number(&self) -> Option<Secret<String>> {
self.address
.get_shipping()
.and_then(|shipping_address| shipping_address.clone().phone)
.and_then(|phone_details| phone_details.get_number_with_country_code().ok())
}
fn get_optional_shipping_phone_number_without_country_code(&self) -> Option<Secret<String>> {
self.address
.get_shipping()
.and_then(|shipping_address| shipping_address.clone().phone)
.and_then(|phone_details| phone_details.get_number().ok())
}
fn get_description(&self) -> Result<String, Error> {
self.description
.clone()
.ok_or_else(missing_field_err("description"))
}
fn get_billing_address(&self) -> Result<&AddressDetails, Error> {
self.address
.get_payment_method_billing()
.as_ref()
.and_then(|a| a.address.as_ref())
.ok_or_else(missing_field_err("billing.address"))
}
fn get_connector_meta(&self) -> Result<pii::SecretSerdeValue, Error> {
self.connector_meta_data
.clone()
.ok_or_else(missing_field_err("connector_meta_data"))
}
fn get_session_token(&self) -> Result<String, Error> {
self.session_token
.clone()
.ok_or_else(missing_field_err("session_token"))
}
fn get_billing_first_name(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.first_name.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.first_name",
))
}
fn get_billing_full_name(&self) -> Result<Secret<String>, Error> {
self.get_optional_billing()
.and_then(|billing_details| billing_details.address.as_ref())
.and_then(|billing_address| billing_address.get_optional_full_name())
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.first_name",
))
}
fn get_billing_last_name(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.last_name.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.last_name",
))
}
fn get_billing_line1(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line1.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.line1",
))
}
fn get_billing_line2(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line2.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.line2",
))
}
fn get_billing_zip(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.zip.clone())
})
.ok_or_else(missing_field_err("payment_method_data.billing.address.zip"))
}
fn get_billing_state(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.state.clone())
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.state",
))
}
fn get_billing_state_code(&self) -> Result<Secret<String>, Error> {
let country = self.get_billing_country()?;
let state = self.get_billing_state()?;
match country {
api_models::enums::CountryAlpha2::US => Ok(Secret::new(
UsStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::CA => Ok(Secret::new(
CanadaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
_ => Ok(state.clone()),
}
}
fn get_billing_city(&self) -> Result<String, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.city)
})
.ok_or_else(missing_field_err(
"payment_method_data.billing.address.city",
))
}
fn get_billing_email(&self) -> Result<Email, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| billing_address.email.clone())
.ok_or_else(missing_field_err("payment_method_data.billing.email"))
}
fn get_billing_phone_number(&self) -> Result<Secret<String>, Error> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| billing_address.clone().phone)
.map(|phone_details| phone_details.get_number_with_country_code())
.transpose()?
.ok_or_else(missing_field_err("payment_method_data.billing.phone"))
}
fn get_optional_billing_line1(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line1)
})
}
fn get_optional_billing_line2(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line2)
})
}
fn get_optional_billing_line3(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.line3)
})
}
fn get_optional_billing_city(&self) -> Option<String> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.city)
})
}
fn get_optional_billing_country(&self) -> Option<enums::CountryAlpha2> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.country)
})
}
fn get_optional_billing_zip(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.zip)
})
}
fn get_optional_billing_state(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.state)
})
}
fn get_optional_billing_state_2_digit(&self) -> Option<Secret<String>> {
self.get_optional_billing_state().and_then(|state| {
if state.clone().expose().len() != 2 {
None
} else {
Some(state)
}
})
}
fn get_optional_billing_state_code(&self) -> Option<Secret<String>> {
self.get_billing_state_code().ok()
}
fn get_optional_billing_first_name(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.first_name)
})
}
fn get_optional_billing_last_name(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.address
.and_then(|billing_details| billing_details.last_name)
})
}
fn get_optional_billing_phone_number(&self) -> Option<Secret<String>> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| {
billing_address
.clone()
.phone
.and_then(|phone_data| phone_data.number)
})
}
fn get_optional_billing_email(&self) -> Option<Email> {
self.address
.get_payment_method_billing()
.and_then(|billing_address| billing_address.clone().email)
}
fn to_connector_meta<T>(&self) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
self.get_connector_meta()?
.parse_value(std::any::type_name::<T>())
.change_context(errors::ConnectorError::NoConnectorMetaData)
}
fn is_three_ds(&self) -> bool {
matches!(self.auth_type, enums::AuthenticationType::ThreeDs)
}
fn get_shipping_address(&self) -> Result<&AddressDetails, Error> {
self.address
.get_shipping()
.and_then(|a| a.address.as_ref())
.ok_or_else(missing_field_err("shipping.address"))
}
fn get_shipping_address_with_phone_number(&self) -> Result<&Address, Error> {
self.address
.get_shipping()
.ok_or_else(missing_field_err("shipping"))
}
fn get_payment_method_token(&self) -> Result<PaymentMethodToken, Error> {
self.payment_method_token
.clone()
.ok_or_else(missing_field_err("payment_method_token"))
}
fn get_customer_id(&self) -> Result<id_type::CustomerId, Error> {
self.customer_id
.to_owned()
.ok_or_else(missing_field_err("customer_id"))
}
fn get_connector_customer_id(&self) -> Result<String, Error> {
self.connector_customer
.to_owned()
.ok_or_else(missing_field_err("connector_customer_id"))
}
fn get_preprocessing_id(&self) -> Result<String, Error> {
self.preprocessing_id
.to_owned()
.ok_or_else(missing_field_err("preprocessing_id"))
}
fn get_recurring_mandate_payment_data(&self) -> Result<RecurringMandatePaymentData, Error> {
self.recurring_mandate_payment_data
.to_owned()
.ok_or_else(missing_field_err("recurring_mandate_payment_data"))
}
fn get_optional_billing_full_name(&self) -> Option<Secret<String>> {
self.get_optional_billing()
.and_then(|billing_details| billing_details.address.as_ref())
.and_then(|billing_address| billing_address.get_optional_full_name())
}
fn get_required_shipping_full_name(&self) -> Result<Secret<String>, Error> {
self.get_optional_shipping_full_name()
.ok_or_else(missing_field_err(
"shipping.address.first_name or shipping.address.last_name",
))
}
fn get_required_shipping_line1(&self) -> Result<Secret<String>, Error> {
self.get_optional_shipping_line1()
.ok_or_else(missing_field_err("shipping.address.line1"))
}
fn get_required_shipping_city(&self) -> Result<String, Error> {
self.get_optional_shipping_city()
.ok_or_else(missing_field_err("shipping.address.city"))
}
fn get_required_shipping_state(&self) -> Result<Secret<String>, Error> {
self.get_optional_shipping_state()
.ok_or_else(missing_field_err("shipping.address.state"))
}
fn get_required_shipping_zip(&self) -> Result<Secret<String>, Error> {
self.get_optional_shipping_zip()
.ok_or_else(missing_field_err("shipping.address.zip"))
}
fn get_required_shipping_phone_number(&self) -> Result<Secret<String>, Error> {
self.get_optional_shipping_phone_number_without_country_code()
.ok_or_else(missing_field_err("shipping.phone.number"))
}
#[cfg(feature = "payouts")]
fn get_payout_method_data(&self) -> Result<api_models::payouts::PayoutMethodData, Error> {
self.payout_method_data
.to_owned()
.ok_or_else(missing_field_err("payout_method_data"))
}
#[cfg(feature = "payouts")]
fn get_quote_id(&self) -> Result<String, Error> {
self.quote_id
.to_owned()
.ok_or_else(missing_field_err("quote_id"))
}
fn get_optional_l2_l3_data(&self) -> Option<Box<L2L3Data>> {
self.l2_l3_data.clone()
}
fn get_optional_customer_id(&self) -> Option<id_type::CustomerId> {
self.customer_id.clone()
}
}
pub trait AccessTokenRequestInfo {
fn get_request_id(&self) -> Result<Secret<String>, Error>;
}
impl AccessTokenRequestInfo for RefreshTokenRouterData {
fn get_request_id(&self) -> Result<Secret<String>, Error> {
self.request
.id
.clone()
.ok_or_else(missing_field_err("request.id"))
}
}
#[derive(Debug, Copy, Clone, strum::Display, Eq, Hash, PartialEq)]
pub enum CardIssuer {
AmericanExpress,
Master,
Maestro,
Visa,
Discover,
DinersClub,
JCB,
CarteBlanche,
CartesBancaires,
UnionPay,
}
pub trait CardData {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>;
fn get_card_expiry_month_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>;
fn get_card_issuer(&self) -> Result<CardIssuer, Error>;
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError>;
fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String>;
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String>;
fn get_expiry_year_4_digit(&self) -> Secret<String>;
fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError>;
fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError>;
fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error>;
fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error>;
fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error>;
fn get_cardholder_name(&self) -> Result<Secret<String>, Error>;
}
impl CardData for Card {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.card_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
fn get_card_expiry_month_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let exp_month = self
.card_exp_month
.peek()
.to_string()
.parse::<u8>()
.map_err(|_| errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
})?;
let month = ::cards::CardExpirationMonth::try_from(exp_month).map_err(|_| {
errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
}
})?;
Ok(Secret::new(month.two_digits()))
}
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.card_number.peek())
}
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
)))
}
fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
year.peek(),
delimiter,
self.card_exp_month.peek()
))
}
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
))
}
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.card_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.card_exp_month.clone().expose();
Ok(Secret::new(format!("{year}{month}")))
}
fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.card_exp_month.clone().expose();
Ok(Secret::new(format!("{month}{year}")))
}
fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
self.card_exp_month
.peek()
.clone()
.parse::<i8>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
self.card_exp_year
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error> {
self.get_expiry_year_4_digit()
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_cardholder_name(&self) -> Result<Secret<String>, Error> {
self.card_holder_name
.clone()
.ok_or_else(missing_field_err("card.card_holder_name"))
}
}
impl CardData for CardDetailsForNetworkTransactionId {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.card_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
fn get_card_expiry_month_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let exp_month = self
.card_exp_month
.peek()
.to_string()
.parse::<u8>()
.map_err(|_| errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
})?;
let month = ::cards::CardExpirationMonth::try_from(exp_month).map_err(|_| {
errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
}
})?;
Ok(Secret::new(month.two_digits()))
}
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.card_number.peek())
}
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
)))
}
fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
year.peek(),
delimiter,
self.card_exp_month.peek()
))
}
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
self.card_exp_month.peek(),
delimiter,
year.peek()
))
}
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.card_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.card_exp_month.clone().expose();
Ok(Secret::new(format!("{year}{month}")))
}
fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.card_exp_month.clone().expose();
Ok(Secret::new(format!("{month}{year}")))
}
fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
self.card_exp_month
.peek()
.clone()
.parse::<i8>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
self.card_exp_year
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error> {
self.get_expiry_year_4_digit()
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_cardholder_name(&self) -> Result<Secret<String>, Error> {
self.card_holder_name
.clone()
.ok_or_else(missing_field_err("card.card_holder_name"))
}
}
#[cfg(feature = "payouts")]
impl CardData for api_models::payouts::ApplePayDecrypt {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.expiry_month.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
fn get_card_expiry_month_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let exp_month = self
.expiry_month
.peek()
.to_string()
.parse::<u8>()
.map_err(|_| errors::ConnectorError::InvalidDataFormat {
field_name: "payout_method_data.apple_pay_decrypt.expiry_month",
})?;
let month = ::cards::CardExpirationMonth::try_from(exp_month).map_err(|_| {
errors::ConnectorError::InvalidDataFormat {
field_name: "payout_method_data.apple_pay_decrypt.expiry_month",
}
})?;
Ok(Secret::new(month.two_digits()))
}
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
Err(errors::ConnectorError::ParsingFailed)
.attach_printable("get_card_issuer is not supported for Applepay Decrypted Payout")
}
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.expiry_month.peek(),
delimiter,
year.peek()
)))
}
fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
year.peek(),
delimiter,
self.expiry_month.peek()
))
}
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
self.expiry_month.peek(),
delimiter,
year.peek()
))
}
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.expiry_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.expiry_month.clone().expose();
Ok(Secret::new(format!("{year}{month}")))
}
fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.expiry_month.clone().expose();
Ok(Secret::new(format!("{month}{year}")))
}
fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
self.expiry_month
.peek()
.clone()
.parse::<i8>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
self.expiry_year
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error> {
self.get_expiry_year_4_digit()
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_cardholder_name(&self) -> Result<Secret<String>, Error> {
self.card_holder_name
.clone()
.ok_or_else(missing_field_err("card.card_holder_name"))
}
}
#[track_caller]
fn get_card_issuer(card_number: &str) -> Result<CardIssuer, Error> {
for (k, v) in CARD_REGEX.iter() {
let regex: Regex = v
.clone()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
if regex.is_match(card_number) {
return Ok(*k);
}
}
Err(error_stack::Report::new(
errors::ConnectorError::NotImplemented("Card Type".into()),
))
}
static CARD_REGEX: LazyLock<HashMap<CardIssuer, Result<Regex, regex::Error>>> = LazyLock::new(
|| {
let mut map = HashMap::new();
// Reference: https://gist.github.com/michaelkeevildown/9096cd3aac9029c4e6e05588448a8841
// [#379]: Determine card issuer from card BIN number
map.insert(CardIssuer::Master, Regex::new(r"^5[1-5][0-9]{14}$"));
map.insert(CardIssuer::AmericanExpress, Regex::new(r"^3[47][0-9]{13}$"));
map.insert(CardIssuer::Visa, Regex::new(r"^4[0-9]{12}(?:[0-9]{3})?$"));
map.insert(CardIssuer::Discover, Regex::new(r"^65[0-9]{14}|64[4-9][0-9]{13}|6011[0-9]{12}|(622(?:12[6-9]|1[3-9][0-9]|[2-8][0-9][0-9]|9[01][0-9]|92[0-5])[0-9]{10})$"));
map.insert(
CardIssuer::Maestro,
Regex::new(r"^(5018|5020|5038|5893|6304|6759|6761|6762|6763)[0-9]{8,15}$"),
);
map.insert(
CardIssuer::DinersClub,
Regex::new(r"^3(?:0[0-5][0-9]{11}|[68][0-9][0-9]{11,13})$"),
);
map.insert(
CardIssuer::JCB,
Regex::new(r"^(3(?:088|096|112|158|337|5(?:2[89]|[3-8][0-9]))\d{12})$"),
);
map.insert(CardIssuer::CarteBlanche, Regex::new(r"^389[0-9]{11}$"));
map.insert(CardIssuer::UnionPay, Regex::new(r"^(62[0-9]{14,17})$"));
map
},
);
pub trait AddressDetailsData {
fn get_first_name(&self) -> Result<&Secret<String>, Error>;
fn get_last_name(&self) -> Result<&Secret<String>, Error>;
fn get_full_name(&self) -> Result<Secret<String>, Error>;
fn get_line1(&self) -> Result<&Secret<String>, Error>;
fn get_city(&self) -> Result<&String, Error>;
fn get_line2(&self) -> Result<&Secret<String>, Error>;
fn get_state(&self) -> Result<&Secret<String>, Error>;
fn get_zip(&self) -> Result<&Secret<String>, Error>;
fn get_country(&self) -> Result<&api_models::enums::CountryAlpha2, Error>;
fn get_combined_address_line(&self) -> Result<Secret<String>, Error>;
fn to_state_code(&self) -> Result<Secret<String>, Error>;
fn to_state_code_as_optional(&self) -> Result<Option<Secret<String>>, Error>;
fn get_optional_city(&self) -> Option<String>;
fn get_optional_line1(&self) -> Option<Secret<String>>;
fn get_optional_line2(&self) -> Option<Secret<String>>;
fn get_optional_line3(&self) -> Option<Secret<String>>;
fn get_optional_first_name(&self) -> Option<Secret<String>>;
fn get_optional_last_name(&self) -> Option<Secret<String>>;
fn get_optional_country(&self) -> Option<api_models::enums::CountryAlpha2>;
fn get_optional_zip(&self) -> Option<Secret<String>>;
fn get_optional_state(&self) -> Option<Secret<String>>;
}
impl AddressDetailsData for AddressDetails {
fn get_first_name(&self) -> Result<&Secret<String>, Error> {
self.first_name
.as_ref()
.ok_or_else(missing_field_err("address.first_name"))
}
fn get_last_name(&self) -> Result<&Secret<String>, Error> {
self.last_name
.as_ref()
.ok_or_else(missing_field_err("address.last_name"))
}
fn get_full_name(&self) -> Result<Secret<String>, Error> {
let first_name = self.get_first_name()?.peek().to_owned();
let last_name = self
.get_last_name()
.ok()
.cloned()
.unwrap_or(Secret::new("".to_string()));
let last_name = last_name.peek();
let full_name = format!("{first_name} {last_name}").trim().to_string();
Ok(Secret::new(full_name))
}
fn get_line1(&self) -> Result<&Secret<String>, Error> {
self.line1
.as_ref()
.ok_or_else(missing_field_err("address.line1"))
}
fn get_city(&self) -> Result<&String, Error> {
self.city
.as_ref()
.ok_or_else(missing_field_err("address.city"))
}
fn get_state(&self) -> Result<&Secret<String>, Error> {
self.state
.as_ref()
.ok_or_else(missing_field_err("address.state"))
}
fn get_line2(&self) -> Result<&Secret<String>, Error> {
self.line2
.as_ref()
.ok_or_else(missing_field_err("address.line2"))
}
fn get_zip(&self) -> Result<&Secret<String>, Error> {
self.zip
.as_ref()
.ok_or_else(missing_field_err("address.zip"))
}
fn get_country(&self) -> Result<&api_models::enums::CountryAlpha2, Error> {
self.country
.as_ref()
.ok_or_else(missing_field_err("address.country"))
}
fn get_combined_address_line(&self) -> Result<Secret<String>, Error> {
Ok(Secret::new(format!(
"{},{}",
self.get_line1()?.peek(),
self.get_line2()?.peek()
)))
}
fn to_state_code(&self) -> Result<Secret<String>, Error> {
let country = self.get_country()?;
let state = self.get_state()?;
match country {
api_models::enums::CountryAlpha2::US => Ok(Secret::new(
UsStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::CA => Ok(Secret::new(
CanadaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::AL => Ok(Secret::new(
AlbaniaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::AD => Ok(Secret::new(
AndorraStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::AT => Ok(Secret::new(
AustriaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::BY => Ok(Secret::new(
BelarusStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::BA => Ok(Secret::new(
BosniaAndHerzegovinaStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::BG => Ok(Secret::new(
BulgariaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::HR => Ok(Secret::new(
CroatiaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::CZ => Ok(Secret::new(
CzechRepublicStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::DK => Ok(Secret::new(
DenmarkStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::FI => Ok(Secret::new(
FinlandStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::FR => Ok(Secret::new(
FranceStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::DE => Ok(Secret::new(
GermanyStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::GR => Ok(Secret::new(
GreeceStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::HU => Ok(Secret::new(
HungaryStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::IS => Ok(Secret::new(
IcelandStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::IE => Ok(Secret::new(
IrelandStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::LV => Ok(Secret::new(
LatviaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::IT => Ok(Secret::new(
ItalyStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::JP => Ok(Secret::new(
JapanStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::LI => Ok(Secret::new(
LiechtensteinStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::LT => Ok(Secret::new(
LithuaniaStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::MT => Ok(Secret::new(
MaltaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::MD => Ok(Secret::new(
MoldovaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::MC => Ok(Secret::new(
MonacoStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::ME => Ok(Secret::new(
MontenegroStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::NL => Ok(Secret::new(
NetherlandsStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::NZ => Ok(Secret::new(
NewZealandStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::MK => Ok(Secret::new(
NorthMacedoniaStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::NO => Ok(Secret::new(
NorwayStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::PL => Ok(Secret::new(
PolandStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::PT => Ok(Secret::new(
PortugalStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::ES => Ok(Secret::new(
SpainStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::CH => Ok(Secret::new(
SwitzerlandStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::GB => Ok(Secret::new(
UnitedKingdomStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::BR => Ok(Secret::new(
BrazilStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::AU => Ok(Secret::new(
AustraliaStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::SG => Ok(Secret::new(
SingaporeStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::TH => Ok(Secret::new(
ThailandStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
api_models::enums::CountryAlpha2::PH => Ok(Secret::new(
PhilippinesStatesAbbreviation::foreign_try_from(state.peek().to_string())?
.to_string(),
)),
api_models::enums::CountryAlpha2::IN => Ok(Secret::new(
IndiaStatesAbbreviation::foreign_try_from(state.peek().to_string())?.to_string(),
)),
_ => Ok(state.clone()),
}
}
fn to_state_code_as_optional(&self) -> Result<Option<Secret<String>>, Error> {
self.state
.as_ref()
.map(|state| {
if state.peek().len() == 2 {
Ok(state.to_owned())
} else {
self.to_state_code()
}
})
.transpose()
}
fn get_optional_city(&self) -> Option<String> {
self.city.clone()
}
fn get_optional_line1(&self) -> Option<Secret<String>> {
self.line1.clone()
}
fn get_optional_line2(&self) -> Option<Secret<String>> {
self.line2.clone()
}
fn get_optional_first_name(&self) -> Option<Secret<String>> {
self.first_name.clone()
}
fn get_optional_last_name(&self) -> Option<Secret<String>> {
self.last_name.clone()
}
fn get_optional_country(&self) -> Option<api_models::enums::CountryAlpha2> {
self.country
}
fn get_optional_line3(&self) -> Option<Secret<String>> {
self.line3.clone()
}
fn get_optional_zip(&self) -> Option<Secret<String>> {
self.zip.clone()
}
fn get_optional_state(&self) -> Option<Secret<String>> {
self.state.clone()
}
}
pub trait AdditionalCardInfo {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>;
}
impl AdditionalCardInfo for payments::AdditionalCardInfo {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding =
self.card_exp_year
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "card_exp_year",
})?;
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
}
pub trait PhoneDetailsData {
fn get_number(&self) -> Result<Secret<String>, Error>;
fn get_country_code(&self) -> Result<String, Error>;
fn get_number_with_country_code(&self) -> Result<Secret<String>, Error>;
fn get_number_with_hash_country_code(&self) -> Result<Secret<String>, Error>;
fn extract_country_code(&self) -> Result<String, Error>;
}
impl PhoneDetailsData for PhoneDetails {
fn get_country_code(&self) -> Result<String, Error> {
self.country_code
.clone()
.ok_or_else(missing_field_err("billing.phone.country_code"))
}
fn extract_country_code(&self) -> Result<String, Error> {
self.get_country_code()
.map(|cc| cc.trim_start_matches('+').to_string())
}
fn get_number(&self) -> Result<Secret<String>, Error> {
self.number
.clone()
.ok_or_else(missing_field_err("billing.phone.number"))
}
fn get_number_with_country_code(&self) -> Result<Secret<String>, Error> {
let number = self.get_number()?;
let country_code = self.get_country_code()?;
Ok(Secret::new(format!("{}{}", country_code, number.peek())))
}
fn get_number_with_hash_country_code(&self) -> Result<Secret<String>, Error> {
let number = self.get_number()?;
let country_code = self.get_country_code()?;
let number_without_plus = country_code.trim_start_matches('+');
Ok(Secret::new(format!(
"{}#{}",
number_without_plus,
number.peek()
)))
}
}
#[cfg(feature = "payouts")]
pub trait PayoutFulfillRequestData {
fn get_connector_payout_id(&self) -> Result<String, Error>;
fn get_connector_transfer_method_id(&self) -> Result<String, Error>;
}
#[cfg(feature = "payouts")]
impl PayoutFulfillRequestData for hyperswitch_domain_models::router_request_types::PayoutsData {
fn get_connector_payout_id(&self) -> Result<String, Error> {
self.connector_payout_id
.clone()
.ok_or_else(missing_field_err("connector_payout_id"))
}
fn get_connector_transfer_method_id(&self) -> Result<String, Error> {
self.connector_transfer_method_id
.clone()
.ok_or_else(missing_field_err("connector_transfer_method_id"))
}
}
pub trait CustomerData {
fn get_email(&self) -> Result<Email, Error>;
fn is_mandate_payment(&self) -> bool;
}
impl CustomerData for ConnectorCustomerData {
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn is_mandate_payment(&self) -> bool {
// We only need to check if the customer acceptance or setup mandate details are present and if the setup future usage is OffSession.
// mandate_reference_id is not needed here as we do not need to check for existing mandates.
self.customer_acceptance.is_some()
&& self.setup_future_usage == Some(FutureUsage::OffSession)
}
}
pub trait PaymentsAuthorizeRequestData {
fn get_optional_language_from_browser_info(&self) -> Option<String>;
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_email(&self) -> Result<Email, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>;
fn get_card(&self) -> Result<Card, Error>;
fn connector_mandate_id(&self) -> Option<String>;
fn is_mandate_payment(&self) -> bool;
fn is_customer_initiated_mandate_payment(&self) -> bool;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_router_return_url(&self) -> Result<String, Error>;
fn is_wallet(&self) -> bool;
fn is_card(&self) -> bool;
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>;
fn get_connector_mandate_id(&self) -> Result<String, Error>;
fn get_connector_mandate_data(&self) -> Option<payments::ConnectorMandateReferenceId>;
fn get_complete_authorize_url(&self) -> Result<String, Error>;
fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>>;
fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error>;
fn get_optional_user_agent(&self) -> Option<String>;
fn get_original_amount(&self) -> i64;
fn get_surcharge_amount(&self) -> Option<i64>;
fn get_tax_on_surcharge_amount(&self) -> Option<i64>;
fn get_total_surcharge_amount(&self) -> Option<i64>;
fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue>;
fn get_authentication_data(&self) -> Result<AuthenticationData, Error>;
fn get_customer_name(&self) -> Result<Secret<String>, Error>;
fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error>;
fn get_card_holder_name_from_additional_payment_method_data(
&self,
) -> Result<Secret<String>, Error>;
fn is_cit_mandate_payment(&self) -> bool;
fn get_optional_network_transaction_id(&self) -> Option<String>;
fn get_optional_email(&self) -> Option<Email>;
fn get_card_network_from_additional_payment_method_data(
&self,
) -> Result<enums::CardNetwork, Error>;
fn get_connector_testing_data(&self) -> Option<pii::SecretSerdeValue>;
fn get_order_id(&self) -> Result<String, errors::ConnectorError>;
fn get_card_mandate_info(&self) -> Result<CardMandateInfo, Error>;
}
impl PaymentsAuthorizeRequestData for PaymentsAuthorizeData {
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_optional_language_from_browser_info(&self) -> Option<String> {
self.browser_info
.clone()
.and_then(|browser_info| browser_info.language)
}
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> {
self.order_details
.clone()
.ok_or_else(missing_field_err("order_details"))
}
fn get_card(&self) -> Result<Card, Error> {
match self.payment_method_data.clone() {
PaymentMethodData::Card(card) => Ok(card),
_ => Err(missing_field_err("card")()),
}
}
fn get_complete_authorize_url(&self) -> Result<String, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
}
fn connector_mandate_id(&self) -> Option<String> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
connector_mandate_ids.get_connector_mandate_id()
}
Some(payments::MandateReferenceId::NetworkMandateId(_))
| None
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None,
})
}
fn is_mandate_payment(&self) -> bool {
((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& (self.setup_future_usage == Some(FutureUsage::OffSession)))
|| self
.mandate_id
.as_ref()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref())
.is_some()
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
fn get_router_return_url(&self) -> Result<String, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))
}
fn is_wallet(&self) -> bool {
matches!(self.payment_method_data, PaymentMethodData::Wallet(_))
}
fn is_card(&self) -> bool {
matches!(self.payment_method_data, PaymentMethodData::Card(_))
}
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> {
self.payment_method_type
.to_owned()
.ok_or_else(missing_field_err("payment_method_type"))
}
fn get_connector_mandate_id(&self) -> Result<String, Error> {
self.connector_mandate_id()
.ok_or_else(missing_field_err("connector_mandate_id"))
}
fn get_connector_mandate_data(&self) -> Option<payments::ConnectorMandateReferenceId> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
Some(connector_mandate_ids.clone())
}
Some(payments::MandateReferenceId::NetworkMandateId(_))
| None
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None,
})
}
fn get_ip_address_as_optional(&self) -> Option<Secret<String, IpAddress>> {
self.browser_info.clone().and_then(|browser_info| {
browser_info
.ip_address
.map(|ip| Secret::new(ip.to_string()))
})
}
fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error> {
let ip_address = self
.browser_info
.clone()
.and_then(|browser_info| browser_info.ip_address);
let val = ip_address.ok_or_else(missing_field_err("browser_info.ip_address"))?;
Ok(Secret::new(val.to_string()))
}
fn get_optional_user_agent(&self) -> Option<String> {
self.browser_info
.clone()
.and_then(|browser_info| browser_info.user_agent)
}
fn get_original_amount(&self) -> i64 {
self.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.original_amount.get_amount_as_i64())
.unwrap_or(self.amount)
}
fn get_surcharge_amount(&self) -> Option<i64> {
self.surcharge_details
.as_ref()
.map(|surcharge_details| surcharge_details.surcharge_amount.get_amount_as_i64())
}
fn get_tax_on_surcharge_amount(&self) -> Option<i64> {
self.surcharge_details.as_ref().map(|surcharge_details| {
surcharge_details
.tax_on_surcharge_amount
.get_amount_as_i64()
})
}
fn get_total_surcharge_amount(&self) -> Option<i64> {
self.surcharge_details.as_ref().map(|surcharge_details| {
surcharge_details
.get_total_surcharge_amount()
.get_amount_as_i64()
})
}
fn is_customer_initiated_mandate_payment(&self) -> bool {
(self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(FutureUsage::OffSession)
}
fn get_metadata_as_object(&self) -> Option<pii::SecretSerdeValue> {
self.metadata.clone().and_then(|meta_data| match meta_data {
Value::Null
| Value::Bool(_)
| Value::Number(_)
| Value::String(_)
| Value::Array(_) => None,
Value::Object(_) => Some(meta_data.into()),
})
}
fn get_authentication_data(&self) -> Result<AuthenticationData, Error> {
self.authentication_data
.clone()
.ok_or_else(missing_field_err("authentication_data"))
}
fn get_customer_name(&self) -> Result<Secret<String>, Error> {
self.customer_name
.clone()
.ok_or_else(missing_field_err("customer_name"))
}
fn get_card_holder_name_from_additional_payment_method_data(
&self,
) -> Result<Secret<String>, Error> {
match &self.additional_payment_method_data {
Some(payments::AdditionalPaymentData::Card(card_data)) => Ok(card_data
.card_holder_name
.clone()
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "card_holder_name",
})?),
_ => Err(errors::ConnectorError::MissingRequiredFields {
field_names: vec!["card_holder_name"],
}
.into()),
}
}
/// Attempts to retrieve the connector mandate reference ID as a `Result<String, Error>`.
fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
connector_mandate_ids.get_connector_mandate_request_reference_id()
}
Some(payments::MandateReferenceId::NetworkMandateId(_))
| None
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None,
})
.ok_or_else(missing_field_err("connector_mandate_request_reference_id"))
}
fn is_cit_mandate_payment(&self) -> bool {
(self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(FutureUsage::OffSession)
}
fn get_optional_network_transaction_id(&self) -> Option<String> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::NetworkMandateId(network_transaction_id)) => {
Some(network_transaction_id.clone())
}
Some(payments::MandateReferenceId::ConnectorMandateId(_))
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_))
| None => None,
})
}
fn get_optional_email(&self) -> Option<Email> {
self.email.clone()
}
fn get_card_network_from_additional_payment_method_data(
&self,
) -> Result<enums::CardNetwork, Error> {
match &self.additional_payment_method_data {
Some(payments::AdditionalPaymentData::Card(card_data)) => Ok(card_data
.card_network
.clone()
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "card_network",
})?),
_ => Err(errors::ConnectorError::MissingRequiredFields {
field_names: vec!["card_network"],
}
.into()),
}
}
fn get_connector_testing_data(&self) -> Option<pii::SecretSerdeValue> {
self.connector_testing_data.clone()
}
fn get_order_id(&self) -> Result<String, errors::ConnectorError> {
self.order_id
.to_owned()
.ok_or(errors::ConnectorError::RequestEncodingFailed)
}
fn get_card_mandate_info(&self) -> Result<CardMandateInfo, Error> {
match &self.additional_payment_method_data {
Some(payments::AdditionalPaymentData::Card(card_data)) => Ok(CardMandateInfo {
card_exp_month: card_data.card_exp_month.clone().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "card_exp_month",
}
})?,
card_exp_year: card_data.card_exp_year.clone().ok_or_else(|| {
errors::ConnectorError::MissingRequiredField {
field_name: "card_exp_year",
}
})?,
}),
_ => Err(errors::ConnectorError::MissingRequiredFields {
field_names: vec!["card_exp_month", "card_exp_year"],
}
.into()),
}
}
}
pub trait PaymentsCaptureRequestData {
fn get_optional_language_from_browser_info(&self) -> Option<String>;
fn is_multiple_capture(&self) -> bool;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
}
impl PaymentsCaptureRequestData for PaymentsCaptureData {
fn is_multiple_capture(&self) -> bool {
self.multiple_capture_data.is_some()
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_optional_language_from_browser_info(&self) -> Option<String> {
self.browser_info
.clone()
.and_then(|browser_info| browser_info.language)
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
}
pub trait PaymentsSyncRequestData {
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError>;
fn is_mandate_payment(&self) -> bool;
fn get_optional_connector_transaction_id(&self) -> Option<String>;
}
impl PaymentsSyncRequestData for PaymentsSyncData {
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
fn get_connector_transaction_id(&self) -> CustomResult<String, errors::ConnectorError> {
match self.connector_transaction_id.clone() {
ResponseId::ConnectorTransactionId(txn_id) => Ok(txn_id),
_ => Err(
common_utils::errors::ValidationError::IncorrectValueProvided {
field_name: "connector_transaction_id",
},
)
.attach_printable("Expected connector transaction ID not found")
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?,
}
}
fn is_mandate_payment(&self) -> bool {
matches!(self.setup_future_usage, Some(FutureUsage::OffSession))
}
fn get_optional_connector_transaction_id(&self) -> Option<String> {
match self.connector_transaction_id.clone() {
ResponseId::ConnectorTransactionId(txn_id) => Some(txn_id),
_ => None,
}
}
}
pub trait PaymentsPostSessionTokensRequestData {
fn is_auto_capture(&self) -> Result<bool, Error>;
}
impl PaymentsPostSessionTokensRequestData for PaymentsPostSessionTokensData {
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| None
| Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
}
pub trait PaymentsCancelRequestData {
fn get_optional_language_from_browser_info(&self) -> Option<String>;
fn get_amount(&self) -> Result<i64, Error>;
fn get_currency(&self) -> Result<enums::Currency, Error>;
fn get_cancellation_reason(&self) -> Result<String, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
}
impl PaymentsCancelRequestData for PaymentsCancelData {
fn get_amount(&self) -> Result<i64, Error> {
self.amount.ok_or_else(missing_field_err("amount"))
}
fn get_currency(&self) -> Result<enums::Currency, Error> {
self.currency.ok_or_else(missing_field_err("currency"))
}
fn get_cancellation_reason(&self) -> Result<String, Error> {
self.cancellation_reason
.clone()
.ok_or_else(missing_field_err("cancellation_reason"))
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_optional_language_from_browser_info(&self) -> Option<String> {
self.browser_info
.clone()
.and_then(|browser_info| browser_info.language)
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
}
pub trait RefundsRequestData {
fn get_optional_language_from_browser_info(&self) -> Option<String>;
fn get_connector_refund_id(&self) -> Result<String, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_connector_metadata(&self) -> Result<Value, Error>;
}
impl RefundsRequestData for RefundsData {
#[track_caller]
fn get_connector_refund_id(&self) -> Result<String, Error> {
self.connector_refund_id
.clone()
.get_required_value("connector_refund_id")
.change_context(errors::ConnectorError::MissingConnectorTransactionID)
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_optional_language_from_browser_info(&self) -> Option<String> {
self.browser_info
.clone()
.and_then(|browser_info| browser_info.language)
}
fn get_connector_metadata(&self) -> Result<Value, Error> {
self.connector_metadata
.clone()
.ok_or_else(missing_field_err("connector_metadata"))
}
}
pub trait PaymentsSetupMandateRequestData {
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_email(&self) -> Result<Email, Error>;
fn get_router_return_url(&self) -> Result<String, Error>;
fn is_card(&self) -> bool;
fn get_return_url(&self) -> Result<String, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_optional_language_from_browser_info(&self) -> Option<String>;
fn get_complete_authorize_url(&self) -> Result<String, Error>;
fn is_auto_capture(&self) -> Result<bool, Error>;
fn is_customer_initiated_mandate_payment(&self) -> bool;
}
impl PaymentsSetupMandateRequestData for SetupMandateRequestData {
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_router_return_url(&self) -> Result<String, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("router_return_url"))
}
fn is_card(&self) -> bool {
matches!(self.payment_method_data, PaymentMethodData::Card(_))
}
fn get_return_url(&self) -> Result<String, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
fn get_optional_language_from_browser_info(&self) -> Option<String> {
self.browser_info
.clone()
.and_then(|browser_info| browser_info.language)
}
fn get_complete_authorize_url(&self) -> Result<String, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
}
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
fn is_customer_initiated_mandate_payment(&self) -> bool {
(self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(FutureUsage::OffSession)
}
}
pub trait PaymentMethodTokenizationRequestData {
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn is_mandate_payment(&self) -> bool;
}
impl PaymentMethodTokenizationRequestData for PaymentMethodTokenizationData {
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn is_mandate_payment(&self) -> bool {
((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& (self.setup_future_usage == Some(FutureUsage::OffSession)))
|| self
.mandate_id
.as_ref()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref())
.is_some()
}
}
pub trait PaymentsCompleteAuthorizeRequestData {
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_email(&self) -> Result<Email, Error>;
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>;
fn get_complete_authorize_url(&self) -> Result<String, Error>;
fn is_mandate_payment(&self) -> bool;
fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error>;
fn is_cit_mandate_payment(&self) -> bool;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_threeds_method_comp_ind(&self) -> Result<payments::ThreeDsCompletionIndicator, Error>;
fn get_connector_mandate_id(&self) -> Option<String>;
}
impl PaymentsCompleteAuthorizeRequestData for CompleteAuthorizeData {
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(_) => Err(errors::ConnectorError::CaptureMethodNotSupported.into()),
}
}
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error> {
self.redirect_response
.as_ref()
.and_then(|res| res.payload.to_owned())
.ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
}
.into(),
)
}
fn get_complete_authorize_url(&self) -> Result<String, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
}
fn is_mandate_payment(&self) -> bool {
((self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(FutureUsage::OffSession))
|| self
.mandate_id
.as_ref()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref())
.is_some()
}
/// Attempts to retrieve the connector mandate reference ID as a `Result<String, Error>`.
fn get_connector_mandate_request_reference_id(&self) -> Result<String, Error> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
connector_mandate_ids.get_connector_mandate_request_reference_id()
}
Some(payments::MandateReferenceId::NetworkMandateId(_))
| None
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None,
})
.ok_or_else(missing_field_err("connector_mandate_request_reference_id"))
}
fn is_cit_mandate_payment(&self) -> bool {
(self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(FutureUsage::OffSession)
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_threeds_method_comp_ind(&self) -> Result<payments::ThreeDsCompletionIndicator, Error> {
self.threeds_method_comp_ind
.clone()
.ok_or_else(missing_field_err("threeds_method_comp_ind"))
}
fn get_connector_mandate_id(&self) -> Option<String> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
connector_mandate_ids.get_connector_mandate_id()
}
Some(payments::MandateReferenceId::NetworkMandateId(_))
| None
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None,
})
}
}
pub trait AddressData {
fn get_optional_full_name(&self) -> Option<Secret<String>>;
fn get_email(&self) -> Result<Email, Error>;
fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error>;
fn get_optional_first_name(&self) -> Option<Secret<String>>;
fn get_optional_last_name(&self) -> Option<Secret<String>>;
}
impl AddressData for Address {
fn get_optional_full_name(&self) -> Option<Secret<String>> {
self.address
.as_ref()
.and_then(|billing_address| billing_address.get_optional_full_name())
}
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_phone_with_country_code(&self) -> Result<Secret<String>, Error> {
self.phone
.clone()
.map(|phone_details| phone_details.get_number_with_country_code())
.transpose()?
.ok_or_else(missing_field_err("phone"))
}
fn get_optional_first_name(&self) -> Option<Secret<String>> {
self.address
.as_ref()
.and_then(|billing_address| billing_address.get_optional_first_name())
}
fn get_optional_last_name(&self) -> Option<Secret<String>> {
self.address
.as_ref()
.and_then(|billing_address| billing_address.get_optional_last_name())
}
}
pub trait PaymentsPreProcessingRequestData {
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error>;
fn get_email(&self) -> Result<Email, Error>;
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error>;
fn get_currency(&self) -> Result<enums::Currency, Error>;
fn get_amount(&self) -> Result<i64, Error>;
fn get_minor_amount(&self) -> Result<MinorUnit, Error>;
fn is_auto_capture(&self) -> Result<bool, Error>;
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_router_return_url(&self) -> Result<String, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
fn get_complete_authorize_url(&self) -> Result<String, Error>;
fn connector_mandate_id(&self) -> Option<String>;
fn get_payment_method_data(&self) -> Result<PaymentMethodData, Error>;
fn is_customer_initiated_mandate_payment(&self) -> bool;
}
impl PaymentsPreProcessingRequestData for PaymentsPreProcessingData {
fn get_email(&self) -> Result<Email, Error> {
self.email.clone().ok_or_else(missing_field_err("email"))
}
fn get_payment_method_type(&self) -> Result<enums::PaymentMethodType, Error> {
self.payment_method_type
.to_owned()
.ok_or_else(missing_field_err("payment_method_type"))
}
fn get_payment_method_data(&self) -> Result<PaymentMethodData, Error> {
self.payment_method_data
.to_owned()
.ok_or_else(missing_field_err("payment_method_data"))
}
fn get_currency(&self) -> Result<enums::Currency, Error> {
self.currency.ok_or_else(missing_field_err("currency"))
}
fn get_amount(&self) -> Result<i64, Error> {
self.amount.ok_or_else(missing_field_err("amount"))
}
// New minor amount function for amount framework
fn get_minor_amount(&self) -> Result<MinorUnit, Error> {
self.minor_amount.ok_or_else(missing_field_err("amount"))
}
fn is_auto_capture(&self) -> Result<bool, Error> {
match self.capture_method {
Some(enums::CaptureMethod::Automatic)
| None
| Some(enums::CaptureMethod::SequentialAutomatic) => Ok(true),
Some(enums::CaptureMethod::Manual) => Ok(false),
Some(enums::CaptureMethod::ManualMultiple) | Some(enums::CaptureMethod::Scheduled) => {
Err(errors::ConnectorError::CaptureMethodNotSupported.into())
}
}
}
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> {
self.order_details
.clone()
.ok_or_else(missing_field_err("order_details"))
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.clone()
.ok_or_else(missing_field_err("webhook_url"))
}
fn get_router_return_url(&self) -> Result<String, Error> {
self.router_return_url
.clone()
.ok_or_else(missing_field_err("return_url"))
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
fn get_complete_authorize_url(&self) -> Result<String, Error> {
self.complete_authorize_url
.clone()
.ok_or_else(missing_field_err("complete_authorize_url"))
}
fn get_redirect_response_payload(&self) -> Result<pii::SecretSerdeValue, Error> {
self.redirect_response
.as_ref()
.and_then(|res| res.payload.to_owned())
.ok_or(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
}
.into(),
)
}
fn connector_mandate_id(&self) -> Option<String> {
self.mandate_id
.as_ref()
.and_then(|mandate_ids| match &mandate_ids.mandate_reference_id {
Some(payments::MandateReferenceId::ConnectorMandateId(connector_mandate_ids)) => {
connector_mandate_ids.get_connector_mandate_id()
}
Some(payments::MandateReferenceId::NetworkMandateId(_))
| None
| Some(payments::MandateReferenceId::NetworkTokenWithNTI(_)) => None,
})
}
fn is_customer_initiated_mandate_payment(&self) -> bool {
(self.customer_acceptance.is_some() || self.setup_mandate_details.is_some())
&& self.setup_future_usage == Some(FutureUsage::OffSession)
}
}
pub trait BrowserInformationData {
fn get_accept_header(&self) -> Result<String, Error>;
fn get_language(&self) -> Result<String, Error>;
fn get_screen_height(&self) -> Result<u32, Error>;
fn get_screen_width(&self) -> Result<u32, Error>;
fn get_color_depth(&self) -> Result<u8, Error>;
fn get_user_agent(&self) -> Result<String, Error>;
fn get_time_zone(&self) -> Result<i32, Error>;
fn get_java_enabled(&self) -> Result<bool, Error>;
fn get_java_script_enabled(&self) -> Result<bool, Error>;
fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error>;
fn get_os_type(&self) -> Result<String, Error>;
fn get_os_version(&self) -> Result<String, Error>;
fn get_device_model(&self) -> Result<String, Error>;
}
impl BrowserInformationData for BrowserInformation {
fn get_ip_address(&self) -> Result<Secret<String, IpAddress>, Error> {
let ip_address = self
.ip_address
.ok_or_else(missing_field_err("browser_info.ip_address"))?;
Ok(Secret::new(ip_address.to_string()))
}
fn get_accept_header(&self) -> Result<String, Error> {
self.accept_header
.clone()
.ok_or_else(missing_field_err("browser_info.accept_header"))
}
fn get_language(&self) -> Result<String, Error> {
self.language
.clone()
.ok_or_else(missing_field_err("browser_info.language"))
}
fn get_screen_height(&self) -> Result<u32, Error> {
self.screen_height
.ok_or_else(missing_field_err("browser_info.screen_height"))
}
fn get_screen_width(&self) -> Result<u32, Error> {
self.screen_width
.ok_or_else(missing_field_err("browser_info.screen_width"))
}
fn get_color_depth(&self) -> Result<u8, Error> {
self.color_depth
.ok_or_else(missing_field_err("browser_info.color_depth"))
}
fn get_user_agent(&self) -> Result<String, Error> {
self.user_agent
.clone()
.ok_or_else(missing_field_err("browser_info.user_agent"))
}
fn get_time_zone(&self) -> Result<i32, Error> {
self.time_zone
.ok_or_else(missing_field_err("browser_info.time_zone"))
}
fn get_java_enabled(&self) -> Result<bool, Error> {
self.java_enabled
.ok_or_else(missing_field_err("browser_info.java_enabled"))
}
fn get_java_script_enabled(&self) -> Result<bool, Error> {
self.java_script_enabled
.ok_or_else(missing_field_err("browser_info.java_script_enabled"))
}
fn get_os_type(&self) -> Result<String, Error> {
self.os_type
.clone()
.ok_or_else(missing_field_err("browser_info.os_type"))
}
fn get_os_version(&self) -> Result<String, Error> {
self.os_version
.clone()
.ok_or_else(missing_field_err("browser_info.os_version"))
}
fn get_device_model(&self) -> Result<String, Error> {
self.device_model
.clone()
.ok_or_else(missing_field_err("browser_info.device_model"))
}
}
pub fn get_header_key_value<'a>(
key: &str,
headers: &'a actix_web::http::header::HeaderMap,
) -> CustomResult<&'a str, errors::ConnectorError> {
get_header_field(headers.get(key))
}
pub fn get_http_header<'a>(
key: &str,
headers: &'a http::HeaderMap,
) -> CustomResult<&'a str, errors::ConnectorError> {
get_header_field(headers.get(key))
}
fn get_header_field(
field: Option<&http::HeaderValue>,
) -> CustomResult<&str, errors::ConnectorError> {
field
.map(|header_value| {
header_value
.to_str()
.change_context(errors::ConnectorError::WebhookSignatureNotFound)
})
.ok_or(report!(
errors::ConnectorError::WebhookSourceVerificationFailed
))?
}
pub trait CryptoData {
fn get_pay_currency(&self) -> Result<String, Error>;
}
impl CryptoData for payment_method_data::CryptoData {
fn get_pay_currency(&self) -> Result<String, Error> {
self.pay_currency
.clone()
.ok_or_else(missing_field_err("crypto_data.pay_currency"))
}
}
#[macro_export]
macro_rules! capture_method_not_supported {
($connector:expr, $capture_method:expr) => {
Err(errors::ConnectorError::NotSupported {
message: format!("{} for selected payment method", $capture_method),
connector: $connector,
}
.into())
};
($connector:expr, $capture_method:expr, $payment_method_type:expr) => {
Err(errors::ConnectorError::NotSupported {
message: format!("{} for {}", $capture_method, $payment_method_type),
connector: $connector,
}
.into())
};
}
#[macro_export]
macro_rules! get_formatted_date_time {
($date_format:tt) => {{
let format = time::macros::format_description!($date_format);
time::OffsetDateTime::now_utc()
.format(&format)
.change_context(ConnectorError::InvalidDateFormat)
}};
}
#[macro_export]
macro_rules! unimplemented_payment_method {
($payment_method:expr, $connector:expr) => {
hyperswitch_interfaces::errors::ConnectorError::NotImplemented(format!(
"{} through {}",
$payment_method, $connector
))
};
($payment_method:expr, $flow:expr, $connector:expr) => {
hyperswitch_interfaces::errors::ConnectorError::NotImplemented(format!(
"{} {} through {}",
$payment_method, $flow, $connector
))
};
}
impl ForeignTryFrom<String> for UsStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "UsStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => {
let binding = value.as_str().to_lowercase();
let state = binding.as_str();
match state {
"alabama" => Ok(Self::AL),
"alaska" => Ok(Self::AK),
"american samoa" => Ok(Self::AS),
"arizona" => Ok(Self::AZ),
"arkansas" => Ok(Self::AR),
"california" => Ok(Self::CA),
"colorado" => Ok(Self::CO),
"connecticut" => Ok(Self::CT),
"delaware" => Ok(Self::DE),
"district of columbia" | "columbia" => Ok(Self::DC),
"federated states of micronesia" | "micronesia" => Ok(Self::FM),
"florida" => Ok(Self::FL),
"georgia" => Ok(Self::GA),
"guam" => Ok(Self::GU),
"hawaii" => Ok(Self::HI),
"idaho" => Ok(Self::ID),
"illinois" => Ok(Self::IL),
"indiana" => Ok(Self::IN),
"iowa" => Ok(Self::IA),
"kansas" => Ok(Self::KS),
"kentucky" => Ok(Self::KY),
"louisiana" => Ok(Self::LA),
"maine" => Ok(Self::ME),
"marshall islands" => Ok(Self::MH),
"maryland" => Ok(Self::MD),
"massachusetts" => Ok(Self::MA),
"michigan" => Ok(Self::MI),
"minnesota" => Ok(Self::MN),
"mississippi" => Ok(Self::MS),
"missouri" => Ok(Self::MO),
"montana" => Ok(Self::MT),
"nebraska" => Ok(Self::NE),
"nevada" => Ok(Self::NV),
"new hampshire" => Ok(Self::NH),
"new jersey" => Ok(Self::NJ),
"new mexico" => Ok(Self::NM),
"new york" => Ok(Self::NY),
"north carolina" => Ok(Self::NC),
"north dakota" => Ok(Self::ND),
"northern mariana islands" => Ok(Self::MP),
"ohio" => Ok(Self::OH),
"oklahoma" => Ok(Self::OK),
"oregon" => Ok(Self::OR),
"palau" => Ok(Self::PW),
"pennsylvania" => Ok(Self::PA),
"puerto rico" => Ok(Self::PR),
"rhode island" => Ok(Self::RI),
"south carolina" => Ok(Self::SC),
"south dakota" => Ok(Self::SD),
"tennessee" => Ok(Self::TN),
"texas" => Ok(Self::TX),
"utah" => Ok(Self::UT),
"vermont" => Ok(Self::VT),
"virgin islands" => Ok(Self::VI),
"virginia" => Ok(Self::VA),
"washington" => Ok(Self::WA),
"west virginia" => Ok(Self::WV),
"wisconsin" => Ok(Self::WI),
"wyoming" => Ok(Self::WY),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
}
}
}
}
}
impl ForeignTryFrom<String> for CanadaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.to_uppercase().clone(), "CanadaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => {
let binding = value.as_str().to_lowercase();
let state = binding.as_str();
match state {
"alberta" => Ok(Self::AB),
"british columbia" => Ok(Self::BC),
"manitoba" => Ok(Self::MB),
"new brunswick" => Ok(Self::NB),
"newfoundland and labrador" | "newfoundland & labrador" => Ok(Self::NL),
"northwest territories" => Ok(Self::NT),
"nova scotia" => Ok(Self::NS),
"nunavut" => Ok(Self::NU),
"ontario" => Ok(Self::ON),
"prince edward island" => Ok(Self::PE),
"quebec" => Ok(Self::QC),
"saskatchewan" => Ok(Self::SK),
"yukon" => Ok(Self::YT),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
}
}
}
}
}
impl ForeignTryFrom<String> for AustraliaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state =
parse_state_enum::<Self>(value, "AustraliaStatesAbbreviation", "address.state")?;
match state.as_str() {
"newsouthwales" => Ok(Self::NSW),
"queensland" => Ok(Self::QLD),
"southaustralia" => Ok(Self::SA),
"westernaustralia" => Ok(Self::WA),
"victoria" => Ok(Self::VIC),
"northernterritory" => Ok(Self::NT),
"australiancapitalterritory" => Ok(Self::ACT),
"tasmania" => Ok(Self::TAS),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
}
}
}
impl ForeignTryFrom<String> for PolandStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "PolandStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Greater Poland" => Ok(Self::GreaterPoland),
"Holy Cross" => Ok(Self::HolyCross),
"Kuyavia-Pomerania" => Ok(Self::KuyaviaPomerania),
"Lesser Poland" => Ok(Self::LesserPoland),
"Lower Silesia" => Ok(Self::LowerSilesia),
"Lublin" => Ok(Self::Lublin),
"Lubusz" => Ok(Self::Lubusz),
"Łódź" => Ok(Self::Łódź),
"Mazovia" => Ok(Self::Mazovia),
"Podlaskie" => Ok(Self::Podlaskie),
"Pomerania" => Ok(Self::Pomerania),
"Silesia" => Ok(Self::Silesia),
"Subcarpathia" => Ok(Self::Subcarpathia),
"Upper Silesia" => Ok(Self::UpperSilesia),
"Warmia-Masuria" => Ok(Self::WarmiaMasuria),
"West Pomerania" => Ok(Self::WestPomerania),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for FranceStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "FranceStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Ain" => Ok(Self::Ain),
"Aisne" => Ok(Self::Aisne),
"Allier" => Ok(Self::Allier),
"Alpes-de-Haute-Provence" => Ok(Self::AlpesDeHauteProvence),
"Alpes-Maritimes" => Ok(Self::AlpesMaritimes),
"Alsace" => Ok(Self::Alsace),
"Ardèche" => Ok(Self::Ardeche),
"Ardennes" => Ok(Self::Ardennes),
"Ariège" => Ok(Self::Ariege),
"Aube" => Ok(Self::Aube),
"Aude" => Ok(Self::Aude),
"Auvergne-Rhône-Alpes" => Ok(Self::AuvergneRhoneAlpes),
"Aveyron" => Ok(Self::Aveyron),
"Bas-Rhin" => Ok(Self::BasRhin),
"Bouches-du-Rhône" => Ok(Self::BouchesDuRhone),
"Bourgogne-Franche-Comté" => Ok(Self::BourgogneFrancheComte),
"Bretagne" => Ok(Self::Bretagne),
"Calvados" => Ok(Self::Calvados),
"Cantal" => Ok(Self::Cantal),
"Centre-Val de Loire" => Ok(Self::CentreValDeLoire),
"Charente" => Ok(Self::Charente),
"Charente-Maritime" => Ok(Self::CharenteMaritime),
"Cher" => Ok(Self::Cher),
"Clipperton" => Ok(Self::Clipperton),
"Corrèze" => Ok(Self::Correze),
"Corse" => Ok(Self::Corse),
"Corse-du-Sud" => Ok(Self::CorseDuSud),
"Côte-d'Or" => Ok(Self::CoteDor),
"Côtes-d'Armor" => Ok(Self::CotesDarmor),
"Creuse" => Ok(Self::Creuse),
"Deux-Sèvres" => Ok(Self::DeuxSevres),
"Dordogne" => Ok(Self::Dordogne),
"Doubs" => Ok(Self::Doubs),
"Drôme" => Ok(Self::Drome),
"Essonne" => Ok(Self::Essonne),
"Eure" => Ok(Self::Eure),
"Eure-et-Loir" => Ok(Self::EureEtLoir),
"Finistère" => Ok(Self::Finistere),
"French Guiana" => Ok(Self::FrenchGuiana),
"French Polynesia" => Ok(Self::FrenchPolynesia),
"French Southern and Antarctic Lands" => Ok(Self::FrenchSouthernAndAntarcticLands),
"Gard" => Ok(Self::Gard),
"Gers" => Ok(Self::Gers),
"Gironde" => Ok(Self::Gironde),
"Grand-Est" => Ok(Self::GrandEst),
"Guadeloupe" => Ok(Self::Guadeloupe),
"Haut-Rhin" => Ok(Self::HautRhin),
"Haute-Corse" => Ok(Self::HauteCorse),
"Haute-Garonne" => Ok(Self::HauteGaronne),
"Haute-Loire" => Ok(Self::HauteLoire),
"Haute-Marne" => Ok(Self::HauteMarne),
"Haute-Saône" => Ok(Self::HauteSaone),
"Haute-Savoie" => Ok(Self::HauteSavoie),
"Haute-Vienne" => Ok(Self::HauteVienne),
"Hautes-Alpes" => Ok(Self::HautesAlpes),
"Hautes-Pyrénées" => Ok(Self::HautesPyrenees),
"Hauts-de-France" => Ok(Self::HautsDeFrance),
"Hauts-de-Seine" => Ok(Self::HautsDeSeine),
"Hérault" => Ok(Self::Herault),
"Île-de-France" => Ok(Self::IleDeFrance),
"Ille-et-Vilaine" => Ok(Self::IlleEtVilaine),
"Indre" => Ok(Self::Indre),
"Indre-et-Loire" => Ok(Self::IndreEtLoire),
"Isère" => Ok(Self::Isere),
"Jura" => Ok(Self::Jura),
"La Réunion" => Ok(Self::LaReunion),
"Landes" => Ok(Self::Landes),
"Loir-et-Cher" => Ok(Self::LoirEtCher),
"Loire" => Ok(Self::Loire),
"Loire-Atlantique" => Ok(Self::LoireAtlantique),
"Loiret" => Ok(Self::Loiret),
"Lot" => Ok(Self::Lot),
"Lot-et-Garonne" => Ok(Self::LotEtGaronne),
"Lozère" => Ok(Self::Lozere),
"Maine-et-Loire" => Ok(Self::MaineEtLoire),
"Manche" => Ok(Self::Manche),
"Marne" => Ok(Self::Marne),
"Martinique" => Ok(Self::Martinique),
"Mayenne" => Ok(Self::Mayenne),
"Mayotte" => Ok(Self::Mayotte),
"Métropole de Lyon" => Ok(Self::MetropoleDeLyon),
"Meurthe-et-Moselle" => Ok(Self::MeurtheEtMoselle),
"Meuse" => Ok(Self::Meuse),
"Morbihan" => Ok(Self::Morbihan),
"Moselle" => Ok(Self::Moselle),
"Nièvre" => Ok(Self::Nievre),
"Nord" => Ok(Self::Nord),
"Normandie" => Ok(Self::Normandie),
"Nouvelle-Aquitaine" => Ok(Self::NouvelleAquitaine),
"Occitanie" => Ok(Self::Occitanie),
"Oise" => Ok(Self::Oise),
"Orne" => Ok(Self::Orne),
"Paris" => Ok(Self::Paris),
"Pas-de-Calais" => Ok(Self::PasDeCalais),
"Pays-de-la-Loire" => Ok(Self::PaysDeLaLoire),
"Provence-Alpes-Côte-d'Azur" => Ok(Self::ProvenceAlpesCoteDazur),
"Puy-de-Dôme" => Ok(Self::PuyDeDome),
"Pyrénées-Atlantiques" => Ok(Self::PyreneesAtlantiques),
"Pyrénées-Orientales" => Ok(Self::PyreneesOrientales),
"Rhône" => Ok(Self::Rhone),
"Saint Pierre and Miquelon" => Ok(Self::SaintPierreAndMiquelon),
"Saint-Barthélemy" => Ok(Self::SaintBarthelemy),
"Saint-Martin" => Ok(Self::SaintMartin),
"Saône-et-Loire" => Ok(Self::SaoneEtLoire),
"Sarthe" => Ok(Self::Sarthe),
"Savoie" => Ok(Self::Savoie),
"Seine-et-Marne" => Ok(Self::SeineEtMarne),
"Seine-Maritime" => Ok(Self::SeineMaritime),
"Seine-Saint-Denis" => Ok(Self::SeineSaintDenis),
"Somme" => Ok(Self::Somme),
"Tarn" => Ok(Self::Tarn),
"Tarn-et-Garonne" => Ok(Self::TarnEtGaronne),
"Territoire de Belfort" => Ok(Self::TerritoireDeBelfort),
"Val-d'Oise" => Ok(Self::ValDoise),
"Val-de-Marne" => Ok(Self::ValDeMarne),
"Var" => Ok(Self::Var),
"Vaucluse" => Ok(Self::Vaucluse),
"Vendée" => Ok(Self::Vendee),
"Vienne" => Ok(Self::Vienne),
"Vosges" => Ok(Self::Vosges),
"Wallis and Futuna" => Ok(Self::WallisAndFutuna),
"Yonne" => Ok(Self::Yonne),
"Yvelines" => Ok(Self::Yvelines),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for GermanyStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "GermanyStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Baden-Württemberg" => Ok(Self::BW),
"Bavaria" => Ok(Self::BY),
"Berlin" => Ok(Self::BE),
"Brandenburg" => Ok(Self::BB),
"Bremen" => Ok(Self::HB),
"Hamburg" => Ok(Self::HH),
"Hessen" => Ok(Self::HE),
"Lower Saxony" => Ok(Self::NI),
"Mecklenburg-Vorpommern" => Ok(Self::MV),
"North Rhine-Westphalia" => Ok(Self::NW),
"Rhineland-Palatinate" => Ok(Self::RP),
"Saarland" => Ok(Self::SL),
"Saxony" => Ok(Self::SN),
"Saxony-Anhalt" => Ok(Self::ST),
"Schleswig-Holstein" => Ok(Self::SH),
"Thuringia" => Ok(Self::TH),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for SpainStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "SpainStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"A Coruña Province" => Ok(Self::ACorunaProvince),
"Albacete Province" => Ok(Self::AlbaceteProvince),
"Alicante Province" => Ok(Self::AlicanteProvince),
"Almería Province" => Ok(Self::AlmeriaProvince),
"Andalusia" => Ok(Self::Andalusia),
"Araba / Álava" => Ok(Self::ArabaAlava),
"Aragon" => Ok(Self::Aragon),
"Badajoz Province" => Ok(Self::BadajozProvince),
"Balearic Islands" => Ok(Self::BalearicIslands),
"Barcelona Province" => Ok(Self::BarcelonaProvince),
"Basque Country" => Ok(Self::BasqueCountry),
"Biscay" => Ok(Self::Biscay),
"Burgos Province" => Ok(Self::BurgosProvince),
"Canary Islands" => Ok(Self::CanaryIslands),
"Cantabria" => Ok(Self::Cantabria),
"Castellón Province" => Ok(Self::CastellonProvince),
"Castile and León" => Ok(Self::CastileAndLeon),
"Castilla-La Mancha" => Ok(Self::CastileLaMancha),
"Catalonia" => Ok(Self::Catalonia),
"Ceuta" => Ok(Self::Ceuta),
"Ciudad Real Province" => Ok(Self::CiudadRealProvince),
"Community of Madrid" => Ok(Self::CommunityOfMadrid),
"Cuenca Province" => Ok(Self::CuencaProvince),
"Cáceres Province" => Ok(Self::CaceresProvince),
"Cádiz Province" => Ok(Self::CadizProvince),
"Córdoba Province" => Ok(Self::CordobaProvince),
"Extremadura" => Ok(Self::Extremadura),
"Galicia" => Ok(Self::Galicia),
"Gipuzkoa" => Ok(Self::Gipuzkoa),
"Girona Province" => Ok(Self::GironaProvince),
"Granada Province" => Ok(Self::GranadaProvince),
"Guadalajara Province" => Ok(Self::GuadalajaraProvince),
"Huelva Province" => Ok(Self::HuelvaProvince),
"Huesca Province" => Ok(Self::HuescaProvince),
"Jaén Province" => Ok(Self::JaenProvince),
"La Rioja" => Ok(Self::LaRioja),
"Las Palmas Province" => Ok(Self::LasPalmasProvince),
"León Province" => Ok(Self::LeonProvince),
"Lleida Province" => Ok(Self::LleidaProvince),
"Lugo Province" => Ok(Self::LugoProvince),
"Madrid Province" => Ok(Self::MadridProvince),
"Melilla" => Ok(Self::Melilla),
"Murcia Province" => Ok(Self::MurciaProvince),
"Málaga Province" => Ok(Self::MalagaProvince),
"Navarre" => Ok(Self::Navarre),
"Ourense Province" => Ok(Self::OurenseProvince),
"Palencia Province" => Ok(Self::PalenciaProvince),
"Pontevedra Province" => Ok(Self::PontevedraProvince),
"Province of Asturias" => Ok(Self::ProvinceOfAsturias),
"Province of Ávila" => Ok(Self::ProvinceOfAvila),
"Region of Murcia" => Ok(Self::RegionOfMurcia),
"Salamanca Province" => Ok(Self::SalamancaProvince),
"Santa Cruz de Tenerife Province" => Ok(Self::SantaCruzDeTenerifeProvince),
"Segovia Province" => Ok(Self::SegoviaProvince),
"Seville Province" => Ok(Self::SevilleProvince),
"Soria Province" => Ok(Self::SoriaProvince),
"Tarragona Province" => Ok(Self::TarragonaProvince),
"Teruel Province" => Ok(Self::TeruelProvince),
"Toledo Province" => Ok(Self::ToledoProvince),
"Valencia Province" => Ok(Self::ValenciaProvince),
"Valencian Community" => Ok(Self::ValencianCommunity),
"Valladolid Province" => Ok(Self::ValladolidProvince),
"Zamora Province" => Ok(Self::ZamoraProvince),
"Zaragoza Province" => Ok(Self::ZaragozaProvince),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for ItalyStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "ItalyStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Abruzzo" => Ok(Self::Abruzzo),
"Aosta Valley" => Ok(Self::AostaValley),
"Apulia" => Ok(Self::Apulia),
"Basilicata" => Ok(Self::Basilicata),
"Benevento Province" => Ok(Self::BeneventoProvince),
"Calabria" => Ok(Self::Calabria),
"Campania" => Ok(Self::Campania),
"Emilia-Romagna" => Ok(Self::EmiliaRomagna),
"Friuli–Venezia Giulia" => Ok(Self::FriuliVeneziaGiulia),
"Lazio" => Ok(Self::Lazio),
"Liguria" => Ok(Self::Liguria),
"Lombardy" => Ok(Self::Lombardy),
"Marche" => Ok(Self::Marche),
"Molise" => Ok(Self::Molise),
"Piedmont" => Ok(Self::Piedmont),
"Sardinia" => Ok(Self::Sardinia),
"Sicily" => Ok(Self::Sicily),
"Trentino-South Tyrol" => Ok(Self::TrentinoSouthTyrol),
"Tuscany" => Ok(Self::Tuscany),
"Umbria" => Ok(Self::Umbria),
"Veneto" => Ok(Self::Veneto),
"Libero consorzio comunale di Agrigento" => Ok(Self::Agrigento),
"Libero consorzio comunale di Caltanissetta" => Ok(Self::Caltanissetta),
"Libero consorzio comunale di Enna" => Ok(Self::Enna),
"Libero consorzio comunale di Ragusa" => Ok(Self::Ragusa),
"Libero consorzio comunale di Siracusa" => Ok(Self::Siracusa),
"Libero consorzio comunale di Trapani" => Ok(Self::Trapani),
"Metropolitan City of Bari" => Ok(Self::Bari),
"Metropolitan City of Bologna" => Ok(Self::Bologna),
"Metropolitan City of Cagliari" => Ok(Self::Cagliari),
"Metropolitan City of Catania" => Ok(Self::Catania),
"Metropolitan City of Florence" => Ok(Self::Florence),
"Metropolitan City of Genoa" => Ok(Self::Genoa),
"Metropolitan City of Messina" => Ok(Self::Messina),
"Metropolitan City of Milan" => Ok(Self::Milan),
"Metropolitan City of Naples" => Ok(Self::Naples),
"Metropolitan City of Palermo" => Ok(Self::Palermo),
"Metropolitan City of Reggio Calabria" => Ok(Self::ReggioCalabria),
"Metropolitan City of Rome" => Ok(Self::Rome),
"Metropolitan City of Turin" => Ok(Self::Turin),
"Metropolitan City of Venice" => Ok(Self::Venice),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for JapanStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state = parse_state_enum::<Self>(value, "JapanStatesAbbreviation", "address.state")?;
match state.as_str() {
"aichi" => Ok(Self::Aichi),
"akita" => Ok(Self::Akita),
"aomori" => Ok(Self::Aomori),
"chiba" => Ok(Self::Chiba),
"ehime" => Ok(Self::Ehime),
"fukui" => Ok(Self::Fukui),
"fukuoka" => Ok(Self::Fukuoka),
"fukushima" | "hukusima" => Ok(Self::Fukushima),
"gifu" => Ok(Self::Gifu),
"gunma" => Ok(Self::Gunma),
"hiroshima" => Ok(Self::Hiroshima),
"hokkaido" => Ok(Self::Hokkaido),
"hyogo" => Ok(Self::Hyogo),
"ibaraki" => Ok(Self::Ibaraki),
"ishikawa" => Ok(Self::Ishikawa),
"iwate" => Ok(Self::Iwate),
"kagawa" => Ok(Self::Kagawa),
"kagoshima" => Ok(Self::Kagoshima),
"kanagawa" => Ok(Self::Kanagawa),
"kochi" => Ok(Self::Kochi),
"kumamoto" => Ok(Self::Kumamoto),
"kyoto" => Ok(Self::Kyoto),
"mie" => Ok(Self::Mie),
"miyagi" => Ok(Self::Miyagi),
"miyazaki" => Ok(Self::Miyazaki),
"nagano" => Ok(Self::Nagano),
"nagasaki" => Ok(Self::Nagasaki),
"nara" => Ok(Self::Nara),
"niigata" => Ok(Self::Niigata),
"oita" => Ok(Self::Oita),
"okayama" => Ok(Self::Okayama),
"okinawa" => Ok(Self::Okinawa),
"osaka" => Ok(Self::Osaka),
"saga" => Ok(Self::Saga),
"saitama" => Ok(Self::Saitama),
"shiga" => Ok(Self::Shiga),
"shimane" => Ok(Self::Shimane),
"shizuoka" => Ok(Self::Shizuoka),
"tochigi" => Ok(Self::Tochigi),
"tokushima" | "tokusima" => Ok(Self::Tokusima),
"tokyo" => Ok(Self::Tokyo),
"tottori" => Ok(Self::Tottori),
"toyama" => Ok(Self::Toyama),
"wakayama" => Ok(Self::Wakayama),
"yamagata" => Ok(Self::Yamagata),
"yamaguchi" => Ok(Self::Yamaguchi),
"yamanashi" => Ok(Self::Yamanashi),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
}
}
}
impl ForeignTryFrom<String> for ThailandStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state = parse_state_enum::<Self>(value, "ThailandStatesAbbreviation", "address.state")?;
match state.as_str() {
"amnatcharoen" => Ok(Self::AmnatCharoen),
"angthong" => Ok(Self::AngThong),
"bangkok" => Ok(Self::Bangkok),
"buengkan" => Ok(Self::BuengKan),
"buriram" => Ok(Self::BuriRam),
"chachoengsao" => Ok(Self::Chachoengsao),
"chainat" => Ok(Self::ChaiNat),
"chaiyaphum" => Ok(Self::Chaiyaphum),
"chanthaburi" => Ok(Self::Chanthaburi),
"chiangmai" => Ok(Self::ChiangMai),
"chiangrai" => Ok(Self::ChiangRai),
"chonburi" => Ok(Self::ChonBuri),
"chumphon" => Ok(Self::Chumphon),
"kalasin" => Ok(Self::Kalasin),
"kamphaengphet" => Ok(Self::KamphaengPhet),
"kanchanaburi" => Ok(Self::Kanchanaburi),
"khonkaen" => Ok(Self::KhonKaen),
"krabi" => Ok(Self::Krabi),
"lampang" => Ok(Self::Lampang),
"lamphun" => Ok(Self::Lamphun),
"loei" => Ok(Self::Loei),
"lopburi" => Ok(Self::LopBuri),
"maehongson" => Ok(Self::MaeHongSon),
"mahasarakham" => Ok(Self::MahaSarakham),
"mukdahan" => Ok(Self::Mukdahan),
"nakhonnayok" => Ok(Self::NakhonNayok),
"nakhonpathom" => Ok(Self::NakhonPathom),
"nakhonphanom" => Ok(Self::NakhonPhanom),
"nakhonratchasima" => Ok(Self::NakhonRatchasima),
"nakhonsawan" => Ok(Self::NakhonSawan),
"nakhonsithammarat" => Ok(Self::NakhonSiThammarat),
"nan" => Ok(Self::Nan),
"narathiwat" => Ok(Self::Narathiwat),
"nongbualamphu" => Ok(Self::NongBuaLamPhu),
"nongkhai" => Ok(Self::NongKhai),
"nonthaburi" => Ok(Self::Nonthaburi),
"pathumthani" => Ok(Self::PathumThani),
"pattani" => Ok(Self::Pattani),
"phangnga" => Ok(Self::Phangnga),
"phatthalung" => Ok(Self::Phatthalung),
"phayao" => Ok(Self::Phayao),
"phatthaya" => Ok(Self::Phatthaya),
"phetchabun" => Ok(Self::Phetchabun),
"phetchaburi" => Ok(Self::Phetchaburi),
"phichit" => Ok(Self::Phichit),
"phitsanulok" => Ok(Self::Phitsanulok),
"phrae" => Ok(Self::Phrae),
"phuket" => Ok(Self::Phuket),
"prachinburi" => Ok(Self::PrachinBuri),
"phranakhonsiayutthaya" => Ok(Self::PhraNakhonSiAyutthaya),
"prachuapkhirikhan" => Ok(Self::PrachuapKhiriKhan),
"ranong" => Ok(Self::Ranong),
"ratchaburi" => Ok(Self::Ratchaburi),
"rayong" => Ok(Self::Rayong),
"roiet" => Ok(Self::RoiEt),
"sakaeo" => Ok(Self::SaKaeo),
"sakonnakhon" => Ok(Self::SakonNakhon),
"samutprakan" => Ok(Self::SamutPrakan),
"samutsakhon" => Ok(Self::SamutSakhon),
"samutsongkhram" => Ok(Self::SamutSongkhram),
"saraburi" => Ok(Self::Saraburi),
"satun" => Ok(Self::Satun),
"sisaket" => Ok(Self::SiSaKet),
"singburi" => Ok(Self::SingBuri),
"songkhla" => Ok(Self::Songkhla),
"sukhothai" => Ok(Self::Sukhothai),
"suphanburi" => Ok(Self::SuphanBuri),
"suratthani" => Ok(Self::SuratThani),
"surin" => Ok(Self::Surin),
"tak" => Ok(Self::Tak),
"trang" => Ok(Self::Trang),
"trat" => Ok(Self::Trat),
"ubonratchathani" => Ok(Self::UbonRatchathani),
"udonthani" => Ok(Self::UdonThani),
"uthaithani" => Ok(Self::UthaiThani),
"uttaradit" => Ok(Self::Uttaradit),
"yala" => Ok(Self::Yala),
"yasothon" => Ok(Self::Yasothon),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
}
}
}
impl ForeignTryFrom<String> for NorwayStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "NorwayStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Akershus" => Ok(Self::Akershus),
"Buskerud" => Ok(Self::Buskerud),
"Finnmark" => Ok(Self::Finnmark),
"Hedmark" => Ok(Self::Hedmark),
"Hordaland" => Ok(Self::Hordaland),
"Jan Mayen" => Ok(Self::JanMayen),
"Møre og Romsdal" => Ok(Self::MoreOgRomsdal),
"Nord-Trøndelag" => Ok(Self::NordTrondelag),
"Nordland" => Ok(Self::Nordland),
"Oppland" => Ok(Self::Oppland),
"Oslo" => Ok(Self::Oslo),
"Rogaland" => Ok(Self::Rogaland),
"Sogn og Fjordane" => Ok(Self::SognOgFjordane),
"Svalbard" => Ok(Self::Svalbard),
"Sør-Trøndelag" => Ok(Self::SorTrondelag),
"Telemark" => Ok(Self::Telemark),
"Troms" => Ok(Self::Troms),
"Trøndelag" => Ok(Self::Trondelag),
"Vest-Agder" => Ok(Self::VestAgder),
"Vestfold" => Ok(Self::Vestfold),
"Østfold" => Ok(Self::Ostfold),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for AlbaniaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "AlbaniaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Berat" => Ok(Self::Berat),
"Dibër" => Ok(Self::Diber),
"Durrës" => Ok(Self::Durres),
"Elbasan" => Ok(Self::Elbasan),
"Fier" => Ok(Self::Fier),
"Gjirokastër" => Ok(Self::Gjirokaster),
"Korçë" => Ok(Self::Korce),
"Kukës" => Ok(Self::Kukes),
"Lezhë" => Ok(Self::Lezhe),
"Shkodër" => Ok(Self::Shkoder),
"Tiranë" => Ok(Self::Tirane),
"Vlorë" => Ok(Self::Vlore),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for AndorraStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "AndorraStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Andorra la Vella" => Ok(Self::AndorraLaVella),
"Canillo" => Ok(Self::Canillo),
"Encamp" => Ok(Self::Encamp),
"Escaldes-Engordany" => Ok(Self::EscaldesEngordany),
"La Massana" => Ok(Self::LaMassana),
"Ordino" => Ok(Self::Ordino),
"Sant Julià de Lòria" => Ok(Self::SantJuliaDeLoria),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for AustriaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "AustriaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Burgenland" => Ok(Self::Burgenland),
"Carinthia" => Ok(Self::Carinthia),
"Lower Austria" => Ok(Self::LowerAustria),
"Salzburg" => Ok(Self::Salzburg),
"Styria" => Ok(Self::Styria),
"Tyrol" => Ok(Self::Tyrol),
"Upper Austria" => Ok(Self::UpperAustria),
"Vienna" => Ok(Self::Vienna),
"Vorarlberg" => Ok(Self::Vorarlberg),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for RomaniaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "RomaniaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Alba" => Ok(Self::Alba),
"Arad County" => Ok(Self::AradCounty),
"Argeș" => Ok(Self::Arges),
"Bacău County" => Ok(Self::BacauCounty),
"Bihor County" => Ok(Self::BihorCounty),
"Bistrița-Năsăud County" => Ok(Self::BistritaNasaudCounty),
"Botoșani County" => Ok(Self::BotosaniCounty),
"Brăila" => Ok(Self::Braila),
"Brașov County" => Ok(Self::BrasovCounty),
"Bucharest" => Ok(Self::Bucharest),
"Buzău County" => Ok(Self::BuzauCounty),
"Caraș-Severin County" => Ok(Self::CarasSeverinCounty),
"Cluj County" => Ok(Self::ClujCounty),
"Constanța County" => Ok(Self::ConstantaCounty),
"Covasna County" => Ok(Self::CovasnaCounty),
"Călărași County" => Ok(Self::CalarasiCounty),
"Dolj County" => Ok(Self::DoljCounty),
"Dâmbovița County" => Ok(Self::DambovitaCounty),
"Galați County" => Ok(Self::GalatiCounty),
"Giurgiu County" => Ok(Self::GiurgiuCounty),
"Gorj County" => Ok(Self::GorjCounty),
"Harghita County" => Ok(Self::HarghitaCounty),
"Hunedoara County" => Ok(Self::HunedoaraCounty),
"Ialomița County" => Ok(Self::IalomitaCounty),
"Iași County" => Ok(Self::IasiCounty),
"Ilfov County" => Ok(Self::IlfovCounty),
"Mehedinți County" => Ok(Self::MehedintiCounty),
"Mureș County" => Ok(Self::MuresCounty),
"Neamț County" => Ok(Self::NeamtCounty),
"Olt County" => Ok(Self::OltCounty),
"Prahova County" => Ok(Self::PrahovaCounty),
"Satu Mare County" => Ok(Self::SatuMareCounty),
"Sibiu County" => Ok(Self::SibiuCounty),
"Suceava County" => Ok(Self::SuceavaCounty),
"Sălaj County" => Ok(Self::SalajCounty),
"Teleorman County" => Ok(Self::TeleormanCounty),
"Timiș County" => Ok(Self::TimisCounty),
"Tulcea County" => Ok(Self::TulceaCounty),
"Vaslui County" => Ok(Self::VasluiCounty),
"Vrancea County" => Ok(Self::VranceaCounty),
"Vâlcea County" => Ok(Self::ValceaCounty),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for PortugalStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "PortugalStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Aveiro District" => Ok(Self::AveiroDistrict),
"Azores" => Ok(Self::Azores),
"Beja District" => Ok(Self::BejaDistrict),
"Braga District" => Ok(Self::BragaDistrict),
"Bragança District" => Ok(Self::BragancaDistrict),
"Castelo Branco District" => Ok(Self::CasteloBrancoDistrict),
"Coimbra District" => Ok(Self::CoimbraDistrict),
"Faro District" => Ok(Self::FaroDistrict),
"Guarda District" => Ok(Self::GuardaDistrict),
"Leiria District" => Ok(Self::LeiriaDistrict),
"Lisbon District" => Ok(Self::LisbonDistrict),
"Madeira" => Ok(Self::Madeira),
"Portalegre District" => Ok(Self::PortalegreDistrict),
"Porto District" => Ok(Self::PortoDistrict),
"Santarém District" => Ok(Self::SantaremDistrict),
"Setúbal District" => Ok(Self::SetubalDistrict),
"Viana do Castelo District" => Ok(Self::VianaDoCasteloDistrict),
"Vila Real District" => Ok(Self::VilaRealDistrict),
"Viseu District" => Ok(Self::ViseuDistrict),
"Évora District" => Ok(Self::EvoraDistrict),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for SwitzerlandStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "SwitzerlandStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Aargau" => Ok(Self::Aargau),
"Appenzell Ausserrhoden" => Ok(Self::AppenzellAusserrhoden),
"Appenzell Innerrhoden" => Ok(Self::AppenzellInnerrhoden),
"Basel-Landschaft" => Ok(Self::BaselLandschaft),
"Canton of Fribourg" => Ok(Self::CantonOfFribourg),
"Canton of Geneva" => Ok(Self::CantonOfGeneva),
"Canton of Jura" => Ok(Self::CantonOfJura),
"Canton of Lucerne" => Ok(Self::CantonOfLucerne),
"Canton of Neuchâtel" => Ok(Self::CantonOfNeuchatel),
"Canton of Schaffhausen" => Ok(Self::CantonOfSchaffhausen),
"Canton of Solothurn" => Ok(Self::CantonOfSolothurn),
"Canton of St. Gallen" => Ok(Self::CantonOfStGallen),
"Canton of Valais" => Ok(Self::CantonOfValais),
"Canton of Vaud" => Ok(Self::CantonOfVaud),
"Canton of Zug" => Ok(Self::CantonOfZug),
"Glarus" => Ok(Self::Glarus),
"Graubünden" => Ok(Self::Graubunden),
"Nidwalden" => Ok(Self::Nidwalden),
"Obwalden" => Ok(Self::Obwalden),
"Schwyz" => Ok(Self::Schwyz),
"Thurgau" => Ok(Self::Thurgau),
"Ticino" => Ok(Self::Ticino),
"Uri" => Ok(Self::Uri),
"canton of Bern" => Ok(Self::CantonOfBern),
"canton of Zürich" => Ok(Self::CantonOfZurich),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for NorthMacedoniaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "NorthMacedoniaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Aerodrom Municipality" => Ok(Self::AerodromMunicipality),
"Aračinovo Municipality" => Ok(Self::AracinovoMunicipality),
"Berovo Municipality" => Ok(Self::BerovoMunicipality),
"Bitola Municipality" => Ok(Self::BitolaMunicipality),
"Bogdanci Municipality" => Ok(Self::BogdanciMunicipality),
"Bogovinje Municipality" => Ok(Self::BogovinjeMunicipality),
"Bosilovo Municipality" => Ok(Self::BosilovoMunicipality),
"Brvenica Municipality" => Ok(Self::BrvenicaMunicipality),
"Butel Municipality" => Ok(Self::ButelMunicipality),
"Centar Municipality" => Ok(Self::CentarMunicipality),
"Centar Župa Municipality" => Ok(Self::CentarZupaMunicipality),
"Debarca Municipality" => Ok(Self::DebarcaMunicipality),
"Delčevo Municipality" => Ok(Self::DelcevoMunicipality),
"Demir Hisar Municipality" => Ok(Self::DemirHisarMunicipality),
"Demir Kapija Municipality" => Ok(Self::DemirKapijaMunicipality),
"Dojran Municipality" => Ok(Self::DojranMunicipality),
"Dolneni Municipality" => Ok(Self::DolneniMunicipality),
"Drugovo Municipality" => Ok(Self::DrugovoMunicipality),
"Gazi Baba Municipality" => Ok(Self::GaziBabaMunicipality),
"Gevgelija Municipality" => Ok(Self::GevgelijaMunicipality),
"Gjorče Petrov Municipality" => Ok(Self::GjorcePetrovMunicipality),
"Gostivar Municipality" => Ok(Self::GostivarMunicipality),
"Gradsko Municipality" => Ok(Self::GradskoMunicipality),
"Greater Skopje" => Ok(Self::GreaterSkopje),
"Ilinden Municipality" => Ok(Self::IlindenMunicipality),
"Jegunovce Municipality" => Ok(Self::JegunovceMunicipality),
"Karbinci" => Ok(Self::Karbinci),
"Karpoš Municipality" => Ok(Self::KarposMunicipality),
"Kavadarci Municipality" => Ok(Self::KavadarciMunicipality),
"Kisela Voda Municipality" => Ok(Self::KiselaVodaMunicipality),
"Kičevo Municipality" => Ok(Self::KicevoMunicipality),
"Konče Municipality" => Ok(Self::KonceMunicipality),
"Kočani Municipality" => Ok(Self::KocaniMunicipality),
"Kratovo Municipality" => Ok(Self::KratovoMunicipality),
"Kriva Palanka Municipality" => Ok(Self::KrivaPalankaMunicipality),
"Krivogaštani Municipality" => Ok(Self::KrivogastaniMunicipality),
"Kruševo Municipality" => Ok(Self::KrusevoMunicipality),
"Kumanovo Municipality" => Ok(Self::KumanovoMunicipality),
"Lipkovo Municipality" => Ok(Self::LipkovoMunicipality),
"Lozovo Municipality" => Ok(Self::LozovoMunicipality),
"Makedonska Kamenica Municipality" => Ok(Self::MakedonskaKamenicaMunicipality),
"Makedonski Brod Municipality" => Ok(Self::MakedonskiBrodMunicipality),
"Mavrovo and Rostuša Municipality" => Ok(Self::MavrovoAndRostusaMunicipality),
"Mogila Municipality" => Ok(Self::MogilaMunicipality),
"Negotino Municipality" => Ok(Self::NegotinoMunicipality),
"Novaci Municipality" => Ok(Self::NovaciMunicipality),
"Novo Selo Municipality" => Ok(Self::NovoSeloMunicipality),
"Ohrid Municipality" => Ok(Self::OhridMunicipality),
"Oslomej Municipality" => Ok(Self::OslomejMunicipality),
"Pehčevo Municipality" => Ok(Self::PehcevoMunicipality),
"Petrovec Municipality" => Ok(Self::PetrovecMunicipality),
"Plasnica Municipality" => Ok(Self::PlasnicaMunicipality),
"Prilep Municipality" => Ok(Self::PrilepMunicipality),
"Probištip Municipality" => Ok(Self::ProbishtipMunicipality),
"Radoviš Municipality" => Ok(Self::RadovisMunicipality),
"Rankovce Municipality" => Ok(Self::RankovceMunicipality),
"Resen Municipality" => Ok(Self::ResenMunicipality),
"Rosoman Municipality" => Ok(Self::RosomanMunicipality),
"Saraj Municipality" => Ok(Self::SarajMunicipality),
"Sopište Municipality" => Ok(Self::SopisteMunicipality),
"Staro Nagoričane Municipality" => Ok(Self::StaroNagoricaneMunicipality),
"Struga Municipality" => Ok(Self::StrugaMunicipality),
"Strumica Municipality" => Ok(Self::StrumicaMunicipality),
"Studeničani Municipality" => Ok(Self::StudenicaniMunicipality),
"Sveti Nikole Municipality" => Ok(Self::SvetiNikoleMunicipality),
"Tearce Municipality" => Ok(Self::TearceMunicipality),
"Tetovo Municipality" => Ok(Self::TetovoMunicipality),
"Valandovo Municipality" => Ok(Self::ValandovoMunicipality),
"Vasilevo Municipality" => Ok(Self::VasilevoMunicipality),
"Veles Municipality" => Ok(Self::VelesMunicipality),
"Vevčani Municipality" => Ok(Self::VevcaniMunicipality),
"Vinica Municipality" => Ok(Self::VinicaMunicipality),
"Vraneštica Municipality" => Ok(Self::VranesticaMunicipality),
"Vrapčište Municipality" => Ok(Self::VrapcisteMunicipality),
"Zajas Municipality" => Ok(Self::ZajasMunicipality),
"Zelenikovo Municipality" => Ok(Self::ZelenikovoMunicipality),
"Zrnovci Municipality" => Ok(Self::ZrnovciMunicipality),
"Čair Municipality" => Ok(Self::CairMunicipality),
"Čaška Municipality" => Ok(Self::CaskaMunicipality),
"Češinovo-Obleševo Municipality" => Ok(Self::CesinovoOblesevoMunicipality),
"Čučer-Sandevo Municipality" => Ok(Self::CucerSandevoMunicipality),
"Štip Municipality" => Ok(Self::StipMunicipality),
"Šuto Orizari Municipality" => Ok(Self::ShutoOrizariMunicipality),
"Želino Municipality" => Ok(Self::ZelinoMunicipality),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for MontenegroStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "MontenegroStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Andrijevica Municipality" => Ok(Self::AndrijevicaMunicipality),
"Bar Municipality" => Ok(Self::BarMunicipality),
"Berane Municipality" => Ok(Self::BeraneMunicipality),
"Bijelo Polje Municipality" => Ok(Self::BijeloPoljeMunicipality),
"Budva Municipality" => Ok(Self::BudvaMunicipality),
"Danilovgrad Municipality" => Ok(Self::DanilovgradMunicipality),
"Gusinje Municipality" => Ok(Self::GusinjeMunicipality),
"Kolašin Municipality" => Ok(Self::KolasinMunicipality),
"Kotor Municipality" => Ok(Self::KotorMunicipality),
"Mojkovac Municipality" => Ok(Self::MojkovacMunicipality),
"Nikšić Municipality" => Ok(Self::NiksicMunicipality),
"Petnjica Municipality" => Ok(Self::PetnjicaMunicipality),
"Plav Municipality" => Ok(Self::PlavMunicipality),
"Pljevlja Municipality" => Ok(Self::PljevljaMunicipality),
"Plužine Municipality" => Ok(Self::PlužineMunicipality),
"Podgorica Municipality" => Ok(Self::PodgoricaMunicipality),
"Rožaje Municipality" => Ok(Self::RožajeMunicipality),
"Tivat Municipality" => Ok(Self::TivatMunicipality),
"Ulcinj Municipality" => Ok(Self::UlcinjMunicipality),
"Žabljak Municipality" => Ok(Self::ŽabljakMunicipality),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for MonacoStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "MonacoStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Monaco" => Ok(Self::Monaco),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for NetherlandsStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "NetherlandsStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Bonaire" => Ok(Self::Bonaire),
"Drenthe" => Ok(Self::Drenthe),
"Flevoland" => Ok(Self::Flevoland),
"Friesland" => Ok(Self::Friesland),
"Gelderland" => Ok(Self::Gelderland),
"Groningen" => Ok(Self::Groningen),
"Limburg" => Ok(Self::Limburg),
"North Brabant" => Ok(Self::NorthBrabant),
"North Holland" => Ok(Self::NorthHolland),
"Overijssel" => Ok(Self::Overijssel),
"Saba" => Ok(Self::Saba),
"Sint Eustatius" => Ok(Self::SintEustatius),
"South Holland" => Ok(Self::SouthHolland),
"Utrecht" => Ok(Self::Utrecht),
"Zeeland" => Ok(Self::Zeeland),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for NewZealandStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state =
parse_state_enum::<Self>(value, "NewZealandStatesAbbreviation", "address.state")?;
match state.as_str() {
"auckland" | "tamakimakaurau" => Ok(Self::Auckland),
"bayofplenty" | "toimoana" => Ok(Self::BayOfPlenty),
"canterbury" | "waitaha" => Ok(Self::Canterbury),
"chathamislandsterritory" | "wharekauri" => Ok(Self::ChathamIslandsTerritory),
"gisborne" | "tetairawhiti" => Ok(Self::Gisborne),
"hawkesbay" | "tematauamaui" => Ok(Self::HawkesBay),
"manawatuwanganui" => Ok(Self::ManawatūWhanganui),
"marlborough" => Ok(Self::Marlborough),
"nelson" | "whakatu" => Ok(Self::Nelson),
"northland" | "tetaitokerau" => Ok(Self::Northland),
"otago" | "otakou" => Ok(Self::Otago),
"southland" | "tetaiaotonga" => Ok(Self::Southland),
"taranaki" => Ok(Self::Taranaki),
"tasman" | "tetaioaorere" => Ok(Self::Tasman),
"waikato" => Ok(Self::Waikato),
"greaterwellington" | "tepanematuataiao" => Ok(Self::GreaterWellington),
"westcoast" | "tetaiopoutini" => Ok(Self::WestCoast),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
}
}
}
impl ForeignTryFrom<String> for SingaporeStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state =
parse_state_enum::<Self>(value, "SingaporeStatesAbbreviation", "address.state")?;
match state.as_str() {
"centralsingapore" => Ok(Self::CentralSingapore),
"northeast" => Ok(Self::NorthEast),
"northwest" => Ok(Self::NorthWest),
"southeast" => Ok(Self::SouthEast),
"southwest" => Ok(Self::SouthWest),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
}
}
}
impl ForeignTryFrom<String> for PhilippinesStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state =
parse_state_enum::<Self>(value, "PhilippinesStatesAbbreviation", "address.state")?;
match state.as_str() {
"abra" => Ok(Self::Abra),
"agusandelnorte" | "hilagangagusan" => Ok(Self::AgusanDelNorte),
"agusandelsur" | "timogagusan" => Ok(Self::AgusanDelSur),
"aklan" => Ok(Self::Aklan),
"albay" => Ok(Self::Albay),
"antique" | "antike" => Ok(Self::Antique),
"apayao" | "apayaw" => Ok(Self::Apayao),
"aurora" => Ok(Self::Aurora),
"autonomousregioninmuslimmindanao" | "nagsasarilingrehiyonngmuslimsamindanaw" => {
Ok(Self::AutonomousRegionInMuslimMindanao)
}
"basilan" => Ok(Self::Basilan),
"bataan" => Ok(Self::Bataan),
"batanes" => Ok(Self::Batanes),
"batangas" => Ok(Self::Batangas),
"benguet" | "benget" => Ok(Self::Benguet),
"bicol" | "rehiyonngbikol" => Ok(Self::Bicol),
"biliran" => Ok(Self::Biliran),
"bohol" => Ok(Self::Bohol),
"bukidnon" => Ok(Self::Bukidnon),
"bulacan" | "bulakan" => Ok(Self::Bulacan),
"cagayan" | "kagayan" => Ok(Self::Cagayan),
"cagayanvalley" | "rehiyonnglambakngkagayan" => Ok(Self::CagayanValley),
"calabarzon" | "rehiyonngcalabarzon" => Ok(Self::Calabarzon),
"camarinesnorte" | "hilagangkamarines" => Ok(Self::CamarinesNorte),
"camarinessur" | "timogkamarines" => Ok(Self::CamarinesSur),
"camiguin" | "kamigin" => Ok(Self::Camiguin),
"capiz" | "kapis" => Ok(Self::Capiz),
"caraga" | "rehiyonngkaraga" => Ok(Self::Caraga),
"catanduanes" | "katanduanes" => Ok(Self::Catanduanes),
"cavite" | "kabite" => Ok(Self::Cavite),
"cebu" | "sebu" => Ok(Self::Cebu),
"centralluzon" | "rehiyonnggitnangluzon" => Ok(Self::CentralLuzon),
"centralvisayas" | "rehiyonnggitnangbisaya" => Ok(Self::CentralVisayas),
"cordilleraadministrativeregion" | "rehiyonngadministratibongkordilyera" => {
Ok(Self::CordilleraAdministrativeRegion)
}
"cotabato" | "kotabato" => Ok(Self::Cotabato),
"davao" | "rehiyonngdabaw" => Ok(Self::Davao),
"davaooccidental" | "kanlurangdabaw" => Ok(Self::DavaoOccidental),
"davaooriental" | "silangangdabaw" => Ok(Self::DavaoOriental),
"davaodeoro" => Ok(Self::DavaoDeOro),
"davaodelnorte" | "hilagangdabaw" => Ok(Self::DavaoDelNorte),
"davaodelsur" | "timogdabaw" => Ok(Self::DavaoDelSur),
"dinagatislands" | "pulongdinagat" => Ok(Self::DinagatIslands),
"easternsamar" | "silangangsamar" => Ok(Self::EasternSamar),
"easternvisayas" | "rehiyonngsilangangbisaya" => Ok(Self::EasternVisayas),
"guimaras" | "gimaras" => Ok(Self::Guimaras),
"hilagangiloko" | "ilocosnorte" => Ok(Self::HilagangIloko),
"hilaganglanaw" | "lanaodelnorte" => Ok(Self::HilagangLanaw),
"hilagangmagindanaw" | "maguindanaodelnorte" => Ok(Self::HilagangMagindanaw),
"hilagangsamar" | "northernsamar" => Ok(Self::HilagangSamar),
"hilagangsambuwangga" | "zamboangadelnorte" => Ok(Self::HilagangSambuwangga),
"hilagangsurigaw" | "surigaodelnorte" => Ok(Self::HilagangSurigaw),
"ifugao" | "ipugaw" => Ok(Self::Ifugao),
"ilocos" | "rehiyonngiloko" => Ok(Self::Ilocos),
"ilocossur" | "timogiloko" => Ok(Self::IlocosSur),
"iloilo" | "iloylo" => Ok(Self::Iloilo),
"isabela" => Ok(Self::Isabela),
"kalinga" => Ok(Self::Kalinga),
"kanlurangmindoro" | "mindorooccidental" => Ok(Self::KanlurangMindoro),
"kanlurangmisamis" | "misamisoriental" => Ok(Self::KanlurangMisamis),
"kanlurangnegros" | "negrosoccidental" => Ok(Self::KanlurangNegros),
"katimogangleyte" | "southernleyte" => Ok(Self::KatimogangLeyte),
"keson" | "quezon" => Ok(Self::Keson),
"kirino" | "quirino" => Ok(Self::Kirino),
"launion" => Ok(Self::LaUnion),
"laguna" => Ok(Self::Laguna),
"lalawigangbulubundukin" | "mountainprovince" => Ok(Self::LalawigangBulubundukin),
"lanaodelsur" | "timoglanaw" => Ok(Self::LanaoDelSur),
"leyte" => Ok(Self::Leyte),
"maguidanaodelsur" | "timogmaguindanao" => Ok(Self::MaguindanaoDelSur),
"marinduque" => Ok(Self::Marinduque),
"masbate" => Ok(Self::Masbate),
"mimaropa" | "rehiyonngmimaropa" => Ok(Self::Mimaropa),
"mindorooriental" | "silingangmindoro" => Ok(Self::MindoroOriental),
"misamisoccidental" | "silingangmisamis" => Ok(Self::MisamisOccidental),
"nationalcapitalregion" | "pambansangpunonglungsod" => Ok(Self::NationalCapitalRegion),
"negrosoriental" | "silingangnegros" => Ok(Self::NegrosOriental),
"northernmindanao" | "rehiyonnghilagangmindanao" => Ok(Self::NorthernMindanao),
"nuevaecija" | "nuwevaesiha" => Ok(Self::NuevaEcija),
"nuevavizcaya" => Ok(Self::NuevaVizcaya),
"palawan" => Ok(Self::Palawan),
"pampanga" => Ok(Self::Pampanga),
"pangasinan" => Ok(Self::Pangasinan),
"rehiyonngkanlurangbisaya" | "westernvisayas" => Ok(Self::RehiyonNgKanlurangBisaya),
"rehiyonngsoccsksargen" | "soccsksargen" => Ok(Self::RehiyonNgSoccsksargen),
"rehiyonngtangwayngsambuwangga" | "zamboangapeninsula" => {
Ok(Self::RehiyonNgTangwayNgSambuwangga)
}
"risal" | "rizal" => Ok(Self::Risal),
"romblon" => Ok(Self::Romblon),
"samar" => Ok(Self::Samar),
"sambales" | "zambales" => Ok(Self::Sambales),
"sambuwanggasibugay" | "zamboangasibugay" => Ok(Self::SambuwanggaSibugay),
"sarangani" => Ok(Self::Sarangani),
"siquijor" | "sikihor" => Ok(Self::Sikihor),
"sorsogon" => Ok(Self::Sorsogon),
"southcotabato" | "timogkotabato" => Ok(Self::SouthCotabato),
"sultankudarat" => Ok(Self::SultanKudarat),
"sulu" => Ok(Self::Sulu),
"surigaodelsur" | "timogsurigaw" => Ok(Self::SurigaoDelSur),
"tarlac" => Ok(Self::Tarlac),
"tawitawi" => Ok(Self::TawiTawi),
"timogsambuwangga" | "zamboangadelsur" => Ok(Self::TimogSambuwangga),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
}
}
}
impl ForeignTryFrom<String> for IndiaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state = parse_state_enum::<Self>(value, "IndiaStatesAbbreviation", "address.state")?;
match state.as_str() {
"andamanandnicobarislands" => Ok(Self::AndamanAndNicobarIslands),
"andhrapradesh" => Ok(Self::AndhraPradesh),
"arunachalpradesh" => Ok(Self::ArunachalPradesh),
"assam" => Ok(Self::Assam),
"bihar" => Ok(Self::Bihar),
"chandigarh" => Ok(Self::Chandigarh),
"chhattisgarh" => Ok(Self::Chhattisgarh),
"dadraandnagarhavelianddamananddiu" => Ok(Self::DadraAndNagarHaveliAndDamanAndDiu),
"delhi" => Ok(Self::Delhi),
"goa" => Ok(Self::Goa),
"gujarat" => Ok(Self::Gujarat),
"haryana" => Ok(Self::Haryana),
"himachalpradesh" => Ok(Self::HimachalPradesh),
"jammuandkashmir" => Ok(Self::JammuAndKashmir),
"jharkhand" => Ok(Self::Jharkhand),
"karnataka" => Ok(Self::Karnataka),
"kerala" => Ok(Self::Kerala),
"ladakh" => Ok(Self::Ladakh),
"lakshadweep" => Ok(Self::Lakshadweep),
"madhyapradesh" => Ok(Self::MadhyaPradesh),
"maharashtra" => Ok(Self::Maharashtra),
"manipur" => Ok(Self::Manipur),
"meghalaya" => Ok(Self::Meghalaya),
"mizoram" => Ok(Self::Mizoram),
"nagaland" => Ok(Self::Nagaland),
"odisha" => Ok(Self::Odisha),
"puducherry" | "pondicherry" => Ok(Self::Puducherry),
"punjab" => Ok(Self::Punjab),
"rajasthan" => Ok(Self::Rajasthan),
"sikkim" => Ok(Self::Sikkim),
"tamilnadu" => Ok(Self::TamilNadu),
"telangana" => Ok(Self::Telangana),
"tripura" => Ok(Self::Tripura),
"uttarpradesh" => Ok(Self::UttarPradesh),
"uttarakhand" => Ok(Self::Uttarakhand),
"westbengal" => Ok(Self::WestBengal),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
}
}
}
impl ForeignTryFrom<String> for MoldovaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "MoldovaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Anenii Noi District" => Ok(Self::AneniiNoiDistrict),
"Basarabeasca District" => Ok(Self::BasarabeascaDistrict),
"Bender Municipality" => Ok(Self::BenderMunicipality),
"Briceni District" => Ok(Self::BriceniDistrict),
"Bălți Municipality" => Ok(Self::BălțiMunicipality),
"Cahul District" => Ok(Self::CahulDistrict),
"Cantemir District" => Ok(Self::CantemirDistrict),
"Chișinău Municipality" => Ok(Self::ChișinăuMunicipality),
"Cimișlia District" => Ok(Self::CimișliaDistrict),
"Criuleni District" => Ok(Self::CriuleniDistrict),
"Călărași District" => Ok(Self::CălărașiDistrict),
"Căușeni District" => Ok(Self::CăușeniDistrict),
"Dondușeni District" => Ok(Self::DondușeniDistrict),
"Drochia District" => Ok(Self::DrochiaDistrict),
"Dubăsari District" => Ok(Self::DubăsariDistrict),
"Edineț District" => Ok(Self::EdinețDistrict),
"Florești District" => Ok(Self::FloreștiDistrict),
"Fălești District" => Ok(Self::FăleștiDistrict),
"Găgăuzia" => Ok(Self::Găgăuzia),
"Glodeni District" => Ok(Self::GlodeniDistrict),
"Hîncești District" => Ok(Self::HînceștiDistrict),
"Ialoveni District" => Ok(Self::IaloveniDistrict),
"Nisporeni District" => Ok(Self::NisporeniDistrict),
"Ocnița District" => Ok(Self::OcnițaDistrict),
"Orhei District" => Ok(Self::OrheiDistrict),
"Rezina District" => Ok(Self::RezinaDistrict),
"Rîșcani District" => Ok(Self::RîșcaniDistrict),
"Soroca District" => Ok(Self::SorocaDistrict),
"Strășeni District" => Ok(Self::StrășeniDistrict),
"Sîngerei District" => Ok(Self::SîngereiDistrict),
"Taraclia District" => Ok(Self::TaracliaDistrict),
"Telenești District" => Ok(Self::TeleneștiDistrict),
"Transnistria Autonomous Territorial Unit" => {
Ok(Self::TransnistriaAutonomousTerritorialUnit)
}
"Ungheni District" => Ok(Self::UngheniDistrict),
"Șoldănești District" => Ok(Self::ȘoldăneștiDistrict),
"Ștefan Vodă District" => Ok(Self::ȘtefanVodăDistrict),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for LithuaniaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "LithuaniaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Akmenė District Municipality" => Ok(Self::AkmeneDistrictMunicipality),
"Alytus City Municipality" => Ok(Self::AlytusCityMunicipality),
"Alytus County" => Ok(Self::AlytusCounty),
"Alytus District Municipality" => Ok(Self::AlytusDistrictMunicipality),
"Birštonas Municipality" => Ok(Self::BirstonasMunicipality),
"Biržai District Municipality" => Ok(Self::BirzaiDistrictMunicipality),
"Druskininkai municipality" => Ok(Self::DruskininkaiMunicipality),
"Elektrėnai municipality" => Ok(Self::ElektrenaiMunicipality),
"Ignalina District Municipality" => Ok(Self::IgnalinaDistrictMunicipality),
"Jonava District Municipality" => Ok(Self::JonavaDistrictMunicipality),
"Joniškis District Municipality" => Ok(Self::JoniskisDistrictMunicipality),
"Jurbarkas District Municipality" => Ok(Self::JurbarkasDistrictMunicipality),
"Kaišiadorys District Municipality" => Ok(Self::KaisiadorysDistrictMunicipality),
"Kalvarija municipality" => Ok(Self::KalvarijaMunicipality),
"Kaunas City Municipality" => Ok(Self::KaunasCityMunicipality),
"Kaunas County" => Ok(Self::KaunasCounty),
"Kaunas District Municipality" => Ok(Self::KaunasDistrictMunicipality),
"Kazlų Rūda municipality" => Ok(Self::KazluRudaMunicipality),
"Kelmė District Municipality" => Ok(Self::KelmeDistrictMunicipality),
"Klaipeda City Municipality" => Ok(Self::KlaipedaCityMunicipality),
"Klaipėda County" => Ok(Self::KlaipedaCounty),
"Klaipėda District Municipality" => Ok(Self::KlaipedaDistrictMunicipality),
"Kretinga District Municipality" => Ok(Self::KretingaDistrictMunicipality),
"Kupiškis District Municipality" => Ok(Self::KupiskisDistrictMunicipality),
"Kėdainiai District Municipality" => Ok(Self::KedainiaiDistrictMunicipality),
"Lazdijai District Municipality" => Ok(Self::LazdijaiDistrictMunicipality),
"Marijampolė County" => Ok(Self::MarijampoleCounty),
"Marijampolė Municipality" => Ok(Self::MarijampoleMunicipality),
"Mažeikiai District Municipality" => Ok(Self::MazeikiaiDistrictMunicipality),
"Molėtai District Municipality" => Ok(Self::MoletaiDistrictMunicipality),
"Neringa Municipality" => Ok(Self::NeringaMunicipality),
"Pagėgiai municipality" => Ok(Self::PagegiaiMunicipality),
"Pakruojis District Municipality" => Ok(Self::PakruojisDistrictMunicipality),
"Palanga City Municipality" => Ok(Self::PalangaCityMunicipality),
"Panevėžys City Municipality" => Ok(Self::PanevezysCityMunicipality),
"Panevėžys County" => Ok(Self::PanevezysCounty),
"Panevėžys District Municipality" => Ok(Self::PanevezysDistrictMunicipality),
"Pasvalys District Municipality" => Ok(Self::PasvalysDistrictMunicipality),
"Plungė District Municipality" => Ok(Self::PlungeDistrictMunicipality),
"Prienai District Municipality" => Ok(Self::PrienaiDistrictMunicipality),
"Radviliškis District Municipality" => Ok(Self::RadviliskisDistrictMunicipality),
"Raseiniai District Municipality" => Ok(Self::RaseiniaiDistrictMunicipality),
"Rietavas municipality" => Ok(Self::RietavasMunicipality),
"Rokiškis District Municipality" => Ok(Self::RokiskisDistrictMunicipality),
"Skuodas District Municipality" => Ok(Self::SkuodasDistrictMunicipality),
"Tauragė County" => Ok(Self::TaurageCounty),
"Tauragė District Municipality" => Ok(Self::TaurageDistrictMunicipality),
"Telšiai County" => Ok(Self::TelsiaiCounty),
"Telšiai District Municipality" => Ok(Self::TelsiaiDistrictMunicipality),
"Trakai District Municipality" => Ok(Self::TrakaiDistrictMunicipality),
"Ukmergė District Municipality" => Ok(Self::UkmergeDistrictMunicipality),
"Utena County" => Ok(Self::UtenaCounty),
"Utena District Municipality" => Ok(Self::UtenaDistrictMunicipality),
"Varėna District Municipality" => Ok(Self::VarenaDistrictMunicipality),
"Vilkaviškis District Municipality" => Ok(Self::VilkaviskisDistrictMunicipality),
"Vilnius City Municipality" => Ok(Self::VilniusCityMunicipality),
"Vilnius County" => Ok(Self::VilniusCounty),
"Vilnius District Municipality" => Ok(Self::VilniusDistrictMunicipality),
"Visaginas Municipality" => Ok(Self::VisaginasMunicipality),
"Zarasai District Municipality" => Ok(Self::ZarasaiDistrictMunicipality),
"Šakiai District Municipality" => Ok(Self::SakiaiDistrictMunicipality),
"Šalčininkai District Municipality" => Ok(Self::SalcininkaiDistrictMunicipality),
"Šiauliai City Municipality" => Ok(Self::SiauliaiCityMunicipality),
"Šiauliai County" => Ok(Self::SiauliaiCounty),
"Šiauliai District Municipality" => Ok(Self::SiauliaiDistrictMunicipality),
"Šilalė District Municipality" => Ok(Self::SilaleDistrictMunicipality),
"Šilutė District Municipality" => Ok(Self::SiluteDistrictMunicipality),
"Širvintos District Municipality" => Ok(Self::SirvintosDistrictMunicipality),
"Švenčionys District Municipality" => Ok(Self::SvencionysDistrictMunicipality),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for LiechtensteinStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "LiechtensteinStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Balzers" => Ok(Self::Balzers),
"Eschen" => Ok(Self::Eschen),
"Gamprin" => Ok(Self::Gamprin),
"Mauren" => Ok(Self::Mauren),
"Planken" => Ok(Self::Planken),
"Ruggell" => Ok(Self::Ruggell),
"Schaan" => Ok(Self::Schaan),
"Schellenberg" => Ok(Self::Schellenberg),
"Triesen" => Ok(Self::Triesen),
"Triesenberg" => Ok(Self::Triesenberg),
"Vaduz" => Ok(Self::Vaduz),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for LatviaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "LatviaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Aglona Municipality" => Ok(Self::AglonaMunicipality),
"Aizkraukle Municipality" => Ok(Self::AizkraukleMunicipality),
"Aizpute Municipality" => Ok(Self::AizputeMunicipality),
"Aknīste Municipality" => Ok(Self::AknīsteMunicipality),
"Aloja Municipality" => Ok(Self::AlojaMunicipality),
"Alsunga Municipality" => Ok(Self::AlsungaMunicipality),
"Alūksne Municipality" => Ok(Self::AlūksneMunicipality),
"Amata Municipality" => Ok(Self::AmataMunicipality),
"Ape Municipality" => Ok(Self::ApeMunicipality),
"Auce Municipality" => Ok(Self::AuceMunicipality),
"Babīte Municipality" => Ok(Self::BabīteMunicipality),
"Baldone Municipality" => Ok(Self::BaldoneMunicipality),
"Baltinava Municipality" => Ok(Self::BaltinavaMunicipality),
"Balvi Municipality" => Ok(Self::BalviMunicipality),
"Bauska Municipality" => Ok(Self::BauskaMunicipality),
"Beverīna Municipality" => Ok(Self::BeverīnaMunicipality),
"Brocēni Municipality" => Ok(Self::BrocēniMunicipality),
"Burtnieki Municipality" => Ok(Self::BurtniekiMunicipality),
"Carnikava Municipality" => Ok(Self::CarnikavaMunicipality),
"Cesvaine Municipality" => Ok(Self::CesvaineMunicipality),
"Cibla Municipality" => Ok(Self::CiblaMunicipality),
"Cēsis Municipality" => Ok(Self::CēsisMunicipality),
"Dagda Municipality" => Ok(Self::DagdaMunicipality),
"Daugavpils" => Ok(Self::Daugavpils),
"Daugavpils Municipality" => Ok(Self::DaugavpilsMunicipality),
"Dobele Municipality" => Ok(Self::DobeleMunicipality),
"Dundaga Municipality" => Ok(Self::DundagaMunicipality),
"Durbe Municipality" => Ok(Self::DurbeMunicipality),
"Engure Municipality" => Ok(Self::EngureMunicipality),
"Garkalne Municipality" => Ok(Self::GarkalneMunicipality),
"Grobiņa Municipality" => Ok(Self::GrobiņaMunicipality),
"Gulbene Municipality" => Ok(Self::GulbeneMunicipality),
"Iecava Municipality" => Ok(Self::IecavaMunicipality),
"Ikšķile Municipality" => Ok(Self::IkšķileMunicipality),
"Ilūkste Municipalityy" => Ok(Self::IlūksteMunicipality),
"Inčukalns Municipality" => Ok(Self::InčukalnsMunicipality),
"Jaunjelgava Municipality" => Ok(Self::JaunjelgavaMunicipality),
"Jaunpiebalga Municipality" => Ok(Self::JaunpiebalgaMunicipality),
"Jaunpils Municipality" => Ok(Self::JaunpilsMunicipality),
"Jelgava" => Ok(Self::Jelgava),
"Jelgava Municipality" => Ok(Self::JelgavaMunicipality),
"Jēkabpils" => Ok(Self::Jēkabpils),
"Jēkabpils Municipality" => Ok(Self::JēkabpilsMunicipality),
"Jūrmala" => Ok(Self::Jūrmala),
"Kandava Municipality" => Ok(Self::KandavaMunicipality),
"Kocēni Municipality" => Ok(Self::KocēniMunicipality),
"Koknese Municipality" => Ok(Self::KokneseMunicipality),
"Krimulda Municipality" => Ok(Self::KrimuldaMunicipality),
"Krustpils Municipality" => Ok(Self::KrustpilsMunicipality),
"Krāslava Municipality" => Ok(Self::KrāslavaMunicipality),
"Kuldīga Municipality" => Ok(Self::KuldīgaMunicipality),
"Kārsava Municipality" => Ok(Self::KārsavaMunicipality),
"Lielvārde Municipality" => Ok(Self::LielvārdeMunicipality),
"Liepāja" => Ok(Self::Liepāja),
"Limbaži Municipality" => Ok(Self::LimbažiMunicipality),
"Lubāna Municipality" => Ok(Self::LubānaMunicipality),
"Ludza Municipality" => Ok(Self::LudzaMunicipality),
"Līgatne Municipality" => Ok(Self::LīgatneMunicipality),
"Līvāni Municipality" => Ok(Self::LīvāniMunicipality),
"Madona Municipality" => Ok(Self::MadonaMunicipality),
"Mazsalaca Municipality" => Ok(Self::MazsalacaMunicipality),
"Mālpils Municipality" => Ok(Self::MālpilsMunicipality),
"Mārupe Municipality" => Ok(Self::MārupeMunicipality),
"Mērsrags Municipality" => Ok(Self::MērsragsMunicipality),
"Naukšēni Municipality" => Ok(Self::NaukšēniMunicipality),
"Nereta Municipality" => Ok(Self::NeretaMunicipality),
"Nīca Municipality" => Ok(Self::NīcaMunicipality),
"Ogre Municipality" => Ok(Self::OgreMunicipality),
"Olaine Municipality" => Ok(Self::OlaineMunicipality),
"Ozolnieki Municipality" => Ok(Self::OzolniekiMunicipality),
"Preiļi Municipality" => Ok(Self::PreiļiMunicipality),
"Priekule Municipality" => Ok(Self::PriekuleMunicipality),
"Priekuļi Municipality" => Ok(Self::PriekuļiMunicipality),
"Pārgauja Municipality" => Ok(Self::PārgaujaMunicipality),
"Pāvilosta Municipality" => Ok(Self::PāvilostaMunicipality),
"Pļaviņas Municipality" => Ok(Self::PļaviņasMunicipality),
"Rauna Municipality" => Ok(Self::RaunaMunicipality),
"Riebiņi Municipality" => Ok(Self::RiebiņiMunicipality),
"Riga" => Ok(Self::Riga),
"Roja Municipality" => Ok(Self::RojaMunicipality),
"Ropaži Municipality" => Ok(Self::RopažiMunicipality),
"Rucava Municipality" => Ok(Self::RucavaMunicipality),
"Rugāji Municipality" => Ok(Self::RugājiMunicipality),
"Rundāle Municipality" => Ok(Self::RundāleMunicipality),
"Rēzekne" => Ok(Self::Rēzekne),
"Rēzekne Municipality" => Ok(Self::RēzekneMunicipality),
"Rūjiena Municipality" => Ok(Self::RūjienaMunicipality),
"Sala Municipality" => Ok(Self::SalaMunicipality),
"Salacgrīva Municipality" => Ok(Self::SalacgrīvaMunicipality),
"Salaspils Municipality" => Ok(Self::SalaspilsMunicipality),
"Saldus Municipality" => Ok(Self::SaldusMunicipality),
"Saulkrasti Municipality" => Ok(Self::SaulkrastiMunicipality),
"Sigulda Municipality" => Ok(Self::SiguldaMunicipality),
"Skrunda Municipality" => Ok(Self::SkrundaMunicipality),
"Skrīveri Municipality" => Ok(Self::SkrīveriMunicipality),
"Smiltene Municipality" => Ok(Self::SmilteneMunicipality),
"Stopiņi Municipality" => Ok(Self::StopiņiMunicipality),
"Strenči Municipality" => Ok(Self::StrenčiMunicipality),
"Sēja Municipality" => Ok(Self::SējaMunicipality),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for MaltaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "MaltaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Attard" => Ok(Self::Attard),
"Balzan" => Ok(Self::Balzan),
"Birgu" => Ok(Self::Birgu),
"Birkirkara" => Ok(Self::Birkirkara),
"Birżebbuġa" => Ok(Self::Birżebbuġa),
"Cospicua" => Ok(Self::Cospicua),
"Dingli" => Ok(Self::Dingli),
"Fgura" => Ok(Self::Fgura),
"Floriana" => Ok(Self::Floriana),
"Fontana" => Ok(Self::Fontana),
"Gudja" => Ok(Self::Gudja),
"Gżira" => Ok(Self::Gżira),
"Għajnsielem" => Ok(Self::Għajnsielem),
"Għarb" => Ok(Self::Għarb),
"Għargħur" => Ok(Self::Għargħur),
"Għasri" => Ok(Self::Għasri),
"Għaxaq" => Ok(Self::Għaxaq),
"Ħamrun" => Ok(Self::Ħamrun),
"Iklin" => Ok(Self::Iklin),
"Senglea" => Ok(Self::Senglea),
"Kalkara" => Ok(Self::Kalkara),
"Kerċem" => Ok(Self::Kerċem),
"Kirkop" => Ok(Self::Kirkop),
"Lija" => Ok(Self::Lija),
"Luqa" => Ok(Self::Luqa),
"Marsa" => Ok(Self::Marsa),
"Marsaskala" => Ok(Self::Marsaskala),
"Marsaxlokk" => Ok(Self::Marsaxlokk),
"Mdina" => Ok(Self::Mdina),
"Mellieħa" => Ok(Self::Mellieħa),
"Mosta" => Ok(Self::Mosta),
"Mqabba" => Ok(Self::Mqabba),
"Msida" => Ok(Self::Msida),
"Mtarfa" => Ok(Self::Mtarfa),
"Munxar" => Ok(Self::Munxar),
"Mġarr" => Ok(Self::Mġarr),
"Nadur" => Ok(Self::Nadur),
"Naxxar" => Ok(Self::Naxxar),
"Paola" => Ok(Self::Paola),
"Pembroke" => Ok(Self::Pembroke),
"Pietà" => Ok(Self::Pietà),
"Qala" => Ok(Self::Qala),
"Qormi" => Ok(Self::Qormi),
"Qrendi" => Ok(Self::Qrendi),
"Rabat" => Ok(Self::Rabat),
"Saint Lawrence" => Ok(Self::SaintLawrence),
"San Ġwann" => Ok(Self::SanĠwann),
"Sannat" => Ok(Self::Sannat),
"Santa Luċija" => Ok(Self::SantaLuċija),
"Santa Venera" => Ok(Self::SantaVenera),
"Siġġiewi" => Ok(Self::Siġġiewi),
"Sliema" => Ok(Self::Sliema),
"St. Julian's" => Ok(Self::StJulians),
"St. Paul's Bay" => Ok(Self::StPaulsBay),
"Swieqi" => Ok(Self::Swieqi),
"Ta' Xbiex" => Ok(Self::TaXbiex),
"Tarxien" => Ok(Self::Tarxien),
"Valletta" => Ok(Self::Valletta),
"Victoria" => Ok(Self::Victoria),
"Xagħra" => Ok(Self::Xagħra),
"Xewkija" => Ok(Self::Xewkija),
"Xgħajra" => Ok(Self::Xgħajra),
"Żabbar" => Ok(Self::Żabbar),
"Żebbuġ Gozo" => Ok(Self::ŻebbuġGozo),
"Żebbuġ Malta" => Ok(Self::ŻebbuġMalta),
"Żejtun" => Ok(Self::Żejtun),
"Żurrieq" => Ok(Self::Żurrieq),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for BelarusStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "BelarusStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Brest Region" => Ok(Self::BrestRegion),
"Gomel Region" => Ok(Self::GomelRegion),
"Grodno Region" => Ok(Self::GrodnoRegion),
"Minsk" => Ok(Self::Minsk),
"Minsk Region" => Ok(Self::MinskRegion),
"Mogilev Region" => Ok(Self::MogilevRegion),
"Vitebsk Region" => Ok(Self::VitebskRegion),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for IrelandStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "IrelandStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Connacht" => Ok(Self::Connacht),
"County Carlow" => Ok(Self::CountyCarlow),
"County Cavan" => Ok(Self::CountyCavan),
"County Clare" => Ok(Self::CountyClare),
"County Cork" => Ok(Self::CountyCork),
"County Donegal" => Ok(Self::CountyDonegal),
"County Dublin" => Ok(Self::CountyDublin),
"County Galway" => Ok(Self::CountyGalway),
"County Kerry" => Ok(Self::CountyKerry),
"County Kildare" => Ok(Self::CountyKildare),
"County Kilkenny" => Ok(Self::CountyKilkenny),
"County Laois" => Ok(Self::CountyLaois),
"County Limerick" => Ok(Self::CountyLimerick),
"County Longford" => Ok(Self::CountyLongford),
"County Louth" => Ok(Self::CountyLouth),
"County Mayo" => Ok(Self::CountyMayo),
"County Meath" => Ok(Self::CountyMeath),
"County Monaghan" => Ok(Self::CountyMonaghan),
"County Offaly" => Ok(Self::CountyOffaly),
"County Roscommon" => Ok(Self::CountyRoscommon),
"County Sligo" => Ok(Self::CountySligo),
"County Tipperary" => Ok(Self::CountyTipperary),
"County Waterford" => Ok(Self::CountyWaterford),
"County Westmeath" => Ok(Self::CountyWestmeath),
"County Wexford" => Ok(Self::CountyWexford),
"County Wicklow" => Ok(Self::CountyWicklow),
"Leinster" => Ok(Self::Leinster),
"Munster" => Ok(Self::Munster),
"Ulster" => Ok(Self::Ulster),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for IcelandStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "IcelandStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Capital Region" => Ok(Self::CapitalRegion),
"Eastern Region" => Ok(Self::EasternRegion),
"Northeastern Region" => Ok(Self::NortheasternRegion),
"Northwestern Region" => Ok(Self::NorthwesternRegion),
"Southern Peninsula Region" => Ok(Self::SouthernPeninsulaRegion),
"Southern Region" => Ok(Self::SouthernRegion),
"Western Region" => Ok(Self::WesternRegion),
"Westfjords" => Ok(Self::Westfjords),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for HungaryStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "HungaryStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Baranya County" => Ok(Self::BaranyaCounty),
"Borsod-Abaúj-Zemplén County" => Ok(Self::BorsodAbaujZemplenCounty),
"Budapest" => Ok(Self::Budapest),
"Bács-Kiskun County" => Ok(Self::BacsKiskunCounty),
"Békés County" => Ok(Self::BekesCounty),
"Békéscsaba" => Ok(Self::Bekescsaba),
"Csongrád County" => Ok(Self::CsongradCounty),
"Debrecen" => Ok(Self::Debrecen),
"Dunaújváros" => Ok(Self::Dunaujvaros),
"Eger" => Ok(Self::Eger),
"Fejér County" => Ok(Self::FejerCounty),
"Győr" => Ok(Self::Gyor),
"Győr-Moson-Sopron County" => Ok(Self::GyorMosonSopronCounty),
"Hajdú-Bihar County" => Ok(Self::HajduBiharCounty),
"Heves County" => Ok(Self::HevesCounty),
"Hódmezővásárhely" => Ok(Self::Hodmezovasarhely),
"Jász-Nagykun-Szolnok County" => Ok(Self::JaszNagykunSzolnokCounty),
"Kaposvár" => Ok(Self::Kaposvar),
"Kecskemét" => Ok(Self::Kecskemet),
"Miskolc" => Ok(Self::Miskolc),
"Nagykanizsa" => Ok(Self::Nagykanizsa),
"Nyíregyháza" => Ok(Self::Nyiregyhaza),
"Nógrád County" => Ok(Self::NogradCounty),
"Pest County" => Ok(Self::PestCounty),
"Pécs" => Ok(Self::Pecs),
"Salgótarján" => Ok(Self::Salgotarjan),
"Somogy County" => Ok(Self::SomogyCounty),
"Sopron" => Ok(Self::Sopron),
"Szabolcs-Szatmár-Bereg County" => Ok(Self::SzabolcsSzatmarBeregCounty),
"Szeged" => Ok(Self::Szeged),
"Szekszárd" => Ok(Self::Szekszard),
"Szolnok" => Ok(Self::Szolnok),
"Szombathely" => Ok(Self::Szombathely),
"Székesfehérvár" => Ok(Self::Szekesfehervar),
"Tatabánya" => Ok(Self::Tatabanya),
"Tolna County" => Ok(Self::TolnaCounty),
"Vas County" => Ok(Self::VasCounty),
"Veszprém" => Ok(Self::Veszprem),
"Veszprém County" => Ok(Self::VeszpremCounty),
"Zala County" => Ok(Self::ZalaCounty),
"Zalaegerszeg" => Ok(Self::Zalaegerszeg),
"Érd" => Ok(Self::Erd),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for GreeceStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "GreeceStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Achaea Regional Unit" => Ok(Self::AchaeaRegionalUnit),
"Aetolia-Acarnania Regional Unit" => Ok(Self::AetoliaAcarnaniaRegionalUnit),
"Arcadia Prefecture" => Ok(Self::ArcadiaPrefecture),
"Argolis Regional Unit" => Ok(Self::ArgolisRegionalUnit),
"Attica Region" => Ok(Self::AtticaRegion),
"Boeotia Regional Unit" => Ok(Self::BoeotiaRegionalUnit),
"Central Greece Region" => Ok(Self::CentralGreeceRegion),
"Central Macedonia" => Ok(Self::CentralMacedonia),
"Chania Regional Unit" => Ok(Self::ChaniaRegionalUnit),
"Corfu Prefecture" => Ok(Self::CorfuPrefecture),
"Corinthia Regional Unit" => Ok(Self::CorinthiaRegionalUnit),
"Crete Region" => Ok(Self::CreteRegion),
"Drama Regional Unit" => Ok(Self::DramaRegionalUnit),
"East Attica Regional Unit" => Ok(Self::EastAtticaRegionalUnit),
"East Macedonia and Thrace" => Ok(Self::EastMacedoniaAndThrace),
"Epirus Region" => Ok(Self::EpirusRegion),
"Euboea" => Ok(Self::Euboea),
"Grevena Prefecture" => Ok(Self::GrevenaPrefecture),
"Imathia Regional Unit" => Ok(Self::ImathiaRegionalUnit),
"Ioannina Regional Unit" => Ok(Self::IoanninaRegionalUnit),
"Ionian Islands Region" => Ok(Self::IonianIslandsRegion),
"Karditsa Regional Unit" => Ok(Self::KarditsaRegionalUnit),
"Kastoria Regional Unit" => Ok(Self::KastoriaRegionalUnit),
"Kefalonia Prefecture" => Ok(Self::KefaloniaPrefecture),
"Kilkis Regional Unit" => Ok(Self::KilkisRegionalUnit),
"Kozani Prefecture" => Ok(Self::KozaniPrefecture),
"Laconia" => Ok(Self::Laconia),
"Larissa Prefecture" => Ok(Self::LarissaPrefecture),
"Lefkada Regional Unit" => Ok(Self::LefkadaRegionalUnit),
"Pella Regional Unit" => Ok(Self::PellaRegionalUnit),
"Peloponnese Region" => Ok(Self::PeloponneseRegion),
"Phthiotis Prefecture" => Ok(Self::PhthiotisPrefecture),
"Preveza Prefecture" => Ok(Self::PrevezaPrefecture),
"Serres Prefecture" => Ok(Self::SerresPrefecture),
"South Aegean" => Ok(Self::SouthAegean),
"Thessaloniki Regional Unit" => Ok(Self::ThessalonikiRegionalUnit),
"West Greece Region" => Ok(Self::WestGreeceRegion),
"West Macedonia Region" => Ok(Self::WestMacedoniaRegion),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for FinlandStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "FinlandStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Central Finland" => Ok(Self::CentralFinland),
"Central Ostrobothnia" => Ok(Self::CentralOstrobothnia),
"Eastern Finland Province" => Ok(Self::EasternFinlandProvince),
"Finland Proper" => Ok(Self::FinlandProper),
"Kainuu" => Ok(Self::Kainuu),
"Kymenlaakso" => Ok(Self::Kymenlaakso),
"Lapland" => Ok(Self::Lapland),
"North Karelia" => Ok(Self::NorthKarelia),
"Northern Ostrobothnia" => Ok(Self::NorthernOstrobothnia),
"Northern Savonia" => Ok(Self::NorthernSavonia),
"Ostrobothnia" => Ok(Self::Ostrobothnia),
"Oulu Province" => Ok(Self::OuluProvince),
"Pirkanmaa" => Ok(Self::Pirkanmaa),
"Päijänne Tavastia" => Ok(Self::PaijanneTavastia),
"Satakunta" => Ok(Self::Satakunta),
"South Karelia" => Ok(Self::SouthKarelia),
"Southern Ostrobothnia" => Ok(Self::SouthernOstrobothnia),
"Southern Savonia" => Ok(Self::SouthernSavonia),
"Tavastia Proper" => Ok(Self::TavastiaProper),
"Uusimaa" => Ok(Self::Uusimaa),
"Åland Islands" => Ok(Self::AlandIslands),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for DenmarkStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "DenmarkStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Capital Region of Denmark" => Ok(Self::CapitalRegionOfDenmark),
"Central Denmark Region" => Ok(Self::CentralDenmarkRegion),
"North Denmark Region" => Ok(Self::NorthDenmarkRegion),
"Region Zealand" => Ok(Self::RegionZealand),
"Region of Southern Denmark" => Ok(Self::RegionOfSouthernDenmark),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for CzechRepublicStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "CzechRepublicStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Benešov District" => Ok(Self::BenesovDistrict),
"Beroun District" => Ok(Self::BerounDistrict),
"Blansko District" => Ok(Self::BlanskoDistrict),
"Brno-City District" => Ok(Self::BrnoCityDistrict),
"Brno-Country District" => Ok(Self::BrnoCountryDistrict),
"Bruntál District" => Ok(Self::BruntalDistrict),
"Břeclav District" => Ok(Self::BreclavDistrict),
"Central Bohemian Region" => Ok(Self::CentralBohemianRegion),
"Cheb District" => Ok(Self::ChebDistrict),
"Chomutov District" => Ok(Self::ChomutovDistrict),
"Chrudim District" => Ok(Self::ChrudimDistrict),
"Domažlice Distric" => Ok(Self::DomazliceDistrict),
"Děčín District" => Ok(Self::DecinDistrict),
"Frýdek-Místek District" => Ok(Self::FrydekMistekDistrict),
"Havlíčkův Brod District" => Ok(Self::HavlickuvBrodDistrict),
"Hodonín District" => Ok(Self::HodoninDistrict),
"Horní Počernice" => Ok(Self::HorniPocernice),
"Hradec Králové District" => Ok(Self::HradecKraloveDistrict),
"Hradec Králové Region" => Ok(Self::HradecKraloveRegion),
"Jablonec nad Nisou District" => Ok(Self::JablonecNadNisouDistrict),
"Jeseník District" => Ok(Self::JesenikDistrict),
"Jihlava District" => Ok(Self::JihlavaDistrict),
"Jindřichův Hradec District" => Ok(Self::JindrichuvHradecDistrict),
"Jičín District" => Ok(Self::JicinDistrict),
"Karlovy Vary District" => Ok(Self::KarlovyVaryDistrict),
"Karlovy Vary Region" => Ok(Self::KarlovyVaryRegion),
"Karviná District" => Ok(Self::KarvinaDistrict),
"Kladno District" => Ok(Self::KladnoDistrict),
"Klatovy District" => Ok(Self::KlatovyDistrict),
"Kolín District" => Ok(Self::KolinDistrict),
"Kroměříž District" => Ok(Self::KromerizDistrict),
"Liberec District" => Ok(Self::LiberecDistrict),
"Liberec Region" => Ok(Self::LiberecRegion),
"Litoměřice District" => Ok(Self::LitomericeDistrict),
"Louny District" => Ok(Self::LounyDistrict),
"Mladá Boleslav District" => Ok(Self::MladaBoleslavDistrict),
"Moravian-Silesian Region" => Ok(Self::MoravianSilesianRegion),
"Most District" => Ok(Self::MostDistrict),
"Mělník District" => Ok(Self::MelnikDistrict),
"Nový Jičín District" => Ok(Self::NovyJicinDistrict),
"Nymburk District" => Ok(Self::NymburkDistrict),
"Náchod District" => Ok(Self::NachodDistrict),
"Olomouc District" => Ok(Self::OlomoucDistrict),
"Olomouc Region" => Ok(Self::OlomoucRegion),
"Opava District" => Ok(Self::OpavaDistrict),
"Ostrava-City District" => Ok(Self::OstravaCityDistrict),
"Pardubice District" => Ok(Self::PardubiceDistrict),
"Pardubice Region" => Ok(Self::PardubiceRegion),
"Pelhřimov District" => Ok(Self::PelhrimovDistrict),
"Plzeň Region" => Ok(Self::PlzenRegion),
"Plzeň-City District" => Ok(Self::PlzenCityDistrict),
"Plzeň-North District" => Ok(Self::PlzenNorthDistrict),
"Plzeň-South District" => Ok(Self::PlzenSouthDistrict),
"Prachatice District" => Ok(Self::PrachaticeDistrict),
"Prague" => Ok(Self::Prague),
"Prague 1" => Ok(Self::Prague1),
"Prague 10" => Ok(Self::Prague10),
"Prague 11" => Ok(Self::Prague11),
"Prague 12" => Ok(Self::Prague12),
"Prague 13" => Ok(Self::Prague13),
"Prague 14" => Ok(Self::Prague14),
"Prague 15" => Ok(Self::Prague15),
"Prague 16" => Ok(Self::Prague16),
"Prague 2" => Ok(Self::Prague2),
"Prague 21" => Ok(Self::Prague21),
"Prague 3" => Ok(Self::Prague3),
"Prague 4" => Ok(Self::Prague4),
"Prague 5" => Ok(Self::Prague5),
"Prague 6" => Ok(Self::Prague6),
"Prague 7" => Ok(Self::Prague7),
"Prague 8" => Ok(Self::Prague8),
"Prague 9" => Ok(Self::Prague9),
"Prague-East District" => Ok(Self::PragueEastDistrict),
"Prague-West District" => Ok(Self::PragueWestDistrict),
"Prostějov District" => Ok(Self::ProstejovDistrict),
"Písek District" => Ok(Self::PisekDistrict),
"Přerov District" => Ok(Self::PrerovDistrict),
"Příbram District" => Ok(Self::PribramDistrict),
"Rakovník District" => Ok(Self::RakovnikDistrict),
"Rokycany District" => Ok(Self::RokycanyDistrict),
"Rychnov nad Kněžnou District" => Ok(Self::RychnovNadKneznouDistrict),
"Semily District" => Ok(Self::SemilyDistrict),
"Sokolov District" => Ok(Self::SokolovDistrict),
"South Bohemian Region" => Ok(Self::SouthBohemianRegion),
"South Moravian Region" => Ok(Self::SouthMoravianRegion),
"Strakonice District" => Ok(Self::StrakoniceDistrict),
"Svitavy District" => Ok(Self::SvitavyDistrict),
"Tachov District" => Ok(Self::TachovDistrict),
"Teplice District" => Ok(Self::TepliceDistrict),
"Trutnov District" => Ok(Self::TrutnovDistrict),
"Tábor District" => Ok(Self::TaborDistrict),
"Třebíč District" => Ok(Self::TrebicDistrict),
"Uherské Hradiště District" => Ok(Self::UherskeHradisteDistrict),
"Vsetín District" => Ok(Self::VsetinDistrict),
"Vysočina Region" => Ok(Self::VysocinaRegion),
"Vyškov District" => Ok(Self::VyskovDistrict),
"Zlín District" => Ok(Self::ZlinDistrict),
"Zlín Region" => Ok(Self::ZlinRegion),
"Znojmo District" => Ok(Self::ZnojmoDistrict),
"Ústí nad Labem District" => Ok(Self::UstiNadLabemDistrict),
"Ústí nad Labem Region" => Ok(Self::UstiNadLabemRegion),
"Ústí nad Orlicí District" => Ok(Self::UstiNadOrliciDistrict),
"Česká Lípa District" => Ok(Self::CeskaLipaDistrict),
"České Budějovice District" => Ok(Self::CeskeBudejoviceDistrict),
"Český Krumlov District" => Ok(Self::CeskyKrumlovDistrict),
"Šumperk District" => Ok(Self::SumperkDistrict),
"Žďár nad Sázavou District" => Ok(Self::ZdarNadSazavouDistrict),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for CroatiaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "CroatiaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Bjelovar-Bilogora County" => Ok(Self::BjelovarBilogoraCounty),
"Brod-Posavina County" => Ok(Self::BrodPosavinaCounty),
"Dubrovnik-Neretva County" => Ok(Self::DubrovnikNeretvaCounty),
"Istria County" => Ok(Self::IstriaCounty),
"Koprivnica-Križevci County" => Ok(Self::KoprivnicaKrizevciCounty),
"Krapina-Zagorje County" => Ok(Self::KrapinaZagorjeCounty),
"Lika-Senj County" => Ok(Self::LikaSenjCounty),
"Međimurje County" => Ok(Self::MedimurjeCounty),
"Osijek-Baranja County" => Ok(Self::OsijekBaranjaCounty),
"Požega-Slavonia County" => Ok(Self::PozegaSlavoniaCounty),
"Primorje-Gorski Kotar County" => Ok(Self::PrimorjeGorskiKotarCounty),
"Sisak-Moslavina County" => Ok(Self::SisakMoslavinaCounty),
"Split-Dalmatia County" => Ok(Self::SplitDalmatiaCounty),
"Varaždin County" => Ok(Self::VarazdinCounty),
"Virovitica-Podravina County" => Ok(Self::ViroviticaPodravinaCounty),
"Vukovar-Syrmia County" => Ok(Self::VukovarSyrmiaCounty),
"Zadar County" => Ok(Self::ZadarCounty),
"Zagreb" => Ok(Self::Zagreb),
"Zagreb County" => Ok(Self::ZagrebCounty),
"Šibenik-Knin County" => Ok(Self::SibenikKninCounty),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for BulgariaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "BulgariaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Blagoevgrad Province" => Ok(Self::BlagoevgradProvince),
"Burgas Province" => Ok(Self::BurgasProvince),
"Dobrich Province" => Ok(Self::DobrichProvince),
"Gabrovo Province" => Ok(Self::GabrovoProvince),
"Haskovo Province" => Ok(Self::HaskovoProvince),
"Kardzhali Province" => Ok(Self::KardzhaliProvince),
"Kyustendil Province" => Ok(Self::KyustendilProvince),
"Lovech Province" => Ok(Self::LovechProvince),
"Montana Province" => Ok(Self::MontanaProvince),
"Pazardzhik Province" => Ok(Self::PazardzhikProvince),
"Pernik Province" => Ok(Self::PernikProvince),
"Pleven Province" => Ok(Self::PlevenProvince),
"Plovdiv Province" => Ok(Self::PlovdivProvince),
"Razgrad Province" => Ok(Self::RazgradProvince),
"Ruse Province" => Ok(Self::RuseProvince),
"Shumen" => Ok(Self::Shumen),
"Silistra Province" => Ok(Self::SilistraProvince),
"Sliven Province" => Ok(Self::SlivenProvince),
"Smolyan Province" => Ok(Self::SmolyanProvince),
"Sofia City Province" => Ok(Self::SofiaCityProvince),
"Sofia Province" => Ok(Self::SofiaProvince),
"Stara Zagora Province" => Ok(Self::StaraZagoraProvince),
"Targovishte Provinc" => Ok(Self::TargovishteProvince),
"Varna Province" => Ok(Self::VarnaProvince),
"Veliko Tarnovo Province" => Ok(Self::VelikoTarnovoProvince),
"Vidin Province" => Ok(Self::VidinProvince),
"Vratsa Province" => Ok(Self::VratsaProvince),
"Yambol Province" => Ok(Self::YambolProvince),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for BosniaAndHerzegovinaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "BosniaAndHerzegovinaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Bosnian Podrinje Canton" => Ok(Self::BosnianPodrinjeCanton),
"Brčko District" => Ok(Self::BrckoDistrict),
"Canton 10" => Ok(Self::Canton10),
"Central Bosnia Canton" => Ok(Self::CentralBosniaCanton),
"Federation of Bosnia and Herzegovina" => {
Ok(Self::FederationOfBosniaAndHerzegovina)
}
"Herzegovina-Neretva Canton" => Ok(Self::HerzegovinaNeretvaCanton),
"Posavina Canton" => Ok(Self::PosavinaCanton),
"Republika Srpska" => Ok(Self::RepublikaSrpska),
"Sarajevo Canton" => Ok(Self::SarajevoCanton),
"Tuzla Canton" => Ok(Self::TuzlaCanton),
"Una-Sana Canton" => Ok(Self::UnaSanaCanton),
"West Herzegovina Canton" => Ok(Self::WestHerzegovinaCanton),
"Zenica-Doboj Canton" => Ok(Self::ZenicaDobojCanton),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for UnitedKingdomStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "UnitedKingdomStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Aberdeen" => Ok(Self::Aberdeen),
"Aberdeenshire" => Ok(Self::Aberdeenshire),
"Angus" => Ok(Self::Angus),
"Antrim" => Ok(Self::Antrim),
"Antrim and Newtownabbey" => Ok(Self::AntrimAndNewtownabbey),
"Ards" => Ok(Self::Ards),
"Ards and North Down" => Ok(Self::ArdsAndNorthDown),
"Argyll and Bute" => Ok(Self::ArgyllAndBute),
"Armagh City and District Council" => Ok(Self::ArmaghCityAndDistrictCouncil),
"Armagh, Banbridge and Craigavon" => Ok(Self::ArmaghBanbridgeAndCraigavon),
"Ascension Island" => Ok(Self::AscensionIsland),
"Ballymena Borough" => Ok(Self::BallymenaBorough),
"Ballymoney" => Ok(Self::Ballymoney),
"Banbridge" => Ok(Self::Banbridge),
"Barnsley" => Ok(Self::Barnsley),
"Bath and North East Somerset" => Ok(Self::BathAndNorthEastSomerset),
"Bedford" => Ok(Self::Bedford),
"Belfast district" => Ok(Self::BelfastDistrict),
"Birmingham" => Ok(Self::Birmingham),
"Blackburn with Darwen" => Ok(Self::BlackburnWithDarwen),
"Blackpool" => Ok(Self::Blackpool),
"Blaenau Gwent County Borough" => Ok(Self::BlaenauGwentCountyBorough),
"Bolton" => Ok(Self::Bolton),
"Bournemouth" => Ok(Self::Bournemouth),
"Bracknell Forest" => Ok(Self::BracknellForest),
"Bradford" => Ok(Self::Bradford),
"Bridgend County Borough" => Ok(Self::BridgendCountyBorough),
"Brighton and Hove" => Ok(Self::BrightonAndHove),
"Buckinghamshire" => Ok(Self::Buckinghamshire),
"Bury" => Ok(Self::Bury),
"Caerphilly County Borough" => Ok(Self::CaerphillyCountyBorough),
"Calderdale" => Ok(Self::Calderdale),
"Cambridgeshire" => Ok(Self::Cambridgeshire),
"Carmarthenshire" => Ok(Self::Carmarthenshire),
"Carrickfergus Borough Council" => Ok(Self::CarrickfergusBoroughCouncil),
"Castlereagh" => Ok(Self::Castlereagh),
"Causeway Coast and Glens" => Ok(Self::CausewayCoastAndGlens),
"Central Bedfordshire" => Ok(Self::CentralBedfordshire),
"Ceredigion" => Ok(Self::Ceredigion),
"Cheshire East" => Ok(Self::CheshireEast),
"Cheshire West and Chester" => Ok(Self::CheshireWestAndChester),
"City and County of Cardiff" => Ok(Self::CityAndCountyOfCardiff),
"City and County of Swansea" => Ok(Self::CityAndCountyOfSwansea),
"City of Bristol" => Ok(Self::CityOfBristol),
"City of Derby" => Ok(Self::CityOfDerby),
"City of Kingston upon Hull" => Ok(Self::CityOfKingstonUponHull),
"City of Leicester" => Ok(Self::CityOfLeicester),
"City of London" => Ok(Self::CityOfLondon),
"City of Nottingham" => Ok(Self::CityOfNottingham),
"City of Peterborough" => Ok(Self::CityOfPeterborough),
"City of Plymouth" => Ok(Self::CityOfPlymouth),
"City of Portsmouth" => Ok(Self::CityOfPortsmouth),
"City of Southampton" => Ok(Self::CityOfSouthampton),
"City of Stoke-on-Trent" => Ok(Self::CityOfStokeOnTrent),
"City of Sunderland" => Ok(Self::CityOfSunderland),
"City of Westminster" => Ok(Self::CityOfWestminster),
"City of Wolverhampton" => Ok(Self::CityOfWolverhampton),
"City of York" => Ok(Self::CityOfYork),
"Clackmannanshire" => Ok(Self::Clackmannanshire),
"Coleraine Borough Council" => Ok(Self::ColeraineBoroughCouncil),
"Conwy County Borough" => Ok(Self::ConwyCountyBorough),
"Cookstown District Council" => Ok(Self::CookstownDistrictCouncil),
"Cornwall" => Ok(Self::Cornwall),
"County Durham" => Ok(Self::CountyDurham),
"Coventry" => Ok(Self::Coventry),
"Craigavon Borough Council" => Ok(Self::CraigavonBoroughCouncil),
"Cumbria" => Ok(Self::Cumbria),
"Darlington" => Ok(Self::Darlington),
"Denbighshire" => Ok(Self::Denbighshire),
"Derbyshire" => Ok(Self::Derbyshire),
"Derry City and Strabane" => Ok(Self::DerryCityAndStrabane),
"Derry City Council" => Ok(Self::DerryCityCouncil),
"Devon" => Ok(Self::Devon),
"Doncaster" => Ok(Self::Doncaster),
"Dorset" => Ok(Self::Dorset),
"Down District Council" => Ok(Self::DownDistrictCouncil),
"Dudley" => Ok(Self::Dudley),
"Dumfries and Galloway" => Ok(Self::DumfriesAndGalloway),
"Dundee" => Ok(Self::Dundee),
"Dungannon and South Tyrone Borough Council" => {
Ok(Self::DungannonAndSouthTyroneBoroughCouncil)
}
"East Ayrshire" => Ok(Self::EastAyrshire),
"East Dunbartonshire" => Ok(Self::EastDunbartonshire),
"East Lothian" => Ok(Self::EastLothian),
"East Renfrewshire" => Ok(Self::EastRenfrewshire),
"East Riding of Yorkshire" => Ok(Self::EastRidingOfYorkshire),
"East Sussex" => Ok(Self::EastSussex),
"Edinburgh" => Ok(Self::Edinburgh),
"England" => Ok(Self::England),
"Essex" => Ok(Self::Essex),
"Falkirk" => Ok(Self::Falkirk),
"Fermanagh and Omagh" => Ok(Self::FermanaghAndOmagh),
"Fermanagh District Council" => Ok(Self::FermanaghDistrictCouncil),
"Fife" => Ok(Self::Fife),
"Flintshire" => Ok(Self::Flintshire),
"Gateshead" => Ok(Self::Gateshead),
"Glasgow" => Ok(Self::Glasgow),
"Gloucestershire" => Ok(Self::Gloucestershire),
"Gwynedd" => Ok(Self::Gwynedd),
"Halton" => Ok(Self::Halton),
"Hampshire" => Ok(Self::Hampshire),
"Hartlepool" => Ok(Self::Hartlepool),
"Herefordshire" => Ok(Self::Herefordshire),
"Hertfordshire" => Ok(Self::Hertfordshire),
"Highland" => Ok(Self::Highland),
"Inverclyde" => Ok(Self::Inverclyde),
"Isle of Wight" => Ok(Self::IsleOfWight),
"Isles of Scilly" => Ok(Self::IslesOfScilly),
"Kent" => Ok(Self::Kent),
"Kirklees" => Ok(Self::Kirklees),
"Knowsley" => Ok(Self::Knowsley),
"Lancashire" => Ok(Self::Lancashire),
"Larne Borough Council" => Ok(Self::LarneBoroughCouncil),
"Leeds" => Ok(Self::Leeds),
"Leicestershire" => Ok(Self::Leicestershire),
"Limavady Borough Council" => Ok(Self::LimavadyBoroughCouncil),
"Lincolnshire" => Ok(Self::Lincolnshire),
"Lisburn and Castlereagh" => Ok(Self::LisburnAndCastlereagh),
"Lisburn City Council" => Ok(Self::LisburnCityCouncil),
"Liverpool" => Ok(Self::Liverpool),
"London Borough of Barking and Dagenham" => {
Ok(Self::LondonBoroughOfBarkingAndDagenham)
}
"London Borough of Barnet" => Ok(Self::LondonBoroughOfBarnet),
"London Borough of Bexley" => Ok(Self::LondonBoroughOfBexley),
"London Borough of Brent" => Ok(Self::LondonBoroughOfBrent),
"London Borough of Bromley" => Ok(Self::LondonBoroughOfBromley),
"London Borough of Camden" => Ok(Self::LondonBoroughOfCamden),
"London Borough of Croydon" => Ok(Self::LondonBoroughOfCroydon),
"London Borough of Ealing" => Ok(Self::LondonBoroughOfEaling),
"London Borough of Enfield" => Ok(Self::LondonBoroughOfEnfield),
"London Borough of Hackney" => Ok(Self::LondonBoroughOfHackney),
"London Borough of Hammersmith and Fulham" => {
Ok(Self::LondonBoroughOfHammersmithAndFulham)
}
"London Borough of Haringey" => Ok(Self::LondonBoroughOfHaringey),
"London Borough of Harrow" => Ok(Self::LondonBoroughOfHarrow),
"London Borough of Havering" => Ok(Self::LondonBoroughOfHavering),
"London Borough of Hillingdon" => Ok(Self::LondonBoroughOfHillingdon),
"London Borough of Hounslow" => Ok(Self::LondonBoroughOfHounslow),
"London Borough of Islington" => Ok(Self::LondonBoroughOfIslington),
"London Borough of Lambeth" => Ok(Self::LondonBoroughOfLambeth),
"London Borough of Lewisham" => Ok(Self::LondonBoroughOfLewisham),
"London Borough of Merton" => Ok(Self::LondonBoroughOfMerton),
"London Borough of Newham" => Ok(Self::LondonBoroughOfNewham),
"London Borough of Redbridge" => Ok(Self::LondonBoroughOfRedbridge),
"London Borough of Richmond upon Thames" => {
Ok(Self::LondonBoroughOfRichmondUponThames)
}
"London Borough of Southwark" => Ok(Self::LondonBoroughOfSouthwark),
"London Borough of Sutton" => Ok(Self::LondonBoroughOfSutton),
"London Borough of Tower Hamlets" => Ok(Self::LondonBoroughOfTowerHamlets),
"London Borough of Waltham Forest" => Ok(Self::LondonBoroughOfWalthamForest),
"London Borough of Wandsworth" => Ok(Self::LondonBoroughOfWandsworth),
"Magherafelt District Council" => Ok(Self::MagherafeltDistrictCouncil),
"Manchester" => Ok(Self::Manchester),
"Medway" => Ok(Self::Medway),
"Merthyr Tydfil County Borough" => Ok(Self::MerthyrTydfilCountyBorough),
"Metropolitan Borough of Wigan" => Ok(Self::MetropolitanBoroughOfWigan),
"Mid and East Antrim" => Ok(Self::MidAndEastAntrim),
"Mid Ulster" => Ok(Self::MidUlster),
"Middlesbrough" => Ok(Self::Middlesbrough),
"Midlothian" => Ok(Self::Midlothian),
"Milton Keynes" => Ok(Self::MiltonKeynes),
"Monmouthshire" => Ok(Self::Monmouthshire),
"Moray" => Ok(Self::Moray),
"Moyle District Council" => Ok(Self::MoyleDistrictCouncil),
"Neath Port Talbot County Borough" => Ok(Self::NeathPortTalbotCountyBorough),
"Newcastle upon Tyne" => Ok(Self::NewcastleUponTyne),
"Newport" => Ok(Self::Newport),
"Newry and Mourne District Council" => Ok(Self::NewryAndMourneDistrictCouncil),
"Newry, Mourne and Down" => Ok(Self::NewryMourneAndDown),
"Newtownabbey Borough Council" => Ok(Self::NewtownabbeyBoroughCouncil),
"Norfolk" => Ok(Self::Norfolk),
"North Ayrshire" => Ok(Self::NorthAyrshire),
"North Down Borough Council" => Ok(Self::NorthDownBoroughCouncil),
"North East Lincolnshire" => Ok(Self::NorthEastLincolnshire),
"North Lanarkshire" => Ok(Self::NorthLanarkshire),
"North Lincolnshire" => Ok(Self::NorthLincolnshire),
"North Somerset" => Ok(Self::NorthSomerset),
"North Tyneside" => Ok(Self::NorthTyneside),
"North Yorkshire" => Ok(Self::NorthYorkshire),
"Northamptonshire" => Ok(Self::Northamptonshire),
"Northern Ireland" => Ok(Self::NorthernIreland),
"Northumberland" => Ok(Self::Northumberland),
"Nottinghamshire" => Ok(Self::Nottinghamshire),
"Oldham" => Ok(Self::Oldham),
"Omagh District Council" => Ok(Self::OmaghDistrictCouncil),
"Orkney Islands" => Ok(Self::OrkneyIslands),
"Outer Hebrides" => Ok(Self::OuterHebrides),
"Oxfordshire" => Ok(Self::Oxfordshire),
"Pembrokeshire" => Ok(Self::Pembrokeshire),
"Perth and Kinross" => Ok(Self::PerthAndKinross),
"Poole" => Ok(Self::Poole),
"Powys" => Ok(Self::Powys),
"Reading" => Ok(Self::Reading),
"Redcar and Cleveland" => Ok(Self::RedcarAndCleveland),
"Renfrewshire" => Ok(Self::Renfrewshire),
"Rhondda Cynon Taf" => Ok(Self::RhonddaCynonTaf),
"Rochdale" => Ok(Self::Rochdale),
"Rotherham" => Ok(Self::Rotherham),
"Royal Borough of Greenwich" => Ok(Self::RoyalBoroughOfGreenwich),
"Royal Borough of Kensington and Chelsea" => {
Ok(Self::RoyalBoroughOfKensingtonAndChelsea)
}
"Royal Borough of Kingston upon Thames" => {
Ok(Self::RoyalBoroughOfKingstonUponThames)
}
"Rutland" => Ok(Self::Rutland),
"Saint Helena" => Ok(Self::SaintHelena),
"Salford" => Ok(Self::Salford),
"Sandwell" => Ok(Self::Sandwell),
"Scotland" => Ok(Self::Scotland),
"Scottish Borders" => Ok(Self::ScottishBorders),
"Sefton" => Ok(Self::Sefton),
"Sheffield" => Ok(Self::Sheffield),
"Shetland Islands" => Ok(Self::ShetlandIslands),
"Shropshire" => Ok(Self::Shropshire),
"Slough" => Ok(Self::Slough),
"Solihull" => Ok(Self::Solihull),
"Somerset" => Ok(Self::Somerset),
"South Ayrshire" => Ok(Self::SouthAyrshire),
"South Gloucestershire" => Ok(Self::SouthGloucestershire),
"South Lanarkshire" => Ok(Self::SouthLanarkshire),
"South Tyneside" => Ok(Self::SouthTyneside),
"Southend-on-Sea" => Ok(Self::SouthendOnSea),
"St Helens" => Ok(Self::StHelens),
"Staffordshire" => Ok(Self::Staffordshire),
"Stirling" => Ok(Self::Stirling),
"Stockport" => Ok(Self::Stockport),
"Stockton-on-Tees" => Ok(Self::StocktonOnTees),
"Strabane District Council" => Ok(Self::StrabaneDistrictCouncil),
"Suffolk" => Ok(Self::Suffolk),
"Surrey" => Ok(Self::Surrey),
"Swindon" => Ok(Self::Swindon),
"Tameside" => Ok(Self::Tameside),
"Telford and Wrekin" => Ok(Self::TelfordAndWrekin),
"Thurrock" => Ok(Self::Thurrock),
"Torbay" => Ok(Self::Torbay),
"Torfaen" => Ok(Self::Torfaen),
"Trafford" => Ok(Self::Trafford),
"United Kingdom" => Ok(Self::UnitedKingdom),
"Vale of Glamorgan" => Ok(Self::ValeOfGlamorgan),
"Wakefield" => Ok(Self::Wakefield),
"Wales" => Ok(Self::Wales),
"Walsall" => Ok(Self::Walsall),
"Warrington" => Ok(Self::Warrington),
"Warwickshire" => Ok(Self::Warwickshire),
"West Berkshire" => Ok(Self::WestBerkshire),
"West Dunbartonshire" => Ok(Self::WestDunbartonshire),
"West Lothian" => Ok(Self::WestLothian),
"West Sussex" => Ok(Self::WestSussex),
"Wiltshire" => Ok(Self::Wiltshire),
"Windsor and Maidenhead" => Ok(Self::WindsorAndMaidenhead),
"Wirral" => Ok(Self::Wirral),
"Wokingham" => Ok(Self::Wokingham),
"Worcestershire" => Ok(Self::Worcestershire),
"Wrexham County Borough" => Ok(Self::WrexhamCountyBorough),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for BelgiumStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "BelgiumStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Antwerp" => Ok(Self::Antwerp),
"Brussels-Capital Region" => Ok(Self::BrusselsCapitalRegion),
"East Flanders" => Ok(Self::EastFlanders),
"Flanders" => Ok(Self::Flanders),
"Flemish Brabant" => Ok(Self::FlemishBrabant),
"Hainaut" => Ok(Self::Hainaut),
"Limburg" => Ok(Self::Limburg),
"Liège" => Ok(Self::Liege),
"Luxembourg" => Ok(Self::Luxembourg),
"Namur" => Ok(Self::Namur),
"Wallonia" => Ok(Self::Wallonia),
"Walloon Brabant" => Ok(Self::WalloonBrabant),
"West Flanders" => Ok(Self::WestFlanders),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for LuxembourgStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "LuxembourgStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Canton of Capellen" => Ok(Self::CantonOfCapellen),
"Canton of Clervaux" => Ok(Self::CantonOfClervaux),
"Canton of Diekirch" => Ok(Self::CantonOfDiekirch),
"Canton of Echternach" => Ok(Self::CantonOfEchternach),
"Canton of Esch-sur-Alzette" => Ok(Self::CantonOfEschSurAlzette),
"Canton of Grevenmacher" => Ok(Self::CantonOfGrevenmacher),
"Canton of Luxembourg" => Ok(Self::CantonOfLuxembourg),
"Canton of Mersch" => Ok(Self::CantonOfMersch),
"Canton of Redange" => Ok(Self::CantonOfRedange),
"Canton of Remich" => Ok(Self::CantonOfRemich),
"Canton of Vianden" => Ok(Self::CantonOfVianden),
"Canton of Wiltz" => Ok(Self::CantonOfWiltz),
"Diekirch District" => Ok(Self::DiekirchDistrict),
"Grevenmacher District" => Ok(Self::GrevenmacherDistrict),
"Luxembourg District" => Ok(Self::LuxembourgDistrict),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for RussiaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "RussiaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Altai Krai" => Ok(Self::AltaiKrai),
"Altai Republic" => Ok(Self::AltaiRepublic),
"Amur Oblast" => Ok(Self::AmurOblast),
"Arkhangelsk" => Ok(Self::Arkhangelsk),
"Astrakhan Oblast" => Ok(Self::AstrakhanOblast),
"Belgorod Oblast" => Ok(Self::BelgorodOblast),
"Bryansk Oblast" => Ok(Self::BryanskOblast),
"Chechen Republic" => Ok(Self::ChechenRepublic),
"Chelyabinsk Oblast" => Ok(Self::ChelyabinskOblast),
"Chukotka Autonomous Okrug" => Ok(Self::ChukotkaAutonomousOkrug),
"Chuvash Republic" => Ok(Self::ChuvashRepublic),
"Irkutsk" => Ok(Self::Irkutsk),
"Ivanovo Oblast" => Ok(Self::IvanovoOblast),
"Jewish Autonomous Oblast" => Ok(Self::JewishAutonomousOblast),
"Kabardino-Balkar Republic" => Ok(Self::KabardinoBalkarRepublic),
"Kaliningrad" => Ok(Self::Kaliningrad),
"Kaluga Oblast" => Ok(Self::KalugaOblast),
"Kamchatka Krai" => Ok(Self::KamchatkaKrai),
"Karachay-Cherkess Republic" => Ok(Self::KarachayCherkessRepublic),
"Kemerovo Oblast" => Ok(Self::KemerovoOblast),
"Khabarovsk Krai" => Ok(Self::KhabarovskKrai),
"Khanty-Mansi Autonomous Okrug" => Ok(Self::KhantyMansiAutonomousOkrug),
"Kirov Oblast" => Ok(Self::KirovOblast),
"Komi Republic" => Ok(Self::KomiRepublic),
"Kostroma Oblast" => Ok(Self::KostromaOblast),
"Krasnodar Krai" => Ok(Self::KrasnodarKrai),
"Krasnoyarsk Krai" => Ok(Self::KrasnoyarskKrai),
"Kurgan Oblast" => Ok(Self::KurganOblast),
"Kursk Oblast" => Ok(Self::KurskOblast),
"Leningrad Oblast" => Ok(Self::LeningradOblast),
"Lipetsk Oblast" => Ok(Self::LipetskOblast),
"Magadan Oblast" => Ok(Self::MagadanOblast),
"Mari El Republic" => Ok(Self::MariElRepublic),
"Moscow" => Ok(Self::Moscow),
"Moscow Oblast" => Ok(Self::MoscowOblast),
"Murmansk Oblast" => Ok(Self::MurmanskOblast),
"Nenets Autonomous Okrug" => Ok(Self::NenetsAutonomousOkrug),
"Nizhny Novgorod Oblast" => Ok(Self::NizhnyNovgorodOblast),
"Novgorod Oblast" => Ok(Self::NovgorodOblast),
"Novosibirsk" => Ok(Self::Novosibirsk),
"Omsk Oblast" => Ok(Self::OmskOblast),
"Orenburg Oblast" => Ok(Self::OrenburgOblast),
"Oryol Oblast" => Ok(Self::OryolOblast),
"Penza Oblast" => Ok(Self::PenzaOblast),
"Perm Krai" => Ok(Self::PermKrai),
"Primorsky Krai" => Ok(Self::PrimorskyKrai),
"Pskov Oblast" => Ok(Self::PskovOblast),
"Republic of Adygea" => Ok(Self::RepublicOfAdygea),
"Republic of Bashkortostan" => Ok(Self::RepublicOfBashkortostan),
"Republic of Buryatia" => Ok(Self::RepublicOfBuryatia),
"Republic of Dagestan" => Ok(Self::RepublicOfDagestan),
"Republic of Ingushetia" => Ok(Self::RepublicOfIngushetia),
"Republic of Kalmykia" => Ok(Self::RepublicOfKalmykia),
"Republic of Karelia" => Ok(Self::RepublicOfKarelia),
"Republic of Khakassia" => Ok(Self::RepublicOfKhakassia),
"Republic of Mordovia" => Ok(Self::RepublicOfMordovia),
"Republic of North Ossetia-Alania" => Ok(Self::RepublicOfNorthOssetiaAlania),
"Republic of Tatarstan" => Ok(Self::RepublicOfTatarstan),
"Rostov Oblast" => Ok(Self::RostovOblast),
"Ryazan Oblast" => Ok(Self::RyazanOblast),
"Saint Petersburg" => Ok(Self::SaintPetersburg),
"Sakha Republic" => Ok(Self::SakhaRepublic),
"Sakhalin" => Ok(Self::Sakhalin),
"Samara Oblast" => Ok(Self::SamaraOblast),
"Saratov Oblast" => Ok(Self::SaratovOblast),
"Sevastopol" => Ok(Self::Sevastopol),
"Smolensk Oblast" => Ok(Self::SmolenskOblast),
"Stavropol Krai" => Ok(Self::StavropolKrai),
"Sverdlovsk" => Ok(Self::Sverdlovsk),
"Tambov Oblast" => Ok(Self::TambovOblast),
"Tomsk Oblast" => Ok(Self::TomskOblast),
"Tula Oblast" => Ok(Self::TulaOblast),
"Tuva Republic" => Ok(Self::TuvaRepublic),
"Tver Oblast" => Ok(Self::TverOblast),
"Tyumen Oblast" => Ok(Self::TyumenOblast),
"Udmurt Republic" => Ok(Self::UdmurtRepublic),
"Ulyanovsk Oblast" => Ok(Self::UlyanovskOblast),
"Vladimir Oblast" => Ok(Self::VladimirOblast),
"Vologda Oblast" => Ok(Self::VologdaOblast),
"Voronezh Oblast" => Ok(Self::VoronezhOblast),
"Yamalo-Nenets Autonomous Okrug" => Ok(Self::YamaloNenetsAutonomousOkrug),
"Yaroslavl Oblast" => Ok(Self::YaroslavlOblast),
"Zabaykalsky Krai" => Ok(Self::ZabaykalskyKrai),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for SanMarinoStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "SanMarinoStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Acquaviva" => Ok(Self::Acquaviva),
"Borgo Maggiore" => Ok(Self::BorgoMaggiore),
"Chiesanuova" => Ok(Self::Chiesanuova),
"Domagnano" => Ok(Self::Domagnano),
"Faetano" => Ok(Self::Faetano),
"Fiorentino" => Ok(Self::Fiorentino),
"Montegiardino" => Ok(Self::Montegiardino),
"San Marino" => Ok(Self::SanMarino),
"Serravalle" => Ok(Self::Serravalle),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for SerbiaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "SerbiaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Belgrade" => Ok(Self::Belgrade),
"Bor District" => Ok(Self::BorDistrict),
"Braničevo District" => Ok(Self::BraničevoDistrict),
"Central Banat District" => Ok(Self::CentralBanatDistrict),
"Jablanica District" => Ok(Self::JablanicaDistrict),
"Kolubara District" => Ok(Self::KolubaraDistrict),
"Mačva District" => Ok(Self::MačvaDistrict),
"Moravica District" => Ok(Self::MoravicaDistrict),
"Nišava District" => Ok(Self::NišavaDistrict),
"North Banat District" => Ok(Self::NorthBanatDistrict),
"North Bačka District" => Ok(Self::NorthBačkaDistrict),
"Pirot District" => Ok(Self::PirotDistrict),
"Podunavlje District" => Ok(Self::PodunavljeDistrict),
"Pomoravlje District" => Ok(Self::PomoravljeDistrict),
"Pčinja District" => Ok(Self::PčinjaDistrict),
"Rasina District" => Ok(Self::RasinaDistrict),
"Raška District" => Ok(Self::RaškaDistrict),
"South Banat District" => Ok(Self::SouthBanatDistrict),
"South Bačka District" => Ok(Self::SouthBačkaDistrict),
"Srem District" => Ok(Self::SremDistrict),
"Toplica District" => Ok(Self::ToplicaDistrict),
"Vojvodina" => Ok(Self::Vojvodina),
"West Bačka District" => Ok(Self::WestBačkaDistrict),
"Zaječar District" => Ok(Self::ZaječarDistrict),
"Zlatibor District" => Ok(Self::ZlatiborDistrict),
"Šumadija District" => Ok(Self::ŠumadijaDistrict),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for SlovakiaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "SlovakiaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Banská Bystrica Region" => Ok(Self::BanskaBystricaRegion),
"Bratislava Region" => Ok(Self::BratislavaRegion),
"Košice Region" => Ok(Self::KosiceRegion),
"Nitra Region" => Ok(Self::NitraRegion),
"Prešov Region" => Ok(Self::PresovRegion),
"Trenčín Region" => Ok(Self::TrencinRegion),
"Trnava Region" => Ok(Self::TrnavaRegion),
"Žilina Region" => Ok(Self::ZilinaRegion),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for SwedenStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "SwedenStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Blekinge" => Ok(Self::Blekinge),
"Dalarna County" => Ok(Self::DalarnaCounty),
"Gotland County" => Ok(Self::GotlandCounty),
"Gävleborg County" => Ok(Self::GävleborgCounty),
"Halland County" => Ok(Self::HallandCounty),
"Jönköping County" => Ok(Self::JönköpingCounty),
"Kalmar County" => Ok(Self::KalmarCounty),
"Kronoberg County" => Ok(Self::KronobergCounty),
"Norrbotten County" => Ok(Self::NorrbottenCounty),
"Skåne County" => Ok(Self::SkåneCounty),
"Stockholm County" => Ok(Self::StockholmCounty),
"Södermanland County" => Ok(Self::SödermanlandCounty),
"Uppsala County" => Ok(Self::UppsalaCounty),
"Värmland County" => Ok(Self::VärmlandCounty),
"Västerbotten County" => Ok(Self::VästerbottenCounty),
"Västernorrland County" => Ok(Self::VästernorrlandCounty),
"Västmanland County" => Ok(Self::VästmanlandCounty),
"Västra Götaland County" => Ok(Self::VästraGötalandCounty),
"Örebro County" => Ok(Self::ÖrebroCounty),
"Östergötland County" => Ok(Self::ÖstergötlandCounty),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for SloveniaStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "SloveniaStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Ajdovščina Municipality" => Ok(Self::Ajdovščina),
"Ankaran Municipality" => Ok(Self::Ankaran),
"Beltinci Municipality" => Ok(Self::Beltinci),
"Benedikt Municipality" => Ok(Self::Benedikt),
"Bistrica ob Sotli Municipality" => Ok(Self::BistricaObSotli),
"Bled Municipality" => Ok(Self::Bled),
"Bloke Municipality" => Ok(Self::Bloke),
"Bohinj Municipality" => Ok(Self::Bohinj),
"Borovnica Municipality" => Ok(Self::Borovnica),
"Bovec Municipality" => Ok(Self::Bovec),
"Braslovče Municipality" => Ok(Self::Braslovče),
"Brda Municipality" => Ok(Self::Brda),
"Brezovica Municipality" => Ok(Self::Brezovica),
"Brežice Municipality" => Ok(Self::Brežice),
"Cankova Municipality" => Ok(Self::Cankova),
"Cerklje na Gorenjskem Municipality" => Ok(Self::CerkljeNaGorenjskem),
"Cerknica Municipality" => Ok(Self::Cerknica),
"Cerkno Municipality" => Ok(Self::Cerkno),
"Cerkvenjak Municipality" => Ok(Self::Cerkvenjak),
"City Municipality of Celje" => Ok(Self::CityMunicipalityOfCelje),
"City Municipality of Novo Mesto" => Ok(Self::CityMunicipalityOfNovoMesto),
"Destrnik Municipality" => Ok(Self::Destrnik),
"Divača Municipality" => Ok(Self::Divača),
"Dobje Municipality" => Ok(Self::Dobje),
"Dobrepolje Municipality" => Ok(Self::Dobrepolje),
"Dobrna Municipality" => Ok(Self::Dobrna),
"Dobrova–Polhov Gradec Municipality" => Ok(Self::DobrovaPolhovGradec),
"Dobrovnik Municipality" => Ok(Self::Dobrovnik),
"Dol pri Ljubljani Municipality" => Ok(Self::DolPriLjubljani),
"Dolenjske Toplice Municipality" => Ok(Self::DolenjskeToplice),
"Domžale Municipality" => Ok(Self::Domžale),
"Dornava Municipality" => Ok(Self::Dornava),
"Dravograd Municipality" => Ok(Self::Dravograd),
"Duplek Municipality" => Ok(Self::Duplek),
"Gorenja Vas–Poljane Municipality" => Ok(Self::GorenjaVasPoljane),
"Gorišnica Municipality" => Ok(Self::Gorišnica),
"Gorje Municipality" => Ok(Self::Gorje),
"Gornja Radgona Municipality" => Ok(Self::GornjaRadgona),
"Gornji Grad Municipality" => Ok(Self::GornjiGrad),
"Gornji Petrovci Municipality" => Ok(Self::GornjiPetrovci),
"Grad Municipality" => Ok(Self::Grad),
"Grosuplje Municipality" => Ok(Self::Grosuplje),
"Hajdina Municipality" => Ok(Self::Hajdina),
"Hodoš Municipality" => Ok(Self::Hodoš),
"Horjul Municipality" => Ok(Self::Horjul),
"Hoče–Slivnica Municipality" => Ok(Self::HočeSlivnica),
"Hrastnik Municipality" => Ok(Self::Hrastnik),
"Hrpelje–Kozina Municipality" => Ok(Self::HrpeljeKozina),
"Idrija Municipality" => Ok(Self::Idrija),
"Ig Municipality" => Ok(Self::Ig),
"Ivančna Gorica Municipality" => Ok(Self::IvančnaGorica),
"Izola Municipality" => Ok(Self::Izola),
"Jesenice Municipality" => Ok(Self::Jesenice),
"Jezersko Municipality" => Ok(Self::Jezersko),
"Juršinci Municipality" => Ok(Self::Jursinci),
"Kamnik Municipality" => Ok(Self::Kamnik),
"Kanal ob Soči Municipality" => Ok(Self::KanalObSoci),
"Kidričevo Municipality" => Ok(Self::Kidricevo),
"Kobarid Municipality" => Ok(Self::Kobarid),
"Kobilje Municipality" => Ok(Self::Kobilje),
"Komen Municipality" => Ok(Self::Komen),
"Komenda Municipality" => Ok(Self::Komenda),
"Koper City Municipality" => Ok(Self::Koper),
"Kostanjevica na Krki Municipality" => Ok(Self::KostanjevicaNaKrki),
"Kostel Municipality" => Ok(Self::Kostel),
"Kozje Municipality" => Ok(Self::Kozje),
"Kočevje Municipality" => Ok(Self::Kocevje),
"Kranj City Municipality" => Ok(Self::Kranj),
"Kranjska Gora Municipality" => Ok(Self::KranjskaGora),
"Križevci Municipality" => Ok(Self::Krizevci),
"Kungota" => Ok(Self::Kungota),
"Kuzma Municipality" => Ok(Self::Kuzma),
"Laško Municipality" => Ok(Self::Lasko),
"Lenart Municipality" => Ok(Self::Lenart),
"Lendava Municipality" => Ok(Self::Lendava),
"Litija Municipality" => Ok(Self::Litija),
"Ljubljana City Municipality" => Ok(Self::Ljubljana),
"Ljubno Municipality" => Ok(Self::Ljubno),
"Ljutomer Municipality" => Ok(Self::Ljutomer),
"Logatec Municipality" => Ok(Self::Logatec),
"Log–Dragomer Municipality" => Ok(Self::LogDragomer),
"Lovrenc na Pohorju Municipality" => Ok(Self::LovrencNaPohorju),
"Loška Dolina Municipality" => Ok(Self::LoskaDolina),
"Loški Potok Municipality" => Ok(Self::LoskiPotok),
"Lukovica Municipality" => Ok(Self::Lukovica),
"Luče Municipality" => Ok(Self::Luče),
"Majšperk Municipality" => Ok(Self::Majsperk),
"Makole Municipality" => Ok(Self::Makole),
"Maribor City Municipality" => Ok(Self::Maribor),
"Markovci Municipality" => Ok(Self::Markovci),
"Medvode Municipality" => Ok(Self::Medvode),
"Mengeš Municipality" => Ok(Self::Menges),
"Metlika Municipality" => Ok(Self::Metlika),
"Mežica Municipality" => Ok(Self::Mezica),
"Miklavž na Dravskem Polju Municipality" => Ok(Self::MiklavzNaDravskemPolju),
"Miren–Kostanjevica Municipality" => Ok(Self::MirenKostanjevica),
"Mirna Municipality" => Ok(Self::Mirna),
"Mirna Peč Municipality" => Ok(Self::MirnaPec),
"Mislinja Municipality" => Ok(Self::Mislinja),
"Mokronog–Trebelno Municipality" => Ok(Self::MokronogTrebelno),
"Moravske Toplice Municipality" => Ok(Self::MoravskeToplice),
"Moravče Municipality" => Ok(Self::Moravce),
"Mozirje Municipality" => Ok(Self::Mozirje),
"Municipality of Apače" => Ok(Self::Apače),
"Municipality of Cirkulane" => Ok(Self::Cirkulane),
"Municipality of Ilirska Bistrica" => Ok(Self::IlirskaBistrica),
"Municipality of Krško" => Ok(Self::Krsko),
"Municipality of Škofljica" => Ok(Self::Skofljica),
"Murska Sobota City Municipality" => Ok(Self::MurskaSobota),
"Muta Municipality" => Ok(Self::Muta),
"Naklo Municipality" => Ok(Self::Naklo),
"Nazarje Municipality" => Ok(Self::Nazarje),
"Nova Gorica City Municipality" => Ok(Self::NovaGorica),
"Odranci Municipality" => Ok(Self::Odranci),
"Oplotnica" => Ok(Self::Oplotnica),
"Ormož Municipality" => Ok(Self::Ormoz),
"Osilnica Municipality" => Ok(Self::Osilnica),
"Pesnica Municipality" => Ok(Self::Pesnica),
"Piran Municipality" => Ok(Self::Piran),
"Pivka Municipality" => Ok(Self::Pivka),
"Podlehnik Municipality" => Ok(Self::Podlehnik),
"Podvelka Municipality" => Ok(Self::Podvelka),
"Podčetrtek Municipality" => Ok(Self::Podcetrtek),
"Poljčane Municipality" => Ok(Self::Poljcane),
"Polzela Municipality" => Ok(Self::Polzela),
"Postojna Municipality" => Ok(Self::Postojna),
"Prebold Municipality" => Ok(Self::Prebold),
"Preddvor Municipality" => Ok(Self::Preddvor),
"Prevalje Municipality" => Ok(Self::Prevalje),
"Ptuj City Municipality" => Ok(Self::Ptuj),
"Puconci Municipality" => Ok(Self::Puconci),
"Radenci Municipality" => Ok(Self::Radenci),
"Radeče Municipality" => Ok(Self::Radece),
"Radlje ob Dravi Municipality" => Ok(Self::RadljeObDravi),
"Radovljica Municipality" => Ok(Self::Radovljica),
"Ravne na Koroškem Municipality" => Ok(Self::RavneNaKoroskem),
"Razkrižje Municipality" => Ok(Self::Razkrizje),
"Rače–Fram Municipality" => Ok(Self::RaceFram),
"Renče–Vogrsko Municipality" => Ok(Self::RenčeVogrsko),
"Rečica ob Savinji Municipality" => Ok(Self::RecicaObSavinji),
"Ribnica Municipality" => Ok(Self::Ribnica),
"Ribnica na Pohorju Municipality" => Ok(Self::RibnicaNaPohorju),
"Rogatec Municipality" => Ok(Self::Rogatec),
"Rogaška Slatina Municipality" => Ok(Self::RogaskaSlatina),
"Rogašovci Municipality" => Ok(Self::Rogasovci),
"Ruše Municipality" => Ok(Self::Ruse),
"Selnica ob Dravi Municipality" => Ok(Self::SelnicaObDravi),
"Semič Municipality" => Ok(Self::Semic),
"Sevnica Municipality" => Ok(Self::Sevnica),
"Sežana Municipality" => Ok(Self::Sezana),
"Slovenj Gradec City Municipality" => Ok(Self::SlovenjGradec),
"Slovenska Bistrica Municipality" => Ok(Self::SlovenskaBistrica),
"Slovenske Konjice Municipality" => Ok(Self::SlovenskeKonjice),
"Sodražica Municipality" => Ok(Self::Sodrazica),
"Solčava Municipality" => Ok(Self::Solcava),
"Središče ob Dravi" => Ok(Self::SredisceObDravi),
"Starše Municipality" => Ok(Self::Starse),
"Straža Municipality" => Ok(Self::Straza),
"Sveta Ana Municipality" => Ok(Self::SvetaAna),
"Sveta Trojica v Slovenskih Goricah Municipality" => Ok(Self::SvetaTrojica),
"Sveti Andraž v Slovenskih Goricah Municipality" => Ok(Self::SvetiAndraz),
"Sveti Jurij ob Ščavnici Municipality" => Ok(Self::SvetiJurijObScavnici),
"Sveti Jurij v Slovenskih Goricah Municipality" => {
Ok(Self::SvetiJurijVSlovenskihGoricah)
}
"Sveti Tomaž Municipality" => Ok(Self::SvetiTomaz),
"Tabor Municipality" => Ok(Self::Tabor),
"Tišina Municipality" => Ok(Self::Tišina),
"Tolmin Municipality" => Ok(Self::Tolmin),
"Trbovlje Municipality" => Ok(Self::Trbovlje),
"Trebnje Municipality" => Ok(Self::Trebnje),
"Trnovska Vas Municipality" => Ok(Self::TrnovskaVas),
"Trzin Municipality" => Ok(Self::Trzin),
"Tržič Municipality" => Ok(Self::Tržič),
"Turnišče Municipality" => Ok(Self::Turnišče),
"Velika Polana Municipality" => Ok(Self::VelikaPolana),
"Velike Lašče Municipality" => Ok(Self::VelikeLašče),
"Veržej Municipality" => Ok(Self::Veržej),
"Videm Municipality" => Ok(Self::Videm),
"Vipava Municipality" => Ok(Self::Vipava),
"Vitanje Municipality" => Ok(Self::Vitanje),
"Vodice Municipality" => Ok(Self::Vodice),
"Vojnik Municipality" => Ok(Self::Vojnik),
"Vransko Municipality" => Ok(Self::Vransko),
"Vrhnika Municipality" => Ok(Self::Vrhnika),
"Vuzenica Municipality" => Ok(Self::Vuzenica),
"Zagorje ob Savi Municipality" => Ok(Self::ZagorjeObSavi),
"Zavrč Municipality" => Ok(Self::Zavrč),
"Zreče Municipality" => Ok(Self::Zreče),
"Črenšovci Municipality" => Ok(Self::Črenšovci),
"Črna na Koroškem Municipality" => Ok(Self::ČrnaNaKoroškem),
"Črnomelj Municipality" => Ok(Self::Črnomelj),
"Šalovci Municipality" => Ok(Self::Šalovci),
"Šempeter–Vrtojba Municipality" => Ok(Self::ŠempeterVrtojba),
"Šentilj Municipality" => Ok(Self::Šentilj),
"Šentjernej Municipality" => Ok(Self::Šentjernej),
"Šentjur Municipality" => Ok(Self::Šentjur),
"Šentrupert Municipality" => Ok(Self::Šentrupert),
"Šenčur Municipality" => Ok(Self::Šenčur),
"Škocjan Municipality" => Ok(Self::Škocjan),
"Škofja Loka Municipality" => Ok(Self::ŠkofjaLoka),
"Šmarje pri Jelšah Municipality" => Ok(Self::ŠmarjePriJelšah),
"Šmarješke Toplice Municipality" => Ok(Self::ŠmarješkeToplice),
"Šmartno ob Paki Municipality" => Ok(Self::ŠmartnoObPaki),
"Šmartno pri Litiji Municipality" => Ok(Self::ŠmartnoPriLitiji),
"Šoštanj Municipality" => Ok(Self::Šoštanj),
"Štore Municipality" => Ok(Self::Štore),
"Žalec Municipality" => Ok(Self::Žalec),
"Železniki Municipality" => Ok(Self::Železniki),
"Žetale Municipality" => Ok(Self::Žetale),
"Žiri Municipality" => Ok(Self::Žiri),
"Žirovnica Municipality" => Ok(Self::Žirovnica),
"Žužemberk Municipality" => Ok(Self::Žužemberk),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for UkraineStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "UkraineStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Autonomous Republic of Crimea" => Ok(Self::AutonomousRepublicOfCrimea),
"Cherkasy Oblast" => Ok(Self::CherkasyOblast),
"Chernihiv Oblast" => Ok(Self::ChernihivOblast),
"Chernivtsi Oblast" => Ok(Self::ChernivtsiOblast),
"Dnipropetrovsk Oblast" => Ok(Self::DnipropetrovskOblast),
"Donetsk Oblast" => Ok(Self::DonetskOblast),
"Ivano-Frankivsk Oblast" => Ok(Self::IvanoFrankivskOblast),
"Kharkiv Oblast" => Ok(Self::KharkivOblast),
"Kherson Oblast" => Ok(Self::KhersonOblast),
"Khmelnytsky Oblast" => Ok(Self::KhmelnytskyOblast),
"Kiev" => Ok(Self::Kiev),
"Kirovohrad Oblast" => Ok(Self::KirovohradOblast),
"Kyiv Oblast" => Ok(Self::KyivOblast),
"Luhansk Oblast" => Ok(Self::LuhanskOblast),
"Lviv Oblast" => Ok(Self::LvivOblast),
"Mykolaiv Oblast" => Ok(Self::MykolaivOblast),
"Odessa Oblast" => Ok(Self::OdessaOblast),
"Rivne Oblast" => Ok(Self::RivneOblast),
"Sumy Oblast" => Ok(Self::SumyOblast),
"Ternopil Oblast" => Ok(Self::TernopilOblast),
"Vinnytsia Oblast" => Ok(Self::VinnytsiaOblast),
"Volyn Oblast" => Ok(Self::VolynOblast),
"Zakarpattia Oblast" => Ok(Self::ZakarpattiaOblast),
"Zaporizhzhya Oblast" => Ok(Self::ZaporizhzhyaOblast),
"Zhytomyr Oblast" => Ok(Self::ZhytomyrOblast),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
impl ForeignTryFrom<String> for BrazilStatesAbbreviation {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(value: String) -> Result<Self, Self::Error> {
let state_abbreviation_check =
StringExt::<Self>::parse_enum(value.clone(), "BrazilStatesAbbreviation");
match state_abbreviation_check {
Ok(state_abbreviation) => Ok(state_abbreviation),
Err(_) => match value.as_str() {
"Acre" => Ok(Self::Acre),
"Alagoas" => Ok(Self::Alagoas),
"Amapá" => Ok(Self::Amapá),
"Amazonas" => Ok(Self::Amazonas),
"Bahia" => Ok(Self::Bahia),
"Ceará" => Ok(Self::Ceará),
"Distrito Federal" => Ok(Self::DistritoFederal),
"Espírito Santo" => Ok(Self::EspíritoSanto),
"Goiás" => Ok(Self::Goiás),
"Maranhão" => Ok(Self::Maranhão),
"Mato Grosso" => Ok(Self::MatoGrosso),
"Mato Grosso do Sul" => Ok(Self::MatoGrossoDoSul),
"Minas Gerais" => Ok(Self::MinasGerais),
"Pará" => Ok(Self::Pará),
"Paraíba" => Ok(Self::Paraíba),
"Paraná" => Ok(Self::Paraná),
"Pernambuco" => Ok(Self::Pernambuco),
"Piauí" => Ok(Self::Piauí),
"Rio de Janeiro" => Ok(Self::RioDeJaneiro),
"Rio Grande do Norte" => Ok(Self::RioGrandeDoNorte),
"Rio Grande do Sul" => Ok(Self::RioGrandeDoSul),
"Rondônia" => Ok(Self::Rondônia),
"Roraima" => Ok(Self::Roraima),
"Santa Catarina" => Ok(Self::SantaCatarina),
"São Paulo" => Ok(Self::SãoPaulo),
"Sergipe" => Ok(Self::Sergipe),
"Tocantins" => Ok(Self::Tocantins),
_ => Err(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
}
.into()),
},
}
}
}
pub trait ForeignTryFrom<F>: Sized {
type Error;
fn foreign_try_from(from: F) -> Result<Self, Self::Error>;
}
#[derive(Debug)]
pub struct QrImage {
pub data: String,
}
// Qr Image data source starts with this string
// The base64 image data will be appended to it to image data source
pub(crate) const QR_IMAGE_DATA_SOURCE_STRING: &str = "data:image/png;base64";
impl QrImage {
pub fn new_from_data(
data: String,
) -> Result<Self, error_stack::Report<common_utils::errors::QrCodeError>> {
let qr_code = qrcode::QrCode::new(data.as_bytes())
.change_context(common_utils::errors::QrCodeError::FailedToCreateQrCode)?;
let qrcode_image_buffer = qr_code.render::<Luma<u8>>().build();
let qrcode_dynamic_image = DynamicImage::ImageLuma8(qrcode_image_buffer);
let mut image_bytes = std::io::BufWriter::new(std::io::Cursor::new(Vec::new()));
// Encodes qrcode_dynamic_image and write it to image_bytes
let _ = qrcode_dynamic_image.write_to(&mut image_bytes, ImageFormat::Png);
let image_data_source = format!(
"{},{}",
QR_IMAGE_DATA_SOURCE_STRING,
BASE64_ENGINE.encode(image_bytes.buffer())
);
Ok(Self {
data: image_data_source,
})
}
pub fn new_colored_from_data(
data: String,
hex_color: &str,
) -> Result<Self, error_stack::Report<common_utils::errors::QrCodeError>> {
let qr_code = qrcode::QrCode::new(data.as_bytes())
.change_context(common_utils::errors::QrCodeError::FailedToCreateQrCode)?;
let qrcode_image_buffer = qr_code.render::<Luma<u8>>().build();
let (width, height) = qrcode_image_buffer.dimensions();
let mut colored_image = ImageBuffer::new(width, height);
let rgb = Self::parse_hex_color(hex_color)?;
for (x, y, pixel) in qrcode_image_buffer.enumerate_pixels() {
let luminance = pixel.0[0];
let color = if luminance == 0 {
Rgba([rgb.0, rgb.1, rgb.2, 255])
} else {
Rgba([255, 255, 255, 255])
};
colored_image.put_pixel(x, y, color);
}
let qrcode_dynamic_image = DynamicImage::ImageRgba8(colored_image);
let mut image_bytes = std::io::Cursor::new(Vec::new());
qrcode_dynamic_image
.write_to(&mut image_bytes, ImageFormat::Png)
.change_context(common_utils::errors::QrCodeError::FailedToCreateQrCode)?;
let image_data_source = format!(
"{},{}",
QR_IMAGE_DATA_SOURCE_STRING,
BASE64_ENGINE.encode(image_bytes.get_ref())
);
Ok(Self {
data: image_data_source,
})
}
pub fn parse_hex_color(hex: &str) -> Result<(u8, u8, u8), common_utils::errors::QrCodeError> {
let hex = hex.trim_start_matches('#');
if hex.len() == 6 {
let r = u8::from_str_radix(&hex[0..2], 16).ok();
let g = u8::from_str_radix(&hex[2..4], 16).ok();
let b = u8::from_str_radix(&hex[4..6], 16).ok();
if let (Some(r), Some(g), Some(b)) = (r, g, b) {
return Ok((r, g, b));
}
}
Err(common_utils::errors::QrCodeError::InvalidHexColor)
}
}
#[cfg(test)]
mod tests {
use crate::utils;
#[test]
fn test_image_data_source_url() {
let qr_image_data_source_url = utils::QrImage::new_from_data("Hyperswitch".to_string());
assert!(qr_image_data_source_url.is_ok());
}
}
pub fn is_mandate_supported(
selected_pmd: PaymentMethodData,
payment_method_type: Option<enums::PaymentMethodType>,
mandate_implemented_pmds: HashSet<PaymentMethodDataType>,
connector: &'static str,
) -> Result<(), Error> {
if mandate_implemented_pmds.contains(&PaymentMethodDataType::from(selected_pmd.clone())) {
Ok(())
} else {
match payment_method_type {
Some(pm_type) => Err(errors::ConnectorError::NotSupported {
message: format!("{pm_type} mandate payment"),
connector,
}
.into()),
None => Err(errors::ConnectorError::NotSupported {
message: "mandate payment".to_string(),
connector,
}
.into()),
}
}
}
pub fn get_mandate_details(
setup_mandate_details: Option<mandates::MandateData>,
) -> Result<Option<mandates::MandateAmountData>, error_stack::Report<errors::ConnectorError>> {
setup_mandate_details
.map(|mandate_data| match &mandate_data.mandate_type {
Some(mandates::MandateDataType::SingleUse(mandate))
| Some(mandates::MandateDataType::MultiUse(Some(mandate))) => Ok(mandate.clone()),
Some(mandates::MandateDataType::MultiUse(None)) => {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "setup_future_usage.mandate_data.mandate_type.multi_use.amount",
}
.into())
}
None => Err(errors::ConnectorError::MissingRequiredField {
field_name: "setup_future_usage.mandate_data.mandate_type",
}
.into()),
})
.transpose()
}
pub fn collect_values_by_removing_signature(value: &Value, signature: &String) -> Vec<String> {
match value {
Value::Null => vec!["null".to_owned()],
Value::Bool(b) => vec![b.to_string()],
Value::Number(n) => match n.as_f64() {
Some(f) => vec![format!("{f:.2}")],
None => vec![n.to_string()],
},
Value::String(s) => {
if signature == s {
vec![]
} else {
vec![s.clone()]
}
}
Value::Array(arr) => arr
.iter()
.flat_map(|v| collect_values_by_removing_signature(v, signature))
.collect(),
Value::Object(obj) => obj
.values()
.flat_map(|v| collect_values_by_removing_signature(v, signature))
.collect(),
}
}
pub fn collect_and_sort_values_by_removing_signature(
value: &Value,
signature: &String,
) -> Vec<String> {
let mut values = collect_values_by_removing_signature(value, signature);
values.sort();
values
}
#[derive(Debug, strum::Display, Eq, PartialEq, Hash)]
pub enum PaymentMethodDataType {
Card,
Knet,
Benefit,
MomoAtm,
CardRedirect,
AliPayQr,
AliPayRedirect,
AliPayHkRedirect,
AmazonPay,
AmazonPayRedirect,
Skrill,
Paysera,
MomoRedirect,
KakaoPayRedirect,
GoPayRedirect,
GcashRedirect,
ApplePay,
ApplePayRedirect,
ApplePayThirdPartySdk,
DanaRedirect,
DuitNow,
GooglePay,
Bluecode,
GooglePayRedirect,
GooglePayThirdPartySdk,
MbWayRedirect,
MobilePayRedirect,
PaypalRedirect,
PaypalSdk,
Paze,
SamsungPay,
TwintRedirect,
VippsRedirect,
TouchNGoRedirect,
WeChatPayRedirect,
WeChatPayQr,
CashappQr,
SwishQr,
KlarnaRedirect,
KlarnaSdk,
AffirmRedirect,
AfterpayClearpayRedirect,
PayBrightRedirect,
WalleyRedirect,
AlmaRedirect,
AtomeRedirect,
Breadpay,
FlexitiRedirect,
BancontactCard,
Bizum,
Blik,
Eft,
Eps,
Giropay,
Ideal,
Interac,
LocalBankRedirect,
OnlineBankingCzechRepublic,
OnlineBankingFinland,
OnlineBankingPoland,
OnlineBankingSlovakia,
OpenBankingUk,
Przelewy24,
Sofort,
Trustly,
OnlineBankingFpx,
OnlineBankingThailand,
AchBankDebit,
SepaBankDebit,
SepaGuarenteedDebit,
BecsBankDebit,
BacsBankDebit,
AchBankTransfer,
SepaBankTransfer,
BacsBankTransfer,
MultibancoBankTransfer,
PermataBankTransfer,
BcaBankTransfer,
BniVaBankTransfer,
BhnCardNetwork,
BriVaBankTransfer,
CimbVaBankTransfer,
DanamonVaBankTransfer,
MandiriVaBankTransfer,
Pix,
Pse,
Crypto,
MandatePayment,
Reward,
Upi,
Boleto,
Efecty,
PagoEfectivo,
RedCompra,
RedPagos,
Alfamart,
Indomaret,
Oxxo,
SevenEleven,
Lawson,
MiniStop,
FamilyMart,
Seicomart,
PayEasy,
Givex,
PaySafeCar,
CardToken,
LocalBankTransfer,
Mifinity,
Fps,
PromptPay,
VietQr,
OpenBanking,
NetworkToken,
NetworkTransactionIdAndCardDetails,
DirectCarrierBilling,
InstantBankTransfer,
InstantBankTransferFinland,
InstantBankTransferPoland,
RevolutPay,
IndonesianBankTransfer,
}
impl From<PaymentMethodData> for PaymentMethodDataType {
fn from(pm_data: PaymentMethodData) -> Self {
match pm_data {
PaymentMethodData::Card(_) => Self::Card,
PaymentMethodData::NetworkToken(_) => Self::NetworkToken,
PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Self::NetworkTransactionIdAndCardDetails
}
PaymentMethodData::CardRedirect(card_redirect_data) => match card_redirect_data {
payment_method_data::CardRedirectData::Knet {} => Self::Knet,
payment_method_data::CardRedirectData::Benefit {} => Self::Benefit,
payment_method_data::CardRedirectData::MomoAtm {} => Self::MomoAtm,
payment_method_data::CardRedirectData::CardRedirect {} => Self::CardRedirect,
},
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
payment_method_data::WalletData::AliPayQr(_) => Self::AliPayQr,
payment_method_data::WalletData::AliPayRedirect(_) => Self::AliPayRedirect,
payment_method_data::WalletData::AliPayHkRedirect(_) => Self::AliPayHkRedirect,
payment_method_data::WalletData::AmazonPayRedirect(_) => Self::AmazonPayRedirect,
payment_method_data::WalletData::Skrill(_) => Self::Skrill,
payment_method_data::WalletData::Paysera(_) => Self::Paysera,
payment_method_data::WalletData::MomoRedirect(_) => Self::MomoRedirect,
payment_method_data::WalletData::KakaoPayRedirect(_) => Self::KakaoPayRedirect,
payment_method_data::WalletData::GoPayRedirect(_) => Self::GoPayRedirect,
payment_method_data::WalletData::GcashRedirect(_) => Self::GcashRedirect,
payment_method_data::WalletData::AmazonPay(_) => Self::AmazonPay,
payment_method_data::WalletData::ApplePay(_) => Self::ApplePay,
payment_method_data::WalletData::ApplePayRedirect(_) => Self::ApplePayRedirect,
payment_method_data::WalletData::ApplePayThirdPartySdk(_) => {
Self::ApplePayThirdPartySdk
}
payment_method_data::WalletData::DanaRedirect {} => Self::DanaRedirect,
payment_method_data::WalletData::GooglePay(_) => Self::GooglePay,
payment_method_data::WalletData::BluecodeRedirect {} => Self::Bluecode,
payment_method_data::WalletData::GooglePayRedirect(_) => Self::GooglePayRedirect,
payment_method_data::WalletData::GooglePayThirdPartySdk(_) => {
Self::GooglePayThirdPartySdk
}
payment_method_data::WalletData::MbWayRedirect(_) => Self::MbWayRedirect,
payment_method_data::WalletData::MobilePayRedirect(_) => Self::MobilePayRedirect,
payment_method_data::WalletData::PaypalRedirect(_) => Self::PaypalRedirect,
payment_method_data::WalletData::PaypalSdk(_) => Self::PaypalSdk,
payment_method_data::WalletData::Paze(_) => Self::Paze,
payment_method_data::WalletData::SamsungPay(_) => Self::SamsungPay,
payment_method_data::WalletData::TwintRedirect {} => Self::TwintRedirect,
payment_method_data::WalletData::VippsRedirect {} => Self::VippsRedirect,
payment_method_data::WalletData::TouchNGoRedirect(_) => Self::TouchNGoRedirect,
payment_method_data::WalletData::WeChatPayRedirect(_) => Self::WeChatPayRedirect,
payment_method_data::WalletData::WeChatPayQr(_) => Self::WeChatPayQr,
payment_method_data::WalletData::CashappQr(_) => Self::CashappQr,
payment_method_data::WalletData::SwishQr(_) => Self::SwishQr,
payment_method_data::WalletData::Mifinity(_) => Self::Mifinity,
payment_method_data::WalletData::RevolutPay(_) => Self::RevolutPay,
},
PaymentMethodData::PayLater(pay_later_data) => match pay_later_data {
payment_method_data::PayLaterData::KlarnaRedirect { .. } => Self::KlarnaRedirect,
payment_method_data::PayLaterData::KlarnaSdk { .. } => Self::KlarnaSdk,
payment_method_data::PayLaterData::AffirmRedirect {} => Self::AffirmRedirect,
payment_method_data::PayLaterData::AfterpayClearpayRedirect { .. } => {
Self::AfterpayClearpayRedirect
}
payment_method_data::PayLaterData::FlexitiRedirect { .. } => Self::FlexitiRedirect,
payment_method_data::PayLaterData::PayBrightRedirect {} => Self::PayBrightRedirect,
payment_method_data::PayLaterData::WalleyRedirect {} => Self::WalleyRedirect,
payment_method_data::PayLaterData::AlmaRedirect {} => Self::AlmaRedirect,
payment_method_data::PayLaterData::AtomeRedirect {} => Self::AtomeRedirect,
payment_method_data::PayLaterData::BreadpayRedirect {} => Self::Breadpay,
},
PaymentMethodData::BankRedirect(bank_redirect_data) => match bank_redirect_data {
payment_method_data::BankRedirectData::BancontactCard { .. } => {
Self::BancontactCard
}
payment_method_data::BankRedirectData::Bizum {} => Self::Bizum,
payment_method_data::BankRedirectData::Blik { .. } => Self::Blik,
payment_method_data::BankRedirectData::Eft { .. } => Self::Eft,
payment_method_data::BankRedirectData::Eps { .. } => Self::Eps,
payment_method_data::BankRedirectData::Giropay { .. } => Self::Giropay,
payment_method_data::BankRedirectData::Ideal { .. } => Self::Ideal,
payment_method_data::BankRedirectData::Interac { .. } => Self::Interac,
payment_method_data::BankRedirectData::OnlineBankingCzechRepublic { .. } => {
Self::OnlineBankingCzechRepublic
}
payment_method_data::BankRedirectData::OnlineBankingFinland { .. } => {
Self::OnlineBankingFinland
}
payment_method_data::BankRedirectData::OnlineBankingPoland { .. } => {
Self::OnlineBankingPoland
}
payment_method_data::BankRedirectData::OnlineBankingSlovakia { .. } => {
Self::OnlineBankingSlovakia
}
payment_method_data::BankRedirectData::OpenBankingUk { .. } => Self::OpenBankingUk,
payment_method_data::BankRedirectData::Przelewy24 { .. } => Self::Przelewy24,
payment_method_data::BankRedirectData::Sofort { .. } => Self::Sofort,
payment_method_data::BankRedirectData::Trustly { .. } => Self::Trustly,
payment_method_data::BankRedirectData::OnlineBankingFpx { .. } => {
Self::OnlineBankingFpx
}
payment_method_data::BankRedirectData::OnlineBankingThailand { .. } => {
Self::OnlineBankingThailand
}
payment_method_data::BankRedirectData::LocalBankRedirect {} => {
Self::LocalBankRedirect
}
},
PaymentMethodData::BankDebit(bank_debit_data) => match bank_debit_data {
payment_method_data::BankDebitData::AchBankDebit { .. } => Self::AchBankDebit,
payment_method_data::BankDebitData::SepaBankDebit { .. } => Self::SepaBankDebit,
payment_method_data::BankDebitData::SepaGuarenteedBankDebit { .. } => {
Self::SepaGuarenteedDebit
}
payment_method_data::BankDebitData::BecsBankDebit { .. } => Self::BecsBankDebit,
payment_method_data::BankDebitData::BacsBankDebit { .. } => Self::BacsBankDebit,
},
PaymentMethodData::BankTransfer(bank_transfer_data) => match *bank_transfer_data {
payment_method_data::BankTransferData::AchBankTransfer { .. } => {
Self::AchBankTransfer
}
payment_method_data::BankTransferData::SepaBankTransfer { .. } => {
Self::SepaBankTransfer
}
payment_method_data::BankTransferData::BacsBankTransfer { .. } => {
Self::BacsBankTransfer
}
payment_method_data::BankTransferData::MultibancoBankTransfer { .. } => {
Self::MultibancoBankTransfer
}
payment_method_data::BankTransferData::PermataBankTransfer { .. } => {
Self::PermataBankTransfer
}
payment_method_data::BankTransferData::BcaBankTransfer { .. } => {
Self::BcaBankTransfer
}
payment_method_data::BankTransferData::BniVaBankTransfer { .. } => {
Self::BniVaBankTransfer
}
payment_method_data::BankTransferData::BriVaBankTransfer { .. } => {
Self::BriVaBankTransfer
}
payment_method_data::BankTransferData::CimbVaBankTransfer { .. } => {
Self::CimbVaBankTransfer
}
payment_method_data::BankTransferData::DanamonVaBankTransfer { .. } => {
Self::DanamonVaBankTransfer
}
payment_method_data::BankTransferData::MandiriVaBankTransfer { .. } => {
Self::MandiriVaBankTransfer
}
payment_method_data::BankTransferData::Pix { .. } => Self::Pix,
payment_method_data::BankTransferData::Pse {} => Self::Pse,
payment_method_data::BankTransferData::LocalBankTransfer { .. } => {
Self::LocalBankTransfer
}
payment_method_data::BankTransferData::InstantBankTransfer {} => {
Self::InstantBankTransfer
}
payment_method_data::BankTransferData::InstantBankTransferFinland {} => {
Self::InstantBankTransferFinland
}
payment_method_data::BankTransferData::InstantBankTransferPoland {} => {
Self::InstantBankTransferPoland
}
payment_method_data::BankTransferData::IndonesianBankTransfer { .. } => {
Self::IndonesianBankTransfer
}
},
PaymentMethodData::Crypto(_) => Self::Crypto,
PaymentMethodData::MandatePayment => Self::MandatePayment,
PaymentMethodData::Reward => Self::Reward,
PaymentMethodData::Upi(_) => Self::Upi,
PaymentMethodData::Voucher(voucher_data) => match voucher_data {
payment_method_data::VoucherData::Boleto(_) => Self::Boleto,
payment_method_data::VoucherData::Efecty => Self::Efecty,
payment_method_data::VoucherData::PagoEfectivo => Self::PagoEfectivo,
payment_method_data::VoucherData::RedCompra => Self::RedCompra,
payment_method_data::VoucherData::RedPagos => Self::RedPagos,
payment_method_data::VoucherData::Alfamart(_) => Self::Alfamart,
payment_method_data::VoucherData::Indomaret(_) => Self::Indomaret,
payment_method_data::VoucherData::Oxxo => Self::Oxxo,
payment_method_data::VoucherData::SevenEleven(_) => Self::SevenEleven,
payment_method_data::VoucherData::Lawson(_) => Self::Lawson,
payment_method_data::VoucherData::MiniStop(_) => Self::MiniStop,
payment_method_data::VoucherData::FamilyMart(_) => Self::FamilyMart,
payment_method_data::VoucherData::Seicomart(_) => Self::Seicomart,
payment_method_data::VoucherData::PayEasy(_) => Self::PayEasy,
},
PaymentMethodData::RealTimePayment(real_time_payment_data) => {
match *real_time_payment_data {
payment_method_data::RealTimePaymentData::DuitNow {} => Self::DuitNow,
payment_method_data::RealTimePaymentData::Fps {} => Self::Fps,
payment_method_data::RealTimePaymentData::PromptPay {} => Self::PromptPay,
payment_method_data::RealTimePaymentData::VietQr {} => Self::VietQr,
}
}
PaymentMethodData::GiftCard(gift_card_data) => match *gift_card_data {
payment_method_data::GiftCardData::Givex(_) => Self::Givex,
payment_method_data::GiftCardData::PaySafeCard {} => Self::PaySafeCar,
payment_method_data::GiftCardData::BhnCardNetwork(_) => Self::BhnCardNetwork,
},
PaymentMethodData::CardToken(_) => Self::CardToken,
PaymentMethodData::OpenBanking(data) => match data {
payment_method_data::OpenBankingData::OpenBankingPIS {} => Self::OpenBanking,
},
PaymentMethodData::MobilePayment(mobile_payment_data) => match mobile_payment_data {
payment_method_data::MobilePaymentData::DirectCarrierBilling { .. } => {
Self::DirectCarrierBilling
}
},
}
}
}
pub trait GooglePay {
fn get_googlepay_encrypted_payment_data(&self) -> Result<Secret<String>, Error>;
}
impl GooglePay for payment_method_data::GooglePayWalletData {
fn get_googlepay_encrypted_payment_data(&self) -> Result<Secret<String>, Error> {
let encrypted_data = self
.tokenization_data
.get_encrypted_google_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Google Pay".to_string(),
})?;
Ok(Secret::new(encrypted_data.token.clone()))
}
}
pub trait ApplePay {
fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error>;
}
impl ApplePay for payment_method_data::ApplePayWalletData {
fn get_applepay_decoded_payment_data(&self) -> Result<Secret<String>, Error> {
let apple_pay_encrypted_data = self
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
let token = Secret::new(
String::from_utf8(
BASE64_ENGINE
.decode(apple_pay_encrypted_data)
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?,
)
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?,
);
Ok(token)
}
}
pub trait WalletData {
fn get_wallet_token(&self) -> Result<Secret<String>, Error>;
fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error>
where
T: serde::de::DeserializeOwned;
fn get_encoded_wallet_token(&self) -> Result<String, Error>;
}
impl WalletData for payment_method_data::WalletData {
fn get_wallet_token(&self) -> Result<Secret<String>, Error> {
match self {
Self::GooglePay(data) => Ok(data.get_googlepay_encrypted_payment_data()?),
Self::ApplePay(data) => Ok(data.get_applepay_decoded_payment_data()?),
Self::PaypalSdk(data) => Ok(Secret::new(data.token.clone())),
_ => Err(errors::ConnectorError::InvalidWallet.into()),
}
}
fn get_wallet_token_as_json<T>(&self, wallet_name: String) -> Result<T, Error>
where
T: serde::de::DeserializeOwned,
{
serde_json::from_str::<T>(self.get_wallet_token()?.peek())
.change_context(errors::ConnectorError::InvalidWalletToken { wallet_name })
}
fn get_encoded_wallet_token(&self) -> Result<String, Error> {
match self {
Self::GooglePay(_) => {
let json_token: Value = self.get_wallet_token_as_json("Google Pay".to_owned())?;
let token_as_vec = serde_json::to_vec(&json_token).change_context(
errors::ConnectorError::InvalidWalletToken {
wallet_name: "Google Pay".to_string(),
},
)?;
let encoded_token = BASE64_ENGINE.encode(token_as_vec);
Ok(encoded_token)
}
_ => Err(
errors::ConnectorError::NotImplemented("SELECTED PAYMENT METHOD".to_owned()).into(),
),
}
}
}
pub fn deserialize_xml_to_struct<T: serde::de::DeserializeOwned>(
xml_data: &[u8],
) -> Result<T, errors::ConnectorError> {
let response_str = std::str::from_utf8(xml_data)
.map_err(|e| {
router_env::logger::error!("Error converting response data to UTF-8: {:?}", e);
errors::ConnectorError::ResponseDeserializationFailed
})?
.trim();
let result: T = quick_xml::de::from_str(response_str).map_err(|e| {
router_env::logger::error!("Error deserializing XML response: {:?}", e);
errors::ConnectorError::ResponseDeserializationFailed
})?;
Ok(result)
}
pub fn is_html_response(response: &str) -> bool {
response.starts_with("<html>") || response.starts_with("<!DOCTYPE html>")
}
#[cfg(feature = "payouts")]
pub trait PayoutsData {
fn get_transfer_id(&self) -> Result<String, Error>;
fn get_customer_details(
&self,
) -> Result<hyperswitch_domain_models::router_request_types::CustomerDetails, Error>;
fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error>;
fn get_payout_type(&self) -> Result<enums::PayoutType, Error>;
fn get_webhook_url(&self) -> Result<String, Error>;
fn get_browser_info(&self) -> Result<BrowserInformation, Error>;
}
#[cfg(feature = "payouts")]
impl PayoutsData for hyperswitch_domain_models::router_request_types::PayoutsData {
fn get_transfer_id(&self) -> Result<String, Error> {
self.connector_payout_id
.clone()
.ok_or_else(missing_field_err("transfer_id"))
}
fn get_customer_details(
&self,
) -> Result<hyperswitch_domain_models::router_request_types::CustomerDetails, Error> {
self.customer_details
.clone()
.ok_or_else(missing_field_err("customer_details"))
}
fn get_vendor_details(&self) -> Result<PayoutVendorAccountDetails, Error> {
self.vendor_details
.clone()
.ok_or_else(missing_field_err("vendor_details"))
}
fn get_payout_type(&self) -> Result<enums::PayoutType, Error> {
self.payout_type
.to_owned()
.ok_or_else(missing_field_err("payout_type"))
}
fn get_webhook_url(&self) -> Result<String, Error> {
self.webhook_url
.to_owned()
.ok_or_else(missing_field_err("webhook_url"))
}
fn get_browser_info(&self) -> Result<BrowserInformation, Error> {
self.browser_info
.clone()
.ok_or_else(missing_field_err("browser_info"))
}
}
pub trait RevokeMandateRequestData {
fn get_connector_mandate_id(&self) -> Result<String, Error>;
}
impl RevokeMandateRequestData for MandateRevokeRequestData {
fn get_connector_mandate_id(&self) -> Result<String, Error> {
self.connector_mandate_id
.clone()
.ok_or_else(missing_field_err("connector_mandate_id"))
}
}
pub trait RecurringMandateData {
fn get_original_payment_amount(&self) -> Result<i64, Error>;
fn get_original_payment_currency(&self) -> Result<enums::Currency, Error>;
}
impl RecurringMandateData for RecurringMandatePaymentData {
fn get_original_payment_amount(&self) -> Result<i64, Error> {
self.original_payment_authorized_amount
.ok_or_else(missing_field_err("original_payment_authorized_amount"))
}
fn get_original_payment_currency(&self) -> Result<enums::Currency, Error> {
self.original_payment_authorized_currency
.ok_or_else(missing_field_err("original_payment_authorized_currency"))
}
}
#[cfg(feature = "payouts")]
impl CardData for api_models::payouts::CardPayout {
fn get_card_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.expiry_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
fn get_card_expiry_month_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let exp_month = self
.expiry_month
.peek()
.to_string()
.parse::<u8>()
.map_err(|_| errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
})?;
let month = ::cards::CardExpirationMonth::try_from(exp_month).map_err(|_| {
errors::ConnectorError::InvalidDataFormat {
field_name: "payment_method_data.card.card_exp_month",
}
})?;
Ok(Secret::new(month.two_digits()))
}
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.card_number.peek())
}
fn get_card_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.expiry_month.peek(),
delimiter,
year.peek()
)))
}
fn get_expiry_date_as_yyyymm(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
year.peek(),
delimiter,
self.expiry_month.peek()
))
}
fn get_expiry_date_as_mmyyyy(&self, delimiter: &str) -> Secret<String> {
let year = self.get_expiry_year_4_digit();
Secret::new(format!(
"{}{}{}",
self.expiry_month.peek(),
delimiter,
year.peek()
))
}
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.expiry_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
fn get_expiry_date_as_yymm(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.expiry_month.clone().expose();
Ok(Secret::new(format!("{year}{month}")))
}
fn get_expiry_month_as_i8(&self) -> Result<Secret<i8>, Error> {
self.expiry_month
.peek()
.clone()
.parse::<i8>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_year_as_i32(&self) -> Result<Secret<i32>, Error> {
self.expiry_year
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_expiry_date_as_mmyy(&self) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_card_expiry_year_2_digit()?.expose();
let month = self.expiry_month.clone().expose();
Ok(Secret::new(format!("{month}{year}")))
}
fn get_expiry_year_as_4_digit_i32(&self) -> Result<Secret<i32>, Error> {
self.get_expiry_year_4_digit()
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.map(Secret::new)
}
fn get_cardholder_name(&self) -> Result<Secret<String>, Error> {
self.card_holder_name
.clone()
.ok_or_else(missing_field_err("card.card_holder_name"))
}
}
pub trait NetworkTokenData {
fn get_card_issuer(&self) -> Result<CardIssuer, Error>;
fn get_expiry_year_4_digit(&self) -> Secret<String>;
fn get_network_token(&self) -> NetworkTokenNumber;
fn get_network_token_expiry_month(&self) -> Secret<String>;
fn get_network_token_expiry_year(&self) -> Secret<String>;
fn get_cryptogram(&self) -> Option<Secret<String>>;
fn get_token_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError>;
fn get_token_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError>;
}
impl NetworkTokenData for payment_method_data::NetworkTokenData {
#[cfg(feature = "v1")]
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.token_number.peek())
}
#[cfg(feature = "v2")]
fn get_card_issuer(&self) -> Result<CardIssuer, Error> {
get_card_issuer(self.network_token.peek())
}
#[cfg(feature = "v1")]
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.token_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
#[cfg(feature = "v2")]
fn get_expiry_year_4_digit(&self) -> Secret<String> {
let mut year = self.network_token_exp_year.peek().clone();
if year.len() == 2 {
year = format!("20{year}");
}
Secret::new(year)
}
#[cfg(feature = "v1")]
fn get_network_token(&self) -> NetworkTokenNumber {
self.token_number.clone()
}
#[cfg(feature = "v2")]
fn get_network_token(&self) -> NetworkTokenNumber {
self.network_token.clone()
}
#[cfg(feature = "v1")]
fn get_network_token_expiry_month(&self) -> Secret<String> {
self.token_exp_month.clone()
}
#[cfg(feature = "v2")]
fn get_network_token_expiry_month(&self) -> Secret<String> {
self.network_token_exp_month.clone()
}
#[cfg(feature = "v1")]
fn get_network_token_expiry_year(&self) -> Secret<String> {
self.token_exp_year.clone()
}
#[cfg(feature = "v2")]
fn get_network_token_expiry_year(&self) -> Secret<String> {
self.network_token_exp_year.clone()
}
#[cfg(feature = "v1")]
fn get_cryptogram(&self) -> Option<Secret<String>> {
self.token_cryptogram.clone()
}
#[cfg(feature = "v2")]
fn get_cryptogram(&self) -> Option<Secret<String>> {
self.cryptogram.clone()
}
#[cfg(feature = "v1")]
fn get_token_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.token_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
#[cfg(feature = "v2")]
fn get_token_expiry_year_2_digit(&self) -> Result<Secret<String>, errors::ConnectorError> {
let binding = self.network_token_exp_year.clone();
let year = binding.peek();
Ok(Secret::new(
year.get(year.len() - 2..)
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string(),
))
}
#[cfg(feature = "v1")]
fn get_token_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_token_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.token_exp_month.peek(),
delimiter,
year.peek()
)))
}
#[cfg(feature = "v2")]
fn get_token_expiry_month_year_2_digit_with_delimiter(
&self,
delimiter: String,
) -> Result<Secret<String>, errors::ConnectorError> {
let year = self.get_token_expiry_year_2_digit()?;
Ok(Secret::new(format!(
"{}{}{}",
self.network_token_exp_month.peek(),
delimiter,
year.peek()
)))
}
}
pub fn convert_uppercase<'de, D, T>(v: D) -> Result<T, D::Error>
where
D: serde::Deserializer<'de>,
T: FromStr,
<T as FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error,
{
use serde::de::Error;
let output = <&str>::deserialize(v)?;
output.to_uppercase().parse::<T>().map_err(D::Error::custom)
}
pub(crate) fn convert_setup_mandate_router_data_to_authorize_router_data(
data: &SetupMandateRouterData,
) -> PaymentsAuthorizeData {
PaymentsAuthorizeData {
currency: data.request.currency,
payment_method_data: data.request.payment_method_data.clone(),
confirm: data.request.confirm,
statement_descriptor_suffix: data.request.statement_descriptor_suffix.clone(),
mandate_id: data.request.mandate_id.clone(),
setup_future_usage: data.request.setup_future_usage,
off_session: data.request.off_session,
setup_mandate_details: data.request.setup_mandate_details.clone(),
router_return_url: data.request.router_return_url.clone(),
email: data.request.email.clone(),
customer_name: data.request.customer_name.clone(),
amount: 0,
order_tax_amount: Some(MinorUnit::zero()),
minor_amount: MinorUnit::new(0),
statement_descriptor: None,
capture_method: data.request.capture_method,
webhook_url: None,
complete_authorize_url: None,
browser_info: data.request.browser_info.clone(),
order_details: None,
order_category: None,
session_token: None,
enrolled_for_3ds: true,
related_transaction_id: None,
payment_experience: None,
payment_method_type: None,
customer_id: None,
surcharge_details: None,
request_extended_authorization: None,
request_incremental_authorization: data.request.request_incremental_authorization,
metadata: None,
authentication_data: None,
customer_acceptance: data.request.customer_acceptance.clone(),
split_payments: None, // TODO: allow charges on mandates?
merchant_order_reference_id: None,
integrity_object: None,
additional_payment_method_data: None,
shipping_cost: data.request.shipping_cost,
merchant_account_id: None,
merchant_config_currency: None,
connector_testing_data: data.request.connector_testing_data.clone(),
order_id: None,
locale: None,
payment_channel: data.request.payment_channel.clone(),
enable_partial_authorization: data.request.enable_partial_authorization,
enable_overcapture: None,
is_stored_credential: data.request.is_stored_credential,
mit_category: None,
}
}
pub(crate) fn convert_payment_authorize_router_response<F1, F2, T1, T2>(
item: (&ConnectorRouterData<F1, T1, PaymentsResponseData>, T2),
) -> ConnectorRouterData<F2, T2, PaymentsResponseData> {
let data = item.0;
let request = item.1;
ConnectorRouterData {
flow: PhantomData,
request,
merchant_id: data.merchant_id.clone(),
connector: data.connector.clone(),
attempt_id: data.attempt_id.clone(),
tenant_id: data.tenant_id.clone(),
status: data.status,
payment_method: data.payment_method,
payment_method_type: data.payment_method_type,
connector_auth_type: data.connector_auth_type.clone(),
description: data.description.clone(),
address: data.address.clone(),
auth_type: data.auth_type,
connector_meta_data: data.connector_meta_data.clone(),
connector_wallets_details: data.connector_wallets_details.clone(),
amount_captured: data.amount_captured,
minor_amount_captured: data.minor_amount_captured,
access_token: data.access_token.clone(),
response: data.response.clone(),
payment_id: data.payment_id.clone(),
session_token: data.session_token.clone(),
reference_id: data.reference_id.clone(),
customer_id: data.customer_id.clone(),
payment_method_token: None,
preprocessing_id: None,
connector_customer: data.connector_customer.clone(),
recurring_mandate_payment_data: data.recurring_mandate_payment_data.clone(),
connector_request_reference_id: data.connector_request_reference_id.clone(),
#[cfg(feature = "payouts")]
payout_method_data: data.payout_method_data.clone(),
#[cfg(feature = "payouts")]
quote_id: data.quote_id.clone(),
test_mode: data.test_mode,
payment_method_status: None,
payment_method_balance: data.payment_method_balance.clone(),
connector_api_version: data.connector_api_version.clone(),
connector_http_status_code: data.connector_http_status_code,
external_latency: data.external_latency,
apple_pay_flow: data.apple_pay_flow.clone(),
frm_metadata: data.frm_metadata.clone(),
dispute_id: data.dispute_id.clone(),
refund_id: data.refund_id.clone(),
connector_response: data.connector_response.clone(),
integrity_check: Ok(()),
additional_merchant_data: data.additional_merchant_data.clone(),
header_payload: data.header_payload.clone(),
connector_mandate_request_reference_id: data.connector_mandate_request_reference_id.clone(),
authentication_id: data.authentication_id.clone(),
psd2_sca_exemption_type: data.psd2_sca_exemption_type,
raw_connector_response: data.raw_connector_response.clone(),
is_payment_id_from_merchant: data.is_payment_id_from_merchant,
l2_l3_data: data.l2_l3_data.clone(),
minor_amount_capturable: data.minor_amount_capturable,
authorized_amount: data.authorized_amount,
}
}
pub fn generate_12_digit_number() -> u64 {
let mut rng = rand::thread_rng();
rng.gen_range(100_000_000_000..=999_999_999_999)
}
/// Normalizes a string by converting to lowercase, performing NFKD normalization(https://unicode.org/reports/tr15/#Description_Norm),and removing special characters and spaces.
pub fn normalize_string(value: String) -> Result<String, regex::Error> {
let nfkd_value = value.nfkd().collect::<String>();
let lowercase_value = nfkd_value.to_lowercase();
static REGEX: LazyLock<Result<Regex, regex::Error>> =
LazyLock::new(|| Regex::new(r"[^a-z0-9]"));
let regex = REGEX.as_ref().map_err(|e| e.clone())?;
let normalized = regex.replace_all(&lowercase_value, "").to_string();
Ok(normalized)
}
fn normalize_state(value: String) -> Result<String, error_stack::Report<errors::ConnectorError>> {
normalize_string(value).map_err(|_e| {
error_stack::Report::new(errors::ConnectorError::InvalidDataFormat {
field_name: "address.state",
})
})
}
pub fn parse_state_enum<T>(
value: String,
enum_name: &'static str,
field_name: &'static str,
) -> Result<String, error_stack::Report<errors::ConnectorError>>
where
T: FromStr,
<T as FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
match StringExt::<T>::parse_enum(value.clone(), enum_name) {
Ok(_) => Ok(value),
Err(_) => normalize_state(value).map_err(|_e| {
error_stack::Report::new(errors::ConnectorError::InvalidDataFormat { field_name })
}),
}
}
#[cfg(feature = "frm")]
pub trait FrmTransactionRouterDataRequest {
fn is_payment_successful(&self) -> Option<bool>;
}
#[cfg(feature = "frm")]
impl FrmTransactionRouterDataRequest for FrmTransactionRouterData {
fn is_payment_successful(&self) -> Option<bool> {
match self.status {
AttemptStatus::AuthenticationFailed
| AttemptStatus::RouterDeclined
| AttemptStatus::AuthorizationFailed
| AttemptStatus::Voided
| AttemptStatus::VoidedPostCharge
| AttemptStatus::CaptureFailed
| AttemptStatus::Failure
| AttemptStatus::AutoRefunded
| AttemptStatus::Expired => Some(false),
AttemptStatus::AuthenticationSuccessful
| AttemptStatus::PartialChargedAndChargeable
| AttemptStatus::Authorized
| AttemptStatus::Charged
| AttemptStatus::IntegrityFailure
| AttemptStatus::PartiallyAuthorized => Some(true),
AttemptStatus::Started
| AttemptStatus::AuthenticationPending
| AttemptStatus::Authorizing
| AttemptStatus::CodInitiated
| AttemptStatus::VoidInitiated
| AttemptStatus::CaptureInitiated
| AttemptStatus::VoidFailed
| AttemptStatus::PartialCharged
| AttemptStatus::Unresolved
| AttemptStatus::Pending
| AttemptStatus::PaymentMethodAwaited
| AttemptStatus::ConfirmationAwaited
| AttemptStatus::DeviceDataCollectionPending => None,
}
}
}
#[cfg(feature = "frm")]
pub trait FraudCheckCheckoutRequest {
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>;
}
#[cfg(feature = "frm")]
impl FraudCheckCheckoutRequest for FraudCheckCheckoutData {
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> {
self.order_details
.clone()
.ok_or_else(missing_field_err("order_details"))
}
}
#[cfg(feature = "frm")]
pub trait FraudCheckTransactionRequest {
fn get_currency(&self) -> Result<enums::Currency, Error>;
}
#[cfg(feature = "frm")]
impl FraudCheckTransactionRequest for FraudCheckTransactionData {
fn get_currency(&self) -> Result<enums::Currency, Error> {
self.currency.ok_or_else(missing_field_err("currency"))
}
}
/// Custom deserializer for Option<Currency> that treats empty strings as None
pub fn deserialize_optional_currency<'de, D>(
deserializer: D,
) -> Result<Option<enums::Currency>, D::Error>
where
D: serde::Deserializer<'de>,
{
let string_data: Option<String> = Option::deserialize(deserializer)?;
match string_data {
Some(ref value) if !value.is_empty() => value
.clone()
.parse_enum("Currency")
.map(Some)
.map_err(|_| serde::de::Error::custom(format!("Invalid currency code: {value}"))),
_ => Ok(None),
}
}
#[cfg(feature = "payouts")]
pub trait CustomerDetails {
fn get_customer_id(&self) -> Result<id_type::CustomerId, errors::ConnectorError>;
fn get_customer_name(
&self,
) -> Result<Secret<String, masking::WithType>, errors::ConnectorError>;
fn get_customer_email(&self) -> Result<Email, errors::ConnectorError>;
fn get_customer_phone(
&self,
) -> Result<Secret<String, masking::WithType>, errors::ConnectorError>;
fn get_customer_phone_country_code(&self) -> Result<String, errors::ConnectorError>;
}
#[cfg(feature = "payouts")]
impl CustomerDetails for hyperswitch_domain_models::router_request_types::CustomerDetails {
fn get_customer_id(&self) -> Result<id_type::CustomerId, errors::ConnectorError> {
self.customer_id
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "customer_id",
})
}
fn get_customer_name(
&self,
) -> Result<Secret<String, masking::WithType>, errors::ConnectorError> {
self.name
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "customer_name",
})
}
fn get_customer_email(&self) -> Result<Email, errors::ConnectorError> {
self.email
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "customer_email",
})
}
fn get_customer_phone(
&self,
) -> Result<Secret<String, masking::WithType>, errors::ConnectorError> {
self.phone
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "customer_phone",
})
}
fn get_customer_phone_country_code(&self) -> Result<String, errors::ConnectorError> {
self.phone_country_code
.clone()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "customer_phone_country_code",
})
}
}
pub fn get_card_details(
payment_method_data: PaymentMethodData,
connector_name: &'static str,
) -> Result<Card, errors::ConnectorError> {
match payment_method_data {
PaymentMethodData::Card(details) => Ok(details),
_ => Err(errors::ConnectorError::NotSupported {
message: SELECTED_PAYMENT_METHOD.to_string(),
connector: connector_name,
})?,
}
}
pub fn get_authorise_integrity_object<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
amount: T,
currency: String,
) -> Result<AuthoriseIntegrityObject, error_stack::Report<errors::ConnectorError>> {
let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let amount_in_minor_unit =
convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?;
Ok(AuthoriseIntegrityObject {
amount: amount_in_minor_unit,
currency: currency_enum,
})
}
pub fn get_sync_integrity_object<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
amount: T,
currency: String,
) -> Result<SyncIntegrityObject, error_stack::Report<errors::ConnectorError>> {
let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let amount_in_minor_unit =
convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum)?;
Ok(SyncIntegrityObject {
amount: Some(amount_in_minor_unit),
currency: Some(currency_enum),
})
}
pub fn get_capture_integrity_object<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
capture_amount: Option<T>,
currency: String,
) -> Result<CaptureIntegrityObject, error_stack::Report<errors::ConnectorError>> {
let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let capture_amount_in_minor_unit = capture_amount
.map(|amount| convert_back_amount_to_minor_units(amount_convertor, amount, currency_enum))
.transpose()?;
Ok(CaptureIntegrityObject {
capture_amount: capture_amount_in_minor_unit,
currency: currency_enum,
})
}
pub fn get_refund_integrity_object<T>(
amount_convertor: &dyn AmountConvertor<Output = T>,
refund_amount: T,
currency: String,
) -> Result<RefundIntegrityObject, error_stack::Report<errors::ConnectorError>> {
let currency_enum = enums::Currency::from_str(currency.to_uppercase().as_str())
.change_context(errors::ConnectorError::ParsingFailed)?;
let refund_amount_in_minor_unit =
convert_back_amount_to_minor_units(amount_convertor, refund_amount, currency_enum)?;
Ok(RefundIntegrityObject {
currency: currency_enum,
refund_amount: refund_amount_in_minor_unit,
})
}
#[cfg(feature = "frm")]
pub trait FraudCheckSaleRequest {
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error>;
}
#[cfg(feature = "frm")]
impl FraudCheckSaleRequest for FraudCheckSaleData {
fn get_order_details(&self) -> Result<Vec<OrderDetailsWithAmount>, Error> {
self.order_details
.clone()
.ok_or_else(missing_field_err("order_details"))
}
}
#[cfg(feature = "frm")]
pub trait FraudCheckRecordReturnRequest {
fn get_currency(&self) -> Result<enums::Currency, Error>;
}
#[cfg(feature = "frm")]
impl FraudCheckRecordReturnRequest for FraudCheckRecordReturnData {
fn get_currency(&self) -> Result<enums::Currency, Error> {
self.currency.ok_or_else(missing_field_err("currency"))
}
}
pub trait SplitPaymentData {
fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest>;
}
impl SplitPaymentData for PaymentsCaptureData {
fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> {
None
}
}
impl SplitPaymentData for PaymentsAuthorizeData {
fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> {
self.split_payments.clone()
}
}
impl SplitPaymentData for PaymentsSyncData {
fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> {
self.split_payments.clone()
}
}
impl SplitPaymentData for PaymentsCancelData {
fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> {
None
}
}
impl SplitPaymentData for SetupMandateRequestData {
fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> {
None
}
}
impl SplitPaymentData for ExternalVaultProxyPaymentsData {
fn get_split_payment_data(&self) -> Option<common_types::payments::SplitPaymentsRequest> {
None
}
}
pub struct XmlSerializer;
impl XmlSerializer {
pub fn serialize_to_xml_bytes<T: Serialize>(
item: &T,
xml_version: &str,
xml_encoding: Option<&str>,
xml_standalone: Option<&str>,
xml_doc_type: Option<&str>,
) -> Result<Vec<u8>, error_stack::Report<errors::ConnectorError>> {
let mut xml_bytes = Vec::new();
let mut writer = Writer::new(std::io::Cursor::new(&mut xml_bytes));
writer
.write_event(Event::Decl(BytesDecl::new(
xml_version,
xml_encoding,
xml_standalone,
)))
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to write XML declaration")?;
if let Some(xml_doc_type_data) = xml_doc_type {
writer
.write_event(Event::DocType(BytesText::from_escaped(xml_doc_type_data)))
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to write the XML declaration")?;
};
let xml_body = quick_xml::se::to_string(&item)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to serialize the XML body")?;
writer
.write_event(Event::Text(BytesText::from_escaped(xml_body)))
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to serialize the XML body")?;
Ok(xml_bytes)
}
}
pub fn deserialize_zero_minor_amount_as_none<'de, D>(
deserializer: D,
) -> Result<Option<MinorUnit>, D::Error>
where
D: serde::de::Deserializer<'de>,
{
let amount = Option::<MinorUnit>::deserialize(deserializer)?;
match amount {
Some(value) if value.get_amount_as_i64() == 0 => Ok(None),
_ => Ok(amount),
}
}
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/utils.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 1,
"num_structs": 3,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_connectors_5011405661612342005
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_connectors
// File: crates/hyperswitch_connectors/src/connectors/nexinets.rs
// Contains: 1 structs, 0 enums
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
errors::api_error_response::ApiErrorResponse,
payment_method_data::PaymentMethodData,
payments::payment_attempt::PaymentAttempt,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorTransactionId, ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType,
RefundExecuteType, RefundSyncType, Response,
},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::Mask;
#[cfg(feature = "v2")]
use masking::PeekInterface;
use transformers as nexinets;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{
is_mandate_supported, to_connector_meta, PaymentMethodDataType, PaymentsSyncRequestData,
},
};
#[derive(Debug, Clone)]
pub struct Nexinets;
impl api::Payment for Nexinets {}
impl api::PaymentSession for Nexinets {}
impl api::ConnectorAccessToken for Nexinets {}
impl api::MandateSetup for Nexinets {}
impl api::PaymentAuthorize for Nexinets {}
impl api::PaymentSync for Nexinets {}
impl api::PaymentCapture for Nexinets {}
impl api::PaymentVoid for Nexinets {}
impl api::Refund for Nexinets {}
impl api::RefundExecute for Nexinets {}
impl api::RefundSync for Nexinets {}
impl Nexinets {
pub fn connector_transaction_id(
&self,
connector_meta: Option<&serde_json::Value>,
) -> CustomResult<Option<String>, errors::ConnectorError> {
let meta: nexinets::NexinetsPaymentsMetadata = to_connector_meta(connector_meta.cloned())?;
Ok(meta.transaction_id)
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nexinets
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Nexinets {
fn id(&self) -> &'static str {
"nexinets"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.nexinets.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = nexinets::NexinetsAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: nexinets::NexinetsErrorResponse = res
.response
.parse_struct("NexinetsErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let errors = response.errors;
let mut message = String::new();
let mut static_message = String::new();
for error in errors.iter() {
let field = error.field.to_owned().unwrap_or_default();
let mut msg = String::new();
if !field.is_empty() {
msg.push_str(format!("{} : {}", field, error.message).as_str());
} else {
error.message.clone_into(&mut msg)
}
if message.is_empty() {
message.push_str(&msg);
static_message.push_str(&msg);
} else {
message.push_str(format!(", {msg}").as_str());
}
}
let connector_reason = format!("reason : {} , message : {}", response.message, message);
Ok(ErrorResponse {
status_code: response.status,
code: response.code.to_string(),
message: static_message,
reason: Some(connector_reason),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Nexinets {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::PaypalRedirect,
PaymentMethodDataType::ApplePay,
PaymentMethodDataType::Eps,
PaymentMethodDataType::Giropay,
PaymentMethodDataType::Ideal,
]);
is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nexinets {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nexinets {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Nexinets
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Nexinets".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nexinets {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let url = if matches!(
req.request.capture_method,
Some(enums::CaptureMethod::Automatic) | Some(enums::CaptureMethod::SequentialAutomatic)
) {
format!("{}/orders/debit", self.base_url(connectors))
} else {
format!("{}/orders/preauth", self.base_url(connectors))
};
Ok(url)
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nexinets::NexinetsPaymentsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: nexinets::NexinetsPreAuthOrDebitResponse = res
.response
.parse_struct("Nexinets PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nexinets {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let meta: nexinets::NexinetsPaymentsMetadata =
to_connector_meta(req.request.connector_meta.clone())?;
let order_id = nexinets::get_order_id(&meta)?;
let transaction_id = match meta.psync_flow {
transformers::NexinetsTransactionType::Debit
| transformers::NexinetsTransactionType::Capture => {
req.request.get_connector_transaction_id()?
}
_ => nexinets::get_transaction_id(&meta)?,
};
Ok(format!(
"{}/orders/{order_id}/transactions/{transaction_id}",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: nexinets::NexinetsPaymentResponse = res
.response
.parse_struct("nexinets NexinetsPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nexinets {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let meta: nexinets::NexinetsPaymentsMetadata =
to_connector_meta(req.request.connector_meta.clone())?;
let order_id = nexinets::get_order_id(&meta)?;
let transaction_id = nexinets::get_transaction_id(&meta)?;
Ok(format!(
"{}/orders/{order_id}/transactions/{transaction_id}/capture",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nexinets::NexinetsCaptureOrVoidRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: nexinets::NexinetsPaymentResponse = res
.response
.parse_struct("NexinetsPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nexinets {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let meta: nexinets::NexinetsPaymentsMetadata =
to_connector_meta(req.request.connector_meta.clone())?;
let order_id = nexinets::get_order_id(&meta)?;
let transaction_id = nexinets::get_transaction_id(&meta)?;
Ok(format!(
"{}/orders/{order_id}/transactions/{transaction_id}/cancel",
self.base_url(connectors),
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nexinets::NexinetsCaptureOrVoidRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: nexinets::NexinetsPaymentResponse = res
.response
.parse_struct("NexinetsPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nexinets {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let meta: nexinets::NexinetsPaymentsMetadata =
to_connector_meta(req.request.connector_metadata.clone())?;
let order_id = nexinets::get_order_id(&meta)?;
Ok(format!(
"{}/orders/{order_id}/transactions/{}/refund",
self.base_url(connectors),
req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nexinets::NexinetsRefundRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: nexinets::NexinetsRefundResponse = res
.response
.parse_struct("nexinets RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nexinets {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let transaction_id = req
.request
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
let meta: nexinets::NexinetsPaymentsMetadata =
to_connector_meta(req.request.connector_metadata.clone())?;
let order_id = nexinets::get_order_id(&meta)?;
Ok(format!(
"{}/orders/{order_id}/transactions/{transaction_id}",
self.base_url(connectors)
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: nexinets::NexinetsRefundResponse = res
.response
.parse_struct("nexinets RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Nexinets {
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
Ok(IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
impl api::PaymentToken for Nexinets {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Nexinets
{
// Not Implemented (R)
}
static NEXINETS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::UnionPay,
];
let mut nexinets_supported_payment_methods = SupportedPaymentMethods::new();
nexinets_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
nexinets_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
nexinets_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Ideal,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
nexinets_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Giropay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
nexinets_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Sofort,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
nexinets_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Eps,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
nexinets_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
nexinets_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Paypal,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
nexinets_supported_payment_methods
});
static NEXINETS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Nexinets",
description: "Nexi and Nets join forces to create The European PayTech leader, a strategic combination to offer future-proof innovative payment solutions.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static NEXINETS_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Nexinets {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&NEXINETS_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*NEXINETS_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&NEXINETS_SUPPORTED_WEBHOOK_FLOWS)
}
}
impl ConnectorTransactionId for Nexinets {
#[cfg(feature = "v1")]
fn connector_transaction_id(
&self,
payment_attempt: &PaymentAttempt,
) -> Result<Option<String>, ApiErrorResponse> {
let metadata =
Self::connector_transaction_id(self, payment_attempt.connector_metadata.as_ref());
metadata.map_err(|_| ApiErrorResponse::ResourceIdNotFound)
}
#[cfg(feature = "v2")]
fn connector_transaction_id(
&self,
payment_attempt: &PaymentAttempt,
) -> Result<Option<String>, ApiErrorResponse> {
use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse;
let metadata = Self::connector_transaction_id(
self,
payment_attempt
.connector_metadata
.as_ref()
.map(|connector_metadata| connector_metadata.peek()),
);
metadata.map_err(|_| ApiErrorResponse::ResourceIdNotFound)
}
}
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/nexinets.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_connectors_-2271275406759165733
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_connectors
// File: crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs
// Contains: 1 structs, 0 enums
pub mod transformers;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{
Authorize, Capture, CreateConnectorCustomer, PSync, PaymentMethodToken, Session,
SetupMandate, Void,
},
refunds::{Execute, RSync},
vault::ExternalVaultCreateFlow,
},
router_request_types::{
AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData, VaultRequestData,
},
router_response_types::{PaymentsResponseData, RefundsResponseData, VaultResponseData},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsSessionRouterData, PaymentsSyncRouterData,
RefreshTokenRouterData, RefundsRouterData, SetupMandateRouterData, TokenizationRouterData,
VaultRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask};
use transformers as hyperswitch_vault;
use crate::{constants::headers, types::ResponseRouterData};
#[derive(Clone)]
pub struct HyperswitchVault;
impl api::Payment for HyperswitchVault {}
impl api::PaymentSession for HyperswitchVault {}
impl api::ConnectorAccessToken for HyperswitchVault {}
impl api::MandateSetup for HyperswitchVault {}
impl api::PaymentAuthorize for HyperswitchVault {}
impl api::PaymentSync for HyperswitchVault {}
impl api::PaymentCapture for HyperswitchVault {}
impl api::PaymentVoid for HyperswitchVault {}
impl api::Refund for HyperswitchVault {}
impl api::RefundExecute for HyperswitchVault {}
impl api::RefundSync for HyperswitchVault {}
impl api::PaymentToken for HyperswitchVault {}
impl api::ExternalVaultCreate for HyperswitchVault {}
impl api::ConnectorCustomer for HyperswitchVault {}
impl ConnectorIntegration<ExternalVaultCreateFlow, VaultRequestData, VaultResponseData>
for HyperswitchVault
{
fn get_headers(
&self,
req: &VaultRouterData<ExternalVaultCreateFlow>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &VaultRouterData<ExternalVaultCreateFlow>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/v2/payment-method-sessions",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &VaultRouterData<ExternalVaultCreateFlow>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = hyperswitch_vault::HyperswitchVaultCreateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &VaultRouterData<ExternalVaultCreateFlow>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::ExternalVaultCreateType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::ExternalVaultCreateType::get_headers(
self, req, connectors,
)?)
.set_body(types::ExternalVaultCreateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &VaultRouterData<ExternalVaultCreateFlow>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<VaultRouterData<ExternalVaultCreateFlow>, errors::ConnectorError> {
let response: hyperswitch_vault::HyperswitchVaultCreateResponse = res
.response
.parse_struct("HyperswitchVault HyperswitchVaultCreateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for HyperswitchVault
{
fn build_request(
&self,
_req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "PaymentMethodTokenization".to_string(),
connector: self.id().to_string(),
}
.into())
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for HyperswitchVault
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = hyperswitch_vault::HyperswitchVaultAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let api_key = auth.api_key.expose();
let header = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
headers::AUTHORIZATION.to_string(),
format!("api-key={api_key}").into_masked(),
),
(
headers::X_PROFILE_ID.to_string(),
auth.profile_id.expose().into_masked(),
),
];
Ok(header)
}
}
impl ConnectorCommon for HyperswitchVault {
fn id(&self) -> &'static str {
"hyperswitch_vault"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.hyperswitch_vault.base_url.as_ref()
}
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: hyperswitch_vault::HyperswitchVaultErrorResponse = res
.response
.parse_struct("HyperswitchVaultErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.code,
message: response.error.error_type,
reason: response.error.message,
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>
for HyperswitchVault
{
fn get_headers(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/v2/customers", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &ConnectorCustomerRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req =
hyperswitch_vault::HyperswitchVaultCustomerCreateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::ConnectorCustomerType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::ConnectorCustomerType::get_headers(
self, req, connectors,
)?)
.set_body(types::ConnectorCustomerType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &ConnectorCustomerRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<ConnectorCustomerRouterData, errors::ConnectorError> {
let response: hyperswitch_vault::HyperswitchVaultCustomerCreateResponse = res
.response
.parse_struct("HyperswitchVault HyperswitchVaultCustomerCreateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorValidation for HyperswitchVault {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for HyperswitchVault {
fn build_request(
&self,
_req: &PaymentsSessionRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "PaymentsSession".to_string(),
connector: self.id().to_string(),
}
.into())
}
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
for HyperswitchVault
{
fn build_request(
&self,
_req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "AccessTokenAuthorize".to_string(),
connector: self.id().to_string(),
}
.into())
}
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for HyperswitchVault
{
fn build_request(
&self,
_req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "SetupMandate".to_string(),
connector: self.id().to_string(),
}
.into())
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for HyperswitchVault
{
fn build_request(
&self,
_req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "PaymentsAuthorize".to_string(),
connector: self.id().to_string(),
}
.into())
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for HyperswitchVault {
fn build_request(
&self,
_req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "PaymentsSync".to_string(),
connector: self.id().to_string(),
}
.into())
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for HyperswitchVault {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "PaymentsCapture".to_string(),
connector: self.id().to_string(),
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for HyperswitchVault {
fn build_request(
&self,
_req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "PaymentsCapture".to_string(),
connector: self.id().to_string(),
}
.into())
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for HyperswitchVault {
fn build_request(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refunds".to_string(),
connector: self.id().to_string(),
}
.into())
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for HyperswitchVault {
fn build_request(
&self,
_req: &RefundsRouterData<RSync>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "RefundsSync".to_string(),
connector: self.id().to_string(),
}
.into())
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for HyperswitchVault {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
impl ConnectorSpecifications for HyperswitchVault {
fn should_call_connector_customer(
&self,
_payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> bool {
true
}
}
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_connectors_4467145319251488264
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_connectors
// File: crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
// Contains: 1 structs, 0 enums
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
mandate_revoke::MandateRevoke,
payments::{
Authorize, Capture, IncrementalAuthorization, PSync, PaymentMethodToken, Session,
SetupMandate, Void,
},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
PaymentsIncrementalAuthorizationData, PaymentsSessionData, PaymentsSyncData, RefundsData,
SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, PaymentsResponseData,
RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsIncrementalAuthorizationRouterData,
PaymentsSyncRouterData, RefundExecuteRouterData, RefundSyncRouterData,
SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self,
refunds::{Refund, RefundExecute, RefundSync},
ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
IncrementalAuthorizationType, MandateRevokeType, PaymentsAuthorizeType,
PaymentsCaptureType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType, RefundSyncType,
Response, SetupMandateType,
},
webhooks,
};
use masking::{ExposeInterface, Mask, Maskable, PeekInterface};
use ring::{digest, hmac};
use time::OffsetDateTime;
use transformers as wellsfargo;
use url::Url;
use crate::{
constants::{self, headers},
types::ResponseRouterData,
utils::{self, convert_amount, PaymentMethodDataType, RefundsRequestData},
};
#[derive(Clone)]
pub struct Wellsfargo {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Wellsfargo {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
pub fn generate_digest(&self, payload: &[u8]) -> String {
let payload_digest = digest::digest(&digest::SHA256, payload);
consts::BASE64_ENGINE.encode(payload_digest)
}
pub fn generate_signature(
&self,
auth: wellsfargo::WellsfargoAuthType,
host: String,
resource: &str,
payload: &String,
date: OffsetDateTime,
http_method: Method,
) -> CustomResult<String, errors::ConnectorError> {
let wellsfargo::WellsfargoAuthType {
api_key,
merchant_account,
api_secret,
} = auth;
let is_post_method = matches!(http_method, Method::Post);
let is_patch_method = matches!(http_method, Method::Patch);
let is_delete_method = matches!(http_method, Method::Delete);
let digest_str = if is_post_method || is_patch_method {
"digest "
} else {
""
};
let headers = format!("host date (request-target) {digest_str}v-c-merchant-id");
let request_target = if is_post_method {
format!("(request-target): post {resource}\ndigest: SHA-256={payload}\n")
} else if is_patch_method {
format!("(request-target): patch {resource}\ndigest: SHA-256={payload}\n")
} else if is_delete_method {
format!("(request-target): delete {resource}\n")
} else {
format!("(request-target): get {resource}\n")
};
let signature_string = format!(
"host: {host}\ndate: {date}\n{request_target}v-c-merchant-id: {}",
merchant_account.peek()
);
let key_value = consts::BASE64_ENGINE
.decode(api_secret.expose())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "connector_account_details.api_secret",
})?;
let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value);
let signature_value =
consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_string.as_bytes()).as_ref());
let signature_header = format!(
r#"keyid="{}", algorithm="HmacSHA256", headers="{headers}", signature="{signature_value}""#,
api_key.peek()
);
Ok(signature_header)
}
}
impl ConnectorCommon for Wellsfargo {
fn id(&self) -> &'static str {
"wellsfargo"
}
fn common_get_content_type(&self) -> &'static str {
"application/json;charset=utf-8"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.wellsfargo.base_url.as_ref()
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<
wellsfargo::WellsfargoErrorResponse,
Report<common_utils::errors::ParsingError>,
> = res.response.parse_struct("Wellsfargo ErrorResponse");
let error_message = if res.status_code == 401 {
constants::CONNECTOR_UNAUTHORIZED_ERROR
} else {
hyperswitch_interfaces::consts::NO_ERROR_MESSAGE
};
match response {
Ok(transformers::WellsfargoErrorResponse::StandardError(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let (code, message, reason) = match response.error_information {
Some(ref error_info) => {
let detailed_error_info = error_info.details.as_ref().map(|details| {
details
.iter()
.map(|det| format!("{} : {}", det.field, det.reason))
.collect::<Vec<_>>()
.join(", ")
});
(
error_info.reason.clone(),
error_info.reason.clone(),
transformers::get_error_reason(
Some(error_info.message.clone()),
detailed_error_info,
None,
),
)
}
None => {
let detailed_error_info = response.details.map(|details| {
details
.iter()
.map(|det| format!("{} : {}", det.field, det.reason))
.collect::<Vec<_>>()
.join(", ")
});
(
response.reason.clone().map_or(
hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
|reason| reason.to_string(),
),
response
.reason
.map_or(error_message.to_string(), |reason| reason.to_string()),
transformers::get_error_reason(
response.message,
detailed_error_info,
None,
),
)
}
};
Ok(ErrorResponse {
status_code: res.status_code,
code,
message,
reason,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Ok(transformers::WellsfargoErrorResponse::AuthenticationError(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: response.response.rmsg.clone(),
reason: Some(response.response.rmsg),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Ok(transformers::WellsfargoErrorResponse::NotAvailableError(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_response = response
.errors
.iter()
.map(|error_info| {
format!(
"{}: {}",
error_info.error_type.clone().unwrap_or("".to_string()),
error_info.message.clone().unwrap_or("".to_string())
)
})
.collect::<Vec<String>>()
.join(" & ");
Ok(ErrorResponse {
status_code: res.status_code,
code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: error_response.clone(),
reason: Some(error_response),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Err(error_msg) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
router_env::logger::error!(deserialization_error =? error_msg);
utils::handle_json_response_deserialization_failure(res, "wellsfargo")
}
}
}
}
impl ConnectorValidation for Wellsfargo {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::ApplePay,
PaymentMethodDataType::GooglePay,
]);
utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Wellsfargo
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let date = OffsetDateTime::now_utc();
let wellsfargo_req = self.get_request_body(req, connectors)?;
let auth = wellsfargo::WellsfargoAuthType::try_from(&req.connector_auth_type)?;
let merchant_account = auth.merchant_account.clone();
let base_url = connectors.wellsfargo.base_url.as_str();
let wellsfargo_host =
Url::parse(base_url).change_context(errors::ConnectorError::RequestEncodingFailed)?;
let host = wellsfargo_host
.host_str()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
let path: String = self
.get_url(req, connectors)?
.chars()
.skip(base_url.len() - 1)
.collect();
let sha256 = self.generate_digest(wellsfargo_req.get_inner_value().expose().as_bytes());
let http_method = self.get_http_method();
let signature = self.generate_signature(
auth,
host.to_string(),
path.as_str(),
&sha256,
date,
http_method,
)?;
let mut headers = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
headers::ACCEPT.to_string(),
"application/hal+json;charset=utf-8".to_string().into(),
),
(
"v-c-merchant-id".to_string(),
merchant_account.into_masked(),
),
("Date".to_string(), date.to_string().into()),
("Host".to_string(), host.to_string().into()),
("Signature".to_string(), signature.into_masked()),
];
if matches!(http_method, Method::Post | Method::Put | Method::Patch) {
headers.push((
"Digest".to_string(),
format!("SHA-256={sha256}").into_masked(),
));
}
Ok(headers)
}
}
impl api::Payment for Wellsfargo {}
impl api::PaymentAuthorize for Wellsfargo {}
impl api::PaymentSync for Wellsfargo {}
impl api::PaymentVoid for Wellsfargo {}
impl api::PaymentCapture for Wellsfargo {}
impl api::PaymentIncrementalAuthorization for Wellsfargo {}
impl api::MandateSetup for Wellsfargo {}
impl api::ConnectorAccessToken for Wellsfargo {}
impl api::PaymentToken for Wellsfargo {}
impl api::ConnectorMandateRevoke for Wellsfargo {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Wellsfargo
{
// Not Implemented (R)
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Wellsfargo
{
fn get_headers(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}pts/v2/payments/", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = wellsfargo::WellsfargoZeroMandateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(SetupMandateType::get_headers(self, req, connectors)?)
.set_body(SetupMandateType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: wellsfargo::WellsfargoPaymentsResponse = res
.response
.parse_struct("WellsfargoSetupMandatesResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: wellsfargo::WellsfargoServerErrorResponse = res
.response
.parse_struct("WellsfargoServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None,
},
None => None,
};
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>
for Wellsfargo
{
fn get_headers(
&self,
req: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_http_method(&self) -> Method {
Method::Delete
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}tms/v1/paymentinstruments/{}",
self.base_url(connectors),
utils::RevokeMandateRequestData::get_connector_mandate_id(&req.request)?
))
}
fn build_request(
&self,
req: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Delete)
.url(&MandateRevokeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(MandateRevokeType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &MandateRevokeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<MandateRevokeRouterData, errors::ConnectorError> {
if matches!(res.status_code, 204) {
event_builder.map(|i| i.set_response_body(&serde_json::json!({"mandate_status": common_enums::MandateStatus::Revoked.to_string()})));
Ok(MandateRevokeRouterData {
response: Ok(MandateRevokeResponseData {
mandate_status: common_enums::MandateStatus::Revoked,
}),
..data.clone()
})
} else {
// If http_code != 204 || http_code != 4xx, we dont know any other response scenario yet.
let response_value: serde_json::Value = serde_json::from_slice(&res.response)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let response_string = response_value.to_string();
event_builder.map(|i| {
i.set_response_body(
&serde_json::json!({"response_string": response_string.clone()}),
)
});
router_env::logger::info!(connector_response=?response_string);
Ok(MandateRevokeRouterData {
response: Err(ErrorResponse {
code: hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string(),
message: response_string.clone(),
reason: Some(response_string),
status_code: res.status_code,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
..data.clone()
})
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Wellsfargo {
// Not Implemented (R)
}
impl api::PaymentSession for Wellsfargo {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Wellsfargo {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Wellsfargo {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{}/captures",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
MinorUnit::new(req.request.amount_to_capture),
req.request.currency,
)?;
let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req));
let connector_req =
wellsfargo::WellsfargoPaymentsCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
errors::ConnectorError,
> {
let response: wellsfargo::WellsfargoPaymentsResponse = res
.response
.parse_struct("Wellsfargo PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: wellsfargo::WellsfargoServerErrorResponse = res
.response
.parse_struct("WellsfargoServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Wellsfargo {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}tss/v2/transactions/{}",
self.base_url(connectors),
connector_payment_id
))
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: wellsfargo::WellsfargoTransactionResponse = res
.response
.parse_struct("Wellsfargo PaymentSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Wellsfargo {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}pts/v2/payments/",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
MinorUnit::new(req.request.amount),
req.request.currency,
)?;
let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req));
let connector_req =
wellsfargo::WellsfargoPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: wellsfargo::WellsfargoPaymentsResponse = res
.response
.parse_struct("Wellsfargo PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: wellsfargo::WellsfargoServerErrorResponse = res
.response
.parse_struct("WellsfargoServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None,
},
None => None,
};
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Wellsfargo {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{connector_payment_id}/reversals",
self.base_url(connectors)
))
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
MinorUnit::new(req.request.amount.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "Amount",
},
)?),
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Currency",
})?,
)?;
let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req));
let connector_req = wellsfargo::WellsfargoVoidRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: wellsfargo::WellsfargoPaymentsResponse = res
.response
.parse_struct("Wellsfargo PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: wellsfargo::WellsfargoServerErrorResponse = res
.response
.parse_struct("WellsfargoServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl Refund for Wellsfargo {}
impl RefundExecute for Wellsfargo {}
impl RefundSync for Wellsfargo {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Wellsfargo {
fn get_headers(
&self,
req: &RefundExecuteRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundExecuteRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{}/refunds",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &RefundExecuteRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
MinorUnit::new(req.request.refund_amount),
req.request.currency,
)?;
let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req));
let connector_req = wellsfargo::WellsfargoRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundExecuteRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundExecuteRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundExecuteRouterData, errors::ConnectorError> {
let response: wellsfargo::WellsfargoRefundResponse = res
.response
.parse_struct("Wellsfargo RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Wellsfargo {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}tss/v2/transactions/{}",
self.base_url(connectors),
refund_id
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: wellsfargo::WellsfargoRsyncResponse = res
.response
.parse_struct("Wellsfargo RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl
ConnectorIntegration<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
> for Wellsfargo
{
fn get_headers(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_http_method(&self) -> Method {
Method::Patch
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{}",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
MinorUnit::new(req.request.additional_amount),
req.request.currency,
)?;
let connector_router_data = wellsfargo::WellsfargoRouterData::from((amount, req));
let connector_request =
wellsfargo::WellsfargoPaymentsIncrementalAuthorizationRequest::try_from(
&connector_router_data,
)?;
Ok(RequestContent::Json(Box::new(connector_request)))
}
fn build_request(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Patch)
.url(&IncrementalAuthorizationType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(IncrementalAuthorizationType::get_headers(
self, req, connectors,
)?)
.set_body(IncrementalAuthorizationType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsIncrementalAuthorizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>,
errors::ConnectorError,
> {
let response: wellsfargo::WellsfargoPaymentsIncrementalAuthorizationResponse = res
.response
.parse_struct("Wellsfargo PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Wellsfargo {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static WELLSFARGO_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
];
let mut wellsfargo_supported_payment_methods = SupportedPaymentMethods::new();
wellsfargo_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
wellsfargo_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
wellsfargo_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
wellsfargo_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
wellsfargo_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
enums::PaymentMethodType::Ach,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
wellsfargo_supported_payment_methods
});
static WELLSFARGO_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Wells Fargo",
description:
"Wells Fargo is a major bank offering retail, commercial, and wealth management services",
connector_type: enums::HyperswitchConnectorCategory::BankAcquirer,
integration_status: enums::ConnectorIntegrationStatus::Beta,
};
static WELLSFARGO_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Wellsfargo {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&WELLSFARGO_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*WELLSFARGO_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&WELLSFARGO_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/wellsfargo.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_connectors_-9103577209080593626
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_connectors
// File: crates/hyperswitch_connectors/src/connectors/zsl.rs
// Contains: 1 structs, 0 enums
pub mod transformers;
use std::fmt::Debug;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::{BytesExt, ValueExt},
request::{Method, Request, RequestBuilder, RequestContent},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
api::ApplicationResponse,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSessionRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails},
};
use lazy_static::lazy_static;
use masking::{ExposeInterface, Secret};
use transformers::{self as zsl, get_status};
use crate::{
constants::headers,
types::{RefreshTokenRouterData, ResponseRouterData},
};
#[derive(Debug, Clone)]
pub struct Zsl;
impl api::Payment for Zsl {}
impl api::PaymentSession for Zsl {}
impl api::ConnectorAccessToken for Zsl {}
impl api::MandateSetup for Zsl {}
impl api::PaymentAuthorize for Zsl {}
impl api::PaymentSync for Zsl {}
impl api::PaymentCapture for Zsl {}
impl api::PaymentVoid for Zsl {}
impl api::Refund for Zsl {}
impl api::RefundExecute for Zsl {}
impl api::RefundSync for Zsl {}
impl api::PaymentToken for Zsl {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Zsl
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
_req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
Ok(header)
}
}
impl ConnectorCommon for Zsl {
fn id(&self) -> &'static str {
"zsl"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.zsl.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response = serde_urlencoded::from_bytes::<zsl::ZslErrorResponse>(&res.response)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_reason = zsl::ZslResponseStatus::try_from(response.status.clone())?.to_string();
Ok(ErrorResponse {
status_code: res.status_code,
code: response.status,
message: error_reason.clone(),
reason: Some(error_reason),
attempt_status: Some(common_enums::AttemptStatus::Failure),
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Zsl {
fn is_webhook_source_verification_mandatory(&self) -> bool {
true
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Zsl {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}ecp", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = zsl::ZslRouterData::try_from((
&self.get_currency_unit(),
req.request.currency,
req.request.amount,
req,
))?;
let connector_req = zsl::ZslPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response = serde_urlencoded::from_bytes::<zsl::ZslPaymentsResponse>(&res.response)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i: &mut ConnectorEvent| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Zsl {
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: zsl::ZslWebhookResponse = res
.response
.parse_struct("ZslWebhookResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i: &mut ConnectorEvent| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Zsl {
fn build_request(
&self,
_req: &PaymentsSessionRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "Session flow".to_owned(),
connector: "Zsl",
}
.into())
}
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Zsl
{
fn build_request(
&self,
_req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "PaymentMethod Tokenization flow ".to_owned(),
connector: "Zsl",
}
.into())
}
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Zsl {
fn build_request(
&self,
_req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "AccessTokenAuth flow".to_owned(),
connector: "Zsl",
}
.into())
}
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Zsl {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "SetupMandate flow".to_owned(),
connector: "Zsl",
}
.into())
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Zsl {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "Capture flow".to_owned(),
connector: "Zsl",
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Zsl {
fn build_request(
&self,
_req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "Void flow ".to_owned(),
connector: "Zsl",
}
.into())
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Zsl {
fn build_request(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "Refund flow".to_owned(),
connector: "Zsl",
}
.into())
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Zsl {
fn build_request(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "Rsync flow ".to_owned(),
connector: "Zsl",
}
.into())
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Zsl {
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::PaymentAttemptId(notif.mer_ref),
))
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(get_status(notif.status))
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let response = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(Box::new(response))
}
async fn verify_webhook_source(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
_connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_account_details = connector_account_details
.parse_value::<ConnectorAuthType>("ConnectorAuthType")
.change_context_lazy(|| errors::ConnectorError::WebhookSourceVerificationFailed)?;
let auth_type = zsl::ZslAuthType::try_from(&connector_account_details)?;
let key = auth_type.api_key.expose();
let mer_id = auth_type.merchant_id.expose();
let webhook_response = get_webhook_object_from_body(request.body)?;
let signature = zsl::calculate_signature(
webhook_response.enctype,
zsl::ZslSignatureType::WebhookSignature {
status: webhook_response.status,
txn_id: webhook_response.txn_id,
txn_date: webhook_response.txn_date,
paid_ccy: webhook_response.paid_ccy.to_string(),
paid_amt: webhook_response.paid_amt,
mer_ref: webhook_response.mer_ref,
mer_id,
key,
},
)?;
Ok(signature.eq(&webhook_response.signature))
}
fn get_webhook_api_response(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_error_kind: Option<IncomingWebhookFlowError>,
) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
Ok(ApplicationResponse::TextPlain("CALLBACK-OK".to_string()))
}
}
fn get_webhook_object_from_body(
body: &[u8],
) -> CustomResult<zsl::ZslWebhookResponse, errors::ConnectorError> {
let response: zsl::ZslWebhookResponse =
serde_urlencoded::from_bytes::<zsl::ZslWebhookResponse>(body)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
Ok(response)
}
lazy_static! {
static ref ZSL_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
let mut zsl_supported_payment_methods = SupportedPaymentMethods::new();
zsl_supported_payment_methods.add(
enums::PaymentMethod::BankTransfer,
enums::PaymentMethodType::LocalBankTransfer,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::NotSupported,
supported_capture_methods,
specific_features: None,
},
);
zsl_supported_payment_methods
};
static ref ZSL_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "ZSL",
description:
"Zsl is a payment gateway operating in China, specializing in facilitating local bank transfers",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static ref ZSL_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
}
impl ConnectorSpecifications for Zsl {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*ZSL_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*ZSL_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*ZSL_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/zsl.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_connectors_9074514464456582528
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_connectors
// File: crates/hyperswitch_connectors/src/connectors/braintree.rs
// Contains: 1 structs, 0 enums
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::IncomingWebhookEvent;
use base64::Engine;
use common_enums::{enums, CallConnectorAction, PaymentAction};
use common_utils::{
consts::BASE64_ENGINE,
crypto,
errors::{CustomResult, ParsingError},
ext_traits::{BytesExt, XmlExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{
AmountConvertor, StringMajorUnit, StringMajorUnitForConnector, StringMinorUnit,
StringMinorUnitForConnector,
},
};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::{
api::ApplicationResponse,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
mandate_revoke::MandateRevoke,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
CompleteAuthorize,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, MandateRevokeRequestData,
PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData,
PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData, RefundsData,
SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, PaymentsResponseData,
RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsSessionRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
disputes::DisputePayload,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
MandateRevokeType, PaymentsAuthorizeType, PaymentsCaptureType,
PaymentsCompleteAuthorizeType, PaymentsSessionType, PaymentsSyncType, PaymentsVoidType,
RefundExecuteType, RefundSyncType, Response, TokenizationType,
},
webhooks::{IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails},
};
use masking::{ExposeInterface, Mask, PeekInterface, Secret};
use ring::hmac;
use router_env::logger;
use sha1::{Digest, Sha1};
use transformers::{self as braintree, get_status};
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{
self, convert_amount, is_mandate_supported, PaymentMethodDataType,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData,
},
};
#[derive(Clone)]
pub struct Braintree {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
amount_converter_webhooks: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Braintree {
pub const fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
amount_converter_webhooks: &StringMinorUnitForConnector,
}
}
}
pub const BRAINTREE_VERSION: &str = "Braintree-Version";
pub const BRAINTREE_VERSION_VALUE: &str = "2019-01-01";
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Braintree
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
BRAINTREE_VERSION.to_string(),
BRAINTREE_VERSION_VALUE.to_string().into(),
),
];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Braintree {
fn id(&self) -> &'static str {
"braintree"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.braintree.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = braintree::BraintreeAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_key = format!("{}:{}", auth.public_key.peek(), auth.private_key.peek());
let auth_header = format!("Basic {}", BASE64_ENGINE.encode(auth_key));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth_header.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<braintree::ErrorResponses, Report<ParsingError>> =
res.response.parse_struct("Braintree Error Response");
match response {
Ok(braintree::ErrorResponses::BraintreeApiErrorResponse(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_object = response.api_error_response.errors;
let error = error_object.errors.first().or(error_object
.transaction
.as_ref()
.and_then(|transaction_error| {
transaction_error.errors.first().or(transaction_error
.credit_card
.as_ref()
.and_then(|credit_card_error| credit_card_error.errors.first()))
}));
let (code, message) = error.map_or(
(NO_ERROR_CODE.to_string(), NO_ERROR_MESSAGE.to_string()),
|error| (error.code.clone(), error.message.clone()),
);
Ok(ErrorResponse {
status_code: res.status_code,
code,
message,
reason: Some(response.api_error_response.message),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Ok(braintree::ErrorResponses::BraintreeErrorResponse(response)) => {
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: Some(response.errors),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Err(error_msg) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
logger::error!(deserialization_error =? error_msg);
utils::handle_json_response_deserialization_failure(res, "braintree")
}
}
}
}
impl ConnectorValidation for Braintree {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: hyperswitch_domain_models::payment_method_data::PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]);
is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl api::Payment for Braintree {}
impl api::PaymentAuthorize for Braintree {}
impl api::PaymentSync for Braintree {}
impl api::PaymentVoid for Braintree {}
impl api::PaymentCapture for Braintree {}
impl api::PaymentsCompleteAuthorize for Braintree {}
impl api::PaymentSession for Braintree {}
impl api::ConnectorAccessToken for Braintree {}
impl api::ConnectorMandateRevoke for Braintree {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Braintree {
// Not Implemented (R)
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Braintree {
fn get_headers(
&self,
req: &PaymentsSessionRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSessionRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &PaymentsSessionRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let metadata: braintree::BraintreeMeta =
braintree::BraintreeMeta::try_from(&req.connector_meta_data)?;
let connector_req = braintree::BraintreeClientTokenRequest::try_from(metadata)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsSessionRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsSessionType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSessionType::get_headers(self, req, connectors)?)
.set_body(PaymentsSessionType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSessionRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSessionRouterData, errors::ConnectorError>
where
PaymentsResponseData: Clone,
{
let response: braintree::BraintreeSessionResponse = res
.response
.parse_struct("BraintreeSessionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
utils::ForeignTryFrom::foreign_try_from((
crate::types::PaymentsSessionResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
data.clone(),
))
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentToken for Braintree {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Braintree
{
fn get_headers(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = transformers::BraintreeTokenRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(TokenizationType::get_headers(self, req, connectors)?)
.set_body(TokenizationType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<TokenizationRouterData, errors::ConnectorError>
where
PaymentsResponseData: Clone,
{
let response: transformers::BraintreeTokenResponse = res
.response
.parse_struct("BraintreeTokenResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::MandateSetup for Braintree {}
#[allow(dead_code)]
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Braintree
{
// Not Implemented (R)
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Braintree".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Braintree {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
let connector_req =
transformers::BraintreeCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: transformers::BraintreeCaptureResponse = res
.response
.parse_struct("Braintree PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Braintree {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = transformers::BraintreePSyncRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(PaymentsSyncType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: transformers::BraintreePSyncResponse = res
.response
.parse_struct("Braintree PaymentSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Braintree {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
let connector_req: transformers::BraintreePaymentsRequest =
transformers::BraintreePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
match data.request.is_auto_capture()? {
true => {
let response: transformers::BraintreePaymentsResponse = res
.response
.parse_struct("Braintree PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
false => {
let response: transformers::BraintreeAuthResponse = res
.response
.parse_struct("Braintree AuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>
for Braintree
{
fn get_headers(
&self,
req: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
_req: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn build_request(
&self,
req: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&MandateRevokeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(MandateRevokeType::get_headers(self, req, connectors)?)
.set_body(MandateRevokeType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn get_request_body(
&self,
req: &MandateRevokeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = transformers::BraintreeRevokeMandateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
&self,
data: &MandateRevokeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<MandateRevokeRouterData, errors::ConnectorError> {
let response: transformers::BraintreeRevokeMandateResponse = res
.response
.parse_struct("BraintreeRevokeMandateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Braintree {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = transformers::BraintreeCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: transformers::BraintreeCancelResponse = res
.response
.parse_struct("Braintree VoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::Refund for Braintree {}
impl api::RefundExecute for Braintree {}
impl api::RefundSync for Braintree {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Braintree {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
let connector_req = transformers::BraintreeRefundRequest::try_from(connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: transformers::BraintreeRefundResponse = res
.response
.parse_struct("Braintree RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Braintree {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = transformers::BraintreeRSyncRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundSyncType::get_headers(self, req, connectors)?)
.set_body(RefundSyncType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RouterData<RSync, RefundsData, RefundsResponseData>, errors::ConnectorError>
{
let response: transformers::BraintreeRSyncResponse = res
.response
.parse_struct("Braintree RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Braintree {
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha1))
}
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let notif_item = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let signature_pairs: Vec<(&str, &str)> = notif_item
.bt_signature
.split('&')
.collect::<Vec<&str>>()
.into_iter()
.map(|pair| pair.split_once('|').unwrap_or(("", "")))
.collect::<Vec<(_, _)>>();
let merchant_secret = connector_webhook_secrets
.additional_secret //public key
.clone()
.ok_or(errors::ConnectorError::WebhookVerificationSecretNotFound)?;
let signature = get_matching_webhook_signature(signature_pairs, merchant_secret.expose())
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;
Ok(signature.as_bytes().to_vec())
}
fn get_webhook_source_verification_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let notify = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let message = notify.bt_payload.to_string();
Ok(message.into_bytes())
}
async fn verify_webhook_source(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_label,
connector_webhook_details,
)
.await
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
let message = self
.get_webhook_source_verification_message(
request,
merchant_id,
&connector_webhook_secrets,
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let sha1_hash_key = Sha1::digest(&connector_webhook_secrets.secret);
let signing_key = hmac::Key::new(
hmac::HMAC_SHA1_FOR_LEGACY_USE_ONLY,
sha1_hash_key.as_slice(),
);
let signed_messaged = hmac::sign(&signing_key, &message);
let payload_sign: String = hex::encode(signed_messaged);
Ok(payload_sign.as_bytes().eq(&signature))
}
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif = get_webhook_object_from_body(_request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let response = decode_webhook_payload(notif.bt_payload.replace('\n', "").as_bytes())?;
match response.dispute {
Some(dispute_data) => Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
dispute_data.transaction.id,
),
)),
None => Err(report!(errors::ConnectorError::WebhookReferenceIdNotFound)),
}
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let response = decode_webhook_payload(notif.bt_payload.replace('\n', "").as_bytes())?;
Ok(get_status(response.kind.as_str()))
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let response = decode_webhook_payload(notif.bt_payload.replace('\n', "").as_bytes())?;
Ok(Box::new(response))
}
fn get_webhook_api_response(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
_error_kind: Option<IncomingWebhookFlowError>,
) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
Ok(ApplicationResponse::TextPlain("[accepted]".to_string()))
}
fn get_dispute_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<DisputePayload, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let response = decode_webhook_payload(notif.bt_payload.replace('\n', "").as_bytes())?;
match response.dispute {
Some(dispute_data) => Ok(DisputePayload {
amount: convert_amount(
self.amount_converter_webhooks,
dispute_data.amount_disputed,
dispute_data.currency_iso_code,
)?,
currency: dispute_data.currency_iso_code,
dispute_stage: transformers::get_dispute_stage(dispute_data.kind.as_str())?,
connector_dispute_id: dispute_data.id,
connector_reason: dispute_data.reason,
connector_reason_code: dispute_data.reason_code,
challenge_required_by: dispute_data.reply_by_date,
connector_status: dispute_data.status,
created_at: dispute_data.created_at,
updated_at: dispute_data.updated_at,
}),
None => Err(errors::ConnectorError::WebhookResourceObjectNotFound)?,
}
}
}
fn get_matching_webhook_signature(
signature_pairs: Vec<(&str, &str)>,
secret: String,
) -> Option<String> {
for (public_key, signature) in signature_pairs {
if *public_key == secret {
return Some(signature.to_string());
}
}
None
}
fn get_webhook_object_from_body(
body: &[u8],
) -> CustomResult<transformers::BraintreeWebhookResponse, ParsingError> {
serde_urlencoded::from_bytes::<transformers::BraintreeWebhookResponse>(body)
.change_context(ParsingError::StructParseFailure("BraintreeWebhookResponse"))
}
fn decode_webhook_payload(
payload: &[u8],
) -> CustomResult<transformers::Notification, errors::ConnectorError> {
let decoded_response = BASE64_ENGINE
.decode(payload)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let xml_response = String::from_utf8(decoded_response)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
xml_response
.parse_xml::<transformers::Notification>()
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)
}
impl ConnectorRedirectResponse for Braintree {
fn get_flow_type(
&self,
_query_params: &str,
json_payload: Option<serde_json::Value>,
action: PaymentAction,
) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
match action {
PaymentAction::PSync => match json_payload {
Some(payload) => {
let redirection_response: transformers::BraintreeRedirectionResponse =
serde_json::from_value(payload).change_context(
errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "redirection_response",
},
)?;
let braintree_payload =
serde_json::from_str::<transformers::BraintreeThreeDsErrorResponse>(
&redirection_response.authentication_response,
);
let (error_code, error_message) = match braintree_payload {
Ok(braintree_response_payload) => (
braintree_response_payload.code,
braintree_response_payload.message,
),
Err(_) => (
NO_ERROR_CODE.to_string(),
redirection_response.authentication_response,
),
};
Ok(CallConnectorAction::StatusUpdate {
status: enums::AttemptStatus::AuthenticationFailed,
error_code: Some(error_code),
error_message: Some(error_message),
})
}
None => Ok(CallConnectorAction::Avoid),
},
PaymentAction::CompleteAuthorize
| PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(CallConnectorAction::Trigger)
}
}
}
}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Braintree
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_string())
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = braintree::BraintreeRouterData::try_from((amount, req))?;
let connector_req =
transformers::BraintreePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
match PaymentsCompleteAuthorizeRequestData::is_auto_capture(&data.request)? {
true => {
let response: transformers::BraintreeCompleteChargeResponse = res
.response
.parse_struct("Braintree PaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
false => {
let response: transformers::BraintreeCompleteAuthResponse = res
.response
.parse_struct("Braintree AuthResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
static BRAINTREE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
];
let mut braintree_supported_payment_methods = SupportedPaymentMethods::new();
braintree_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
braintree_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
braintree_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
braintree_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
braintree_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Paypal,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
braintree_supported_payment_methods
});
static BRAINTREE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Braintree",
description:
"Braintree, a PayPal service, offers a full-stack payment platform that simplifies accepting payments in your app or website, supporting various payment methods including credit cards and PayPal.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static BRAINTREE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] =
[enums::EventClass::Payments, enums::EventClass::Refunds];
impl ConnectorSpecifications for Braintree {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&BRAINTREE_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BRAINTREE_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&BRAINTREE_SUPPORTED_WEBHOOK_FLOWS)
}
fn is_sdk_client_token_generation_enabled(&self) -> bool {
true
}
fn supported_payment_method_types_for_sdk_client_token_generation(
&self,
) -> Vec<enums::PaymentMethodType> {
vec![
enums::PaymentMethodType::ApplePay,
enums::PaymentMethodType::GooglePay,
enums::PaymentMethodType::Paypal,
]
}
}
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/braintree.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_connectors_2508401549477667830
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_connectors
// File: crates/hyperswitch_connectors/src/connectors/noon.rs
// Contains: 1 structs, 0 enums
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::{ConnectorWebhookSecrets, IncomingWebhookEvent, ObjectReferenceId};
use base64::Engine;
use common_enums::enums;
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{Report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
mandate_revoke::MandateRevoke,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, MandateRevokeRequestData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, MandateRevokeResponseData, PaymentMethodDetails, PaymentsResponseData,
RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
MandateRevokeRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
MandateRevokeType, PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType,
PaymentsVoidType, RefundExecuteType, RefundSyncType, Response,
},
webhooks,
};
use masking::{Mask, PeekInterface};
use router_env::logger;
use transformers as noon;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self as connector_utils, PaymentMethodDataType},
};
#[derive(Clone)]
pub struct Noon {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Noon {
pub const fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl api::Payment for Noon {}
impl api::PaymentSession for Noon {}
impl api::ConnectorAccessToken for Noon {}
impl api::MandateSetup for Noon {}
impl api::PaymentAuthorize for Noon {}
impl api::PaymentSync for Noon {}
impl api::PaymentCapture for Noon {}
impl api::PaymentVoid for Noon {}
impl api::Refund for Noon {}
impl api::RefundExecute for Noon {}
impl api::RefundSync for Noon {}
impl api::PaymentToken for Noon {}
impl api::ConnectorMandateRevoke for Noon {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Noon
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Noon
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
)];
let mut api_key = get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
fn get_auth_header(
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = noon::NoonAuthType::try_from(auth_type)?;
let encoded_api_key = auth
.business_identifier
.zip(auth.application_identifier)
.zip(auth.api_key)
.map(|((business_identifier, application_identifier), api_key)| {
common_utils::consts::BASE64_ENGINE.encode(format!(
"{business_identifier}.{application_identifier}:{api_key}",
))
});
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Key {}", encoded_api_key.peek()).into_masked(),
)])
}
impl ConnectorCommon for Noon {
fn id(&self) -> &'static str {
"noon"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.noon.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<noon::NoonErrorResponse, Report<common_utils::errors::ParsingError>> =
res.response.parse_struct("NoonErrorResponse");
match response {
Ok(noon_error_response) => {
event_builder.map(|i| i.set_error_response_body(&noon_error_response));
router_env::logger::info!(connector_response=?noon_error_response);
// Adding in case of timeouts, if psync gives 4xx with this code, fail the payment
let attempt_status = if noon_error_response.result_code == 19001 {
Some(enums::AttemptStatus::Failure)
} else {
None
};
Ok(ErrorResponse {
status_code: res.status_code,
code: noon_error_response.result_code.to_string(),
message: noon_error_response.class_description,
reason: Some(noon_error_response.message),
attempt_status,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Err(error_message) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
logger::error!(deserialization_error =? error_message);
connector_utils::handle_json_response_deserialization_failure(res, "noon")
}
}
}
}
impl ConnectorValidation for Noon {
fn validate_connector_against_payment_request(
&self,
capture_method: Option<enums::CaptureMethod>,
_payment_method: enums::PaymentMethod,
_pmt: Option<enums::PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
match capture_method {
enums::CaptureMethod::Automatic
| enums::CaptureMethod::Manual
| enums::CaptureMethod::SequentialAutomatic => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
connector_utils::construct_not_implemented_error_report(capture_method, self.id()),
),
}
}
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::ApplePay,
PaymentMethodDataType::GooglePay,
]);
connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
fn validate_psync_reference_id(
&self,
_data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
// since we can make psync call with our reference_id, having connector_transaction_id is not an mandatory criteria
Ok(())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Noon {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Noon {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Noon {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Noon".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Noon {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}payment/v1/order", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let mandate_details =
connector_utils::get_mandate_details(req.request.setup_mandate_details.clone())?;
let mandate_amount = mandate_details
.map(|mandate| {
connector_utils::convert_amount(
self.amount_converter,
mandate.amount,
mandate.currency,
)
})
.transpose()?;
let connector_router_data = noon::NoonRouterData::from((amount, req, mandate_amount));
let connector_req = noon::NoonPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: noon::NoonPaymentsResponse = res
.response
.parse_struct("Noon PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Noon {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}payment/v1/order/getbyreference/{}",
self.base_url(connectors),
req.connector_request_reference_id
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: noon::NoonPaymentsResponse = res
.response
.parse_struct("noon PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Noon {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}payment/v1/order", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = noon::NoonRouterData::from((amount, req, None));
let connector_req = noon::NoonPaymentsActionRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: noon::NoonPaymentsResponse = res
.response
.parse_struct("Noon PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Noon {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}payment/v1/order", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = noon::NoonPaymentsCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: noon::NoonPaymentsResponse = res
.response
.parse_struct("Noon PaymentsCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>
for Noon
{
fn get_headers(
&self,
req: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}payment/v1/order", self.base_url(connectors)))
}
fn build_request(
&self,
req: &MandateRevokeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&MandateRevokeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(MandateRevokeType::get_headers(self, req, connectors)?)
.set_body(MandateRevokeType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn get_request_body(
&self,
req: &MandateRevokeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = noon::NoonRevokeMandateRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn handle_response(
&self,
data: &MandateRevokeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<MandateRevokeRouterData, errors::ConnectorError> {
let response: noon::NoonRevokeMandateResponse = res
.response
.parse_struct("Noon NoonRevokeMandateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Noon {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}payment/v1/order", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = noon::NoonRouterData::from((refund_amount, req, None));
let connector_req = noon::NoonPaymentsActionRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: noon::RefundResponse = res
.response
.parse_struct("noon RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Noon {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}payment/v1/order/getbyreference/{}",
self.base_url(connectors),
req.connector_request_reference_id
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: noon::RefundSyncResponse = res
.response
.parse_struct("noon RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::ConnectorRedirectResponse for Noon {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
action: enums::PaymentAction,
) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> {
match action {
enums::PaymentAction::PSync
| enums::PaymentAction::CompleteAuthorize
| enums::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(enums::CallConnectorAction::Trigger)
}
}
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Noon {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha512))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let webhook_body: noon::NoonWebhookSignature = request
.body
.parse_struct("NoonWebhookSignature")
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
let signature = webhook_body.signature;
common_utils::consts::BASE64_ENGINE
.decode(signature)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let webhook_body: noon::NoonWebhookBody = request
.body
.parse_struct("NoonWebhookBody")
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
let message = format!(
"{},{},{},{},{}",
webhook_body.order_id,
webhook_body.order_status,
webhook_body.event_id,
webhook_body.event_type,
webhook_body.time_stamp,
);
Ok(message.into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, errors::ConnectorError> {
let details: noon::NoonWebhookOrderId = request
.body
.parse_struct("NoonWebhookOrderId")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
details.order_id.to_string(),
),
))
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let details: noon::NoonWebhookEvent = request
.body
.parse_struct("NoonWebhookEvent")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(match &details.event_type {
noon::NoonWebhookEventTypes::Sale | noon::NoonWebhookEventTypes::Capture => {
match &details.order_status {
noon::NoonPaymentStatus::Captured => IncomingWebhookEvent::PaymentIntentSuccess,
_ => Err(errors::ConnectorError::WebhookEventTypeNotFound)?,
}
}
noon::NoonWebhookEventTypes::Fail => IncomingWebhookEvent::PaymentIntentFailure,
noon::NoonWebhookEventTypes::Authorize
| noon::NoonWebhookEventTypes::Authenticate
| noon::NoonWebhookEventTypes::Refund
| noon::NoonWebhookEventTypes::Unknown => IncomingWebhookEvent::EventNotSupported,
})
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let resource: noon::NoonWebhookObject = request
.body
.parse_struct("NoonWebhookObject")
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(noon::NoonPaymentsResponse::from(resource)))
}
}
static NOON_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
];
let mut noon_supported_payment_methods = SupportedPaymentMethods::new();
noon_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
noon_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
noon_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
noon_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
noon_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Paypal,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
noon_supported_payment_methods
});
static NOON_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Noon",
description: "Noon is a payment gateway and PSP enabling secure online transactions",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static NOON_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
impl ConnectorSpecifications for Noon {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&NOON_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*NOON_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&NOON_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/noon.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_connectors_5028629497934600287
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_connectors
// File: crates/hyperswitch_connectors/src/connectors/breadpay.rs
// Contains: 1 structs, 0 enums
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::{enums, CallConnectorAction, PaymentAction};
use common_utils::{
consts::BASE64_ENGINE,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
CompleteAuthorize,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask, Maskable, PeekInterface};
use transformers::{
self as breadpay, BreadpayTransactionRequest, BreadpayTransactionResponse,
BreadpayTransactionType,
};
use crate::{
connectors::breadpay::transformers::CallBackResponse,
constants::headers,
types::ResponseRouterData,
utils::{self, PaymentsCompleteAuthorizeRequestData},
};
#[derive(Clone)]
pub struct Breadpay {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Breadpay {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Breadpay {}
impl api::PaymentSession for Breadpay {}
impl api::PaymentsCompleteAuthorize for Breadpay {}
impl api::ConnectorAccessToken for Breadpay {}
impl api::MandateSetup for Breadpay {}
impl api::PaymentAuthorize for Breadpay {}
impl api::PaymentSync for Breadpay {}
impl api::PaymentCapture for Breadpay {}
impl api::PaymentVoid for Breadpay {}
impl api::Refund for Breadpay {}
impl api::RefundExecute for Breadpay {}
impl api::RefundSync for Breadpay {}
impl api::PaymentToken for Breadpay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Breadpay
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Breadpay
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Breadpay {
fn id(&self) -> &'static str {
"breadpay"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
// TODO! Check connector documentation, on which unit they are processing the currency.
// If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
// if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.breadpay.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = breadpay::BreadpayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let encoded_api_key = BASE64_ENGINE.encode(format!(
"{}:{}",
auth.api_key.peek(),
auth.api_secret.peek()
));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Basic {encoded_api_key}").into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: breadpay::BreadpayErrorResponse = res
.response
.parse_struct("BreadpayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_type.clone(),
message: response.description.clone(),
reason: Some(response.description),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Breadpay {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Breadpay {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Breadpay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Breadpay
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Breadpay {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}{}", self.base_url(connectors), "/carts"))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = breadpay::BreadpayRouterData::from((amount, req));
let connector_req = breadpay::BreadpayCartRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: breadpay::BreadpayPaymentsResponse = res
.response
.parse_struct("Breadpay BreadpayPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Breadpay
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let transaction_type = if req.request.is_auto_capture()? {
BreadpayTransactionType::Settle
} else {
BreadpayTransactionType::Authorize
};
let connector_req = BreadpayTransactionRequest { transaction_type };
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn get_url(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let redirect_response = req.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
let redirect_payload = redirect_response
.payload
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.expose();
let call_back_response: CallBackResponse = serde_json::from_value::<CallBackResponse>(
redirect_payload.clone(),
)
.change_context(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "redirection_payload",
})?;
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"/transactions/actions",
call_back_response.transaction_id
))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.headers(types::PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: BreadpayTransactionResponse = res
.response
.parse_struct("BreadpayTransactionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Breadpay {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"/transactions",
req.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: BreadpayTransactionResponse = res
.response
.parse_struct("BreadpayTransactionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Breadpay {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"/transactions/actions",
req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = BreadpayTransactionRequest {
transaction_type: BreadpayTransactionType::Settle,
};
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: BreadpayTransactionResponse = res
.response
.parse_struct("BreadpayTransactionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Breadpay {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"/transactions/actions",
req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
_req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = BreadpayTransactionRequest {
transaction_type: BreadpayTransactionType::Cancel,
};
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: BreadpayTransactionResponse = res
.response
.parse_struct("BreadpayTransactionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Breadpay {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = breadpay::BreadpayRouterData::from((refund_amount, req));
let connector_req = breadpay::BreadpayRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: breadpay::RefundResponse = res
.response
.parse_struct("breadpay RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Breadpay {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: breadpay::RefundResponse = res
.response
.parse_struct("breadpay RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Breadpay {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static BREADPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let mut breadpay_supported_payment_methods = SupportedPaymentMethods::new();
breadpay_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
enums::PaymentMethodType::Breadpay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
breadpay_supported_payment_methods
});
static BREADPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Breadpay",
description: "Breadpay connector",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static BREADPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Breadpay {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&BREADPAY_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BREADPAY_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&BREADPAY_SUPPORTED_WEBHOOK_FLOWS)
}
}
impl ConnectorRedirectResponse for Breadpay {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
action: PaymentAction,
) -> CustomResult<CallConnectorAction, errors::ConnectorError> {
match action {
PaymentAction::PSync
| PaymentAction::CompleteAuthorize
| PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(CallConnectorAction::Trigger)
}
}
}
}
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/breadpay.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_connectors_935778917553707437
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_connectors
// File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
// Contains: 1 structs, 0 enums
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_utils::{
consts::BASE64_ENGINE,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{
Authorize, Capture, PSync, PaymentMethodToken, PostCaptureVoid, Session, SetupMandate,
Void,
},
refunds::{Execute, RSync},
Accept, Dsync, Evidence, Fetch, Retrieve, Upload,
},
router_request_types::{
AcceptDisputeRequestData, AccessTokenRequestData, DisputeSyncData,
FetchDisputesRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData,
PaymentsSessionData, PaymentsSyncData, RefundsData, RetrieveFileRequestData,
SetupMandateRequestData, SubmitEvidenceRequestData, UploadFileRequestData,
},
router_response_types::{
AcceptDisputeResponse, ConnectorInfo, DisputeSyncResponse, FetchDisputesResponse,
PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, RetrieveFileResponse,
SubmitEvidenceResponse, SupportedPaymentMethods, SupportedPaymentMethodsExt,
UploadFileResponse,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelPostCaptureRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self,
disputes::{AcceptDispute, Dispute, DisputeSync, FetchDisputes, SubmitEvidence},
files::{FilePurpose, FileUpload, RetrieveFile, UploadFile},
ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts::NO_ERROR_CODE,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{Mask, PeekInterface};
use transformers as worldpayvantiv;
use crate::{
constants::headers,
types::{
AcceptDisputeRouterData, DisputeSyncRouterData, FetchDisputeRouterData, ResponseRouterData,
RetrieveFileRouterData, SubmitEvidenceRouterData, UploadFileRouterData,
},
utils as connector_utils,
};
#[derive(Clone)]
pub struct Worldpayvantiv {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Worldpayvantiv {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Worldpayvantiv {}
impl api::PaymentSession for Worldpayvantiv {}
impl api::ConnectorAccessToken for Worldpayvantiv {}
impl api::MandateSetup for Worldpayvantiv {}
impl api::PaymentAuthorize for Worldpayvantiv {}
impl api::PaymentSync for Worldpayvantiv {}
impl api::PaymentCapture for Worldpayvantiv {}
impl api::PaymentVoid for Worldpayvantiv {}
impl api::Refund for Worldpayvantiv {}
impl api::RefundExecute for Worldpayvantiv {}
impl api::RefundSync for Worldpayvantiv {}
impl api::PaymentToken for Worldpayvantiv {}
impl api::PaymentPostCaptureVoid for Worldpayvantiv {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Worldpayvantiv
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Worldpayvantiv
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
_req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
Ok(header)
}
}
impl ConnectorCommon for Worldpayvantiv {
fn id(&self) -> &'static str {
"worldpayvantiv"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"text/xml"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.worldpayvantiv.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = worldpayvantiv::WorldpayvantivAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_key = format!("{}:{}", auth.user.peek(), auth.password.peek());
let auth_header = format!("Basic {}", BASE64_ENGINE.encode(auth_key));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth_header.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<worldpayvantiv::CnpOnlineResponse, _> =
connector_utils::deserialize_xml_to_struct(&res.response);
match response {
Ok(response_data) => {
event_builder.map(|i| i.set_response_body(&response_data));
router_env::logger::info!(connector_response=?response_data);
Ok(ErrorResponse {
status_code: res.status_code,
code: response_data.response_code,
message: response_data.message.clone(),
reason: Some(response_data.message.clone()),
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Err(error_msg) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
router_env::logger::error!(deserialization_error =? error_msg);
connector_utils::handle_json_response_deserialization_failure(res, "worldpayvantiv")
}
}
}
}
impl ConnectorValidation for Worldpayvantiv {
fn validate_mandate_payment(
&self,
pm_type: Option<api_models::enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([
connector_utils::PaymentMethodDataType::Card,
connector_utils::PaymentMethodDataType::ApplePay,
connector_utils::PaymentMethodDataType::GooglePay,
]);
connector_utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Worldpayvantiv {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Worldpayvantiv {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Worldpayvantiv
{
fn get_headers(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_owned())
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req_object = worldpayvantiv::CnpOnlineRequest::try_from(req)?;
router_env::logger::info!(raw_connector_request=?connector_req_object);
let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes(
&connector_req_object,
worldpayvantiv::worldpayvantiv_constants::XML_VERSION,
Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING),
None,
None,
)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::SetupMandateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::SetupMandateType::get_headers(self, req, connectors)?)
.set_body(types::SetupMandateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: worldpayvantiv::CnpOnlineResponse =
connector_utils::deserialize_xml_to_struct(&res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for Worldpayvantiv
{
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_owned())
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = worldpayvantiv::WorldpayvantivRouterData::from((amount, req));
let connector_req_object =
worldpayvantiv::CnpOnlineRequest::try_from(&connector_router_data)?;
router_env::logger::info!(raw_connector_request=?connector_req_object);
let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes(
&connector_req_object,
worldpayvantiv::worldpayvantiv_constants::XML_VERSION,
Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING),
None,
None,
)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
// For certification purposes, to be removed later
router_env::logger::info!(raw_connector_response=?res.response);
let response: worldpayvantiv::CnpOnlineResponse =
connector_utils::deserialize_xml_to_struct(&res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Worldpayvantiv {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.get_auth_header(&req.connector_auth_type)
}
fn get_content_type(&self) -> &'static str {
"application/json"
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/reports/dtrPaymentStatus/{}",
connectors.worldpayvantiv.secondary_base_url.to_owned(),
req.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: worldpayvantiv::VantivSyncResponse = res
.response
.parse_struct("VantivSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
handle_vantiv_json_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Worldpayvantiv {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_owned())
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = worldpayvantiv::WorldpayvantivRouterData::from((amount, req));
let connector_req_object =
worldpayvantiv::CnpOnlineRequest::try_from(&connector_router_data)?;
router_env::logger::info!(raw_connector_request=?connector_req_object);
let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes(
&connector_req_object,
worldpayvantiv::worldpayvantiv_constants::XML_VERSION,
Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING),
None,
None,
)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: worldpayvantiv::CnpOnlineResponse =
connector_utils::deserialize_xml_to_struct(&res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Worldpayvantiv {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_owned())
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req_object = worldpayvantiv::CnpOnlineRequest::try_from(req)?;
router_env::logger::info!(raw_connector_request=?connector_req_object);
let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes(
&connector_req_object,
worldpayvantiv::worldpayvantiv_constants::XML_VERSION,
Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING),
None,
None,
)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: worldpayvantiv::CnpOnlineResponse =
connector_utils::deserialize_xml_to_struct(&res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>
for Worldpayvantiv
{
fn get_headers(
&self,
req: &PaymentsCancelPostCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCancelPostCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_owned())
}
fn get_request_body(
&self,
req: &PaymentsCancelPostCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req_object = worldpayvantiv::CnpOnlineRequest::try_from(req)?;
router_env::logger::info!(raw_connector_request=?connector_req_object);
let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes(
&connector_req_object,
worldpayvantiv::worldpayvantiv_constants::XML_VERSION,
Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING),
None,
None,
)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &PaymentsCancelPostCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsPostCaptureVoidType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsPostCaptureVoidType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsPostCaptureVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelPostCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelPostCaptureRouterData, errors::ConnectorError> {
let response: worldpayvantiv::CnpOnlineResponse =
connector_utils::deserialize_xml_to_struct(&res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Worldpayvantiv {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(self.base_url(connectors).to_owned())
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = connector_utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data =
worldpayvantiv::WorldpayvantivRouterData::from((refund_amount, req));
let connector_req_object =
worldpayvantiv::CnpOnlineRequest::try_from(&connector_router_data)?;
router_env::logger::info!(connector_request=?connector_req_object);
let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes(
&connector_req_object,
worldpayvantiv::worldpayvantiv_constants::XML_VERSION,
Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING),
None,
None,
)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: worldpayvantiv::CnpOnlineResponse =
connector_utils::deserialize_xml_to_struct(&res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Worldpayvantiv {
fn get_headers(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.get_auth_header(&req.connector_auth_type)
}
fn get_content_type(&self) -> &'static str {
"application/json"
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/reports/dtrPaymentStatus/{}",
connectors.worldpayvantiv.secondary_base_url.to_owned(),
req.request.connector_transaction_id
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: worldpayvantiv::VantivSyncResponse = res
.response
.parse_struct("VantivSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
handle_vantiv_json_error_response(res, event_builder)
}
}
impl Dispute for Worldpayvantiv {}
impl FetchDisputes for Worldpayvantiv {}
impl DisputeSync for Worldpayvantiv {}
impl SubmitEvidence for Worldpayvantiv {}
impl AcceptDispute for Worldpayvantiv {}
impl ConnectorIntegration<Fetch, FetchDisputesRequestData, FetchDisputesResponse>
for Worldpayvantiv
{
fn get_headers(
&self,
req: &FetchDisputeRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = vec![
(
headers::CONTENT_TYPE.to_string(),
types::FetchDisputesType::get_content_type(self)
.to_string()
.into(),
),
(
headers::ACCEPT.to_string(),
types::FetchDisputesType::get_content_type(self)
.to_string()
.into(),
),
];
let mut auth_header = self.get_auth_header(&req.connector_auth_type)?;
headers.append(&mut auth_header);
Ok(headers)
}
fn get_content_type(&self) -> &'static str {
"application/com.vantivcnp.services-v2+xml"
}
fn get_url(
&self,
req: &FetchDisputeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let date = req.request.created_from.date();
let day = date.day();
let month = u8::from(date.month());
let year = date.year();
Ok(format!(
"{}/services/chargebacks/?date={year}-{month}-{day}",
connectors.worldpayvantiv.third_base_url.to_owned()
))
}
fn build_request(
&self,
req: &FetchDisputeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Get)
.url(&types::FetchDisputesType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::FetchDisputesType::get_headers(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &FetchDisputeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<FetchDisputeRouterData, errors::ConnectorError> {
let response: worldpayvantiv::ChargebackRetrievalResponse =
connector_utils::deserialize_xml_to_struct(&res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
handle_vantiv_dispute_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Dsync, DisputeSyncData, DisputeSyncResponse> for Worldpayvantiv {
fn get_headers(
&self,
req: &DisputeSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = vec![
(
headers::CONTENT_TYPE.to_string(),
types::FetchDisputesType::get_content_type(self)
.to_string()
.into(),
),
(
headers::ACCEPT.to_string(),
types::FetchDisputesType::get_content_type(self)
.to_string()
.into(),
),
];
let mut auth_header = self.get_auth_header(&req.connector_auth_type)?;
headers.append(&mut auth_header);
Ok(headers)
}
fn get_url(
&self,
req: &DisputeSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/services/chargebacks/{}",
connectors.worldpayvantiv.third_base_url.to_owned(),
req.request.connector_dispute_id
))
}
fn build_request(
&self,
req: &DisputeSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Get)
.url(&types::DisputeSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::DisputeSyncType::get_headers(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &DisputeSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<DisputeSyncRouterData, errors::ConnectorError> {
let response: worldpayvantiv::ChargebackRetrievalResponse =
connector_utils::deserialize_xml_to_struct(&res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
handle_vantiv_dispute_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Evidence, SubmitEvidenceRequestData, SubmitEvidenceResponse>
for Worldpayvantiv
{
fn get_headers(
&self,
req: &SubmitEvidenceRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = vec![
(
headers::CONTENT_TYPE.to_string(),
types::FetchDisputesType::get_content_type(self)
.to_string()
.into(),
),
(
headers::ACCEPT.to_string(),
types::FetchDisputesType::get_content_type(self)
.to_string()
.into(),
),
];
let mut auth_header = self.get_auth_header(&req.connector_auth_type)?;
headers.append(&mut auth_header);
Ok(headers)
}
fn get_url(
&self,
req: &SubmitEvidenceRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/services/chargebacks/{}",
connectors.worldpayvantiv.third_base_url.to_owned(),
req.request.connector_dispute_id
))
}
fn get_request_body(
&self,
req: &SubmitEvidenceRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req_object = worldpayvantiv::ChargebackUpdateRequest::from(req);
router_env::logger::info!(raw_connector_request=?connector_req_object);
let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes(
&connector_req_object,
worldpayvantiv::worldpayvantiv_constants::XML_VERSION,
Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING),
None,
None,
)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &SubmitEvidenceRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Put)
.url(&types::SubmitEvidenceType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::SubmitEvidenceType::get_headers(
self, req, connectors,
)?)
.set_body(types::SubmitEvidenceType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &SubmitEvidenceRouterData,
_event_builder: Option<&mut ConnectorEvent>,
_res: Response,
) -> CustomResult<SubmitEvidenceRouterData, errors::ConnectorError> {
Ok(SubmitEvidenceRouterData {
response: Ok(SubmitEvidenceResponse {
dispute_status: data.request.dispute_status,
connector_status: None,
}),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
handle_vantiv_dispute_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Accept, AcceptDisputeRequestData, AcceptDisputeResponse>
for Worldpayvantiv
{
fn get_headers(
&self,
req: &AcceptDisputeRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = vec![
(
headers::CONTENT_TYPE.to_string(),
types::FetchDisputesType::get_content_type(self)
.to_string()
.into(),
),
(
headers::ACCEPT.to_string(),
types::FetchDisputesType::get_content_type(self)
.to_string()
.into(),
),
];
let mut auth_header = self.get_auth_header(&req.connector_auth_type)?;
headers.append(&mut auth_header);
Ok(headers)
}
fn get_url(
&self,
req: &AcceptDisputeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/services/chargebacks/{}",
connectors.worldpayvantiv.third_base_url.to_owned(),
req.request.connector_dispute_id
))
}
fn get_request_body(
&self,
req: &AcceptDisputeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req_object = worldpayvantiv::ChargebackUpdateRequest::from(req);
router_env::logger::info!(raw_connector_request=?connector_req_object);
let connector_req = connector_utils::XmlSerializer::serialize_to_xml_bytes(
&connector_req_object,
worldpayvantiv::worldpayvantiv_constants::XML_VERSION,
Some(worldpayvantiv::worldpayvantiv_constants::XML_ENCODING),
Some(worldpayvantiv::worldpayvantiv_constants::XML_STANDALONE),
None,
)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &AcceptDisputeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Put)
.url(&types::AcceptDisputeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::AcceptDisputeType::get_headers(
self, req, connectors,
)?)
.set_body(types::AcceptDisputeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &AcceptDisputeRouterData,
_event_builder: Option<&mut ConnectorEvent>,
_res: Response,
) -> CustomResult<AcceptDisputeRouterData, errors::ConnectorError> {
Ok(AcceptDisputeRouterData {
response: Ok(AcceptDisputeResponse {
dispute_status: data.request.dispute_status,
connector_status: None,
}),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
handle_vantiv_dispute_error_response(res, event_builder)
}
}
impl UploadFile for Worldpayvantiv {}
impl ConnectorIntegration<Upload, UploadFileRequestData, UploadFileResponse> for Worldpayvantiv {
fn get_headers(
&self,
req: &RouterData<Upload, UploadFileRequestData, UploadFileResponse>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = vec![(
headers::CONTENT_TYPE.to_string(),
req.request.file_type.to_string().into(),
)];
let mut auth_header = self.get_auth_header(&req.connector_auth_type)?;
headers.append(&mut auth_header);
Ok(headers)
}
fn get_url(
&self,
req: &UploadFileRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let file_type = if req.request.file_type == mime::IMAGE_GIF {
"gif"
} else if req.request.file_type == mime::IMAGE_JPEG {
"jpeg"
} else if req.request.file_type == mime::IMAGE_PNG {
"png"
} else if req.request.file_type == mime::APPLICATION_PDF {
"pdf"
} else {
return Err(errors::ConnectorError::FileValidationFailed {
reason: "file_type does not match JPEG, JPG, PNG, or PDF format".to_owned(),
})?;
};
let file_name = req.request.file_key.split('/').next_back().ok_or(
errors::ConnectorError::RequestEncodingFailedWithReason(
"Failed fetching file_id from file_key".to_string(),
),
)?;
Ok(format!(
"{}/services/chargebacks/upload/{}/{file_name}.{file_type}",
connectors.worldpayvantiv.third_base_url.to_owned(),
req.request.connector_dispute_id,
))
}
fn get_request_body(
&self,
req: &UploadFileRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Ok(RequestContent::RawBytes(req.request.file.clone()))
}
fn build_request(
&self,
req: &UploadFileRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::UploadFileType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::UploadFileType::get_headers(self, req, connectors)?)
.set_body(types::UploadFileType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &UploadFileRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<Upload, UploadFileRequestData, UploadFileResponse>,
errors::ConnectorError,
> {
let response: worldpayvantiv::ChargebackDocumentUploadResponse =
connector_utils::deserialize_xml_to_struct(&res.response)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
handle_vantiv_dispute_error_response(res, event_builder)
}
}
impl RetrieveFile for Worldpayvantiv {}
impl ConnectorIntegration<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>
for Worldpayvantiv
{
fn get_headers(
&self,
req: &RouterData<Retrieve, RetrieveFileRequestData, RetrieveFileResponse>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.get_auth_header(&req.connector_auth_type)
}
fn get_url(
&self,
req: &RetrieveFileRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_dispute_id = req.request.connector_dispute_id.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "dispute_id",
},
)?;
Ok(format!(
"{}/services/chargebacks/retrieve/{connector_dispute_id}/{}",
connectors.worldpayvantiv.third_base_url.to_owned(),
req.request.provider_file_id,
))
}
fn build_request(
&self,
req: &RetrieveFileRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RetrieveFileType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RetrieveFileType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RetrieveFileRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RetrieveFileRouterData, errors::ConnectorError> {
let response: Result<worldpayvantiv::ChargebackDocumentUploadResponse, _> =
connector_utils::deserialize_xml_to_struct(&res.response);
match response {
Ok(response) => {
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
Err(_) => {
event_builder.map(|event| event.set_response_body(&serde_json::json!({"connector_response_type": "file", "status_code": res.status_code})));
router_env::logger::info!(connector_response_type=?"file");
let response = res.response;
Ok(RetrieveFileRouterData {
response: Ok(RetrieveFileResponse {
file_data: response.to_vec(),
}),
..data.clone()
})
}
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
handle_vantiv_dispute_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Worldpayvantiv {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
fn handle_vantiv_json_error_response(
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<worldpayvantiv::VantivSyncErrorResponse, _> = res
.response
.parse_struct("VantivSyncErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed);
match response {
Ok(response_data) => {
event_builder.map(|i| i.set_response_body(&response_data));
router_env::logger::info!(connector_response=?response_data);
let error_reason = response_data.error_messages.join(" & ");
Ok(ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_string(),
message: error_reason.clone(),
reason: Some(error_reason.clone()),
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Err(error_msg) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
router_env::logger::error!(deserialization_error =? error_msg);
connector_utils::handle_json_response_deserialization_failure(res, "worldpayvantiv")
}
}
}
fn handle_vantiv_dispute_error_response(
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<worldpayvantiv::VantivDisputeErrorResponse, _> =
connector_utils::deserialize_xml_to_struct::<worldpayvantiv::VantivDisputeErrorResponse>(
&res.response,
);
match response {
Ok(response_data) => {
event_builder.map(|i| i.set_response_body(&response_data));
router_env::logger::info!(connector_response=?response_data);
let error_reason = response_data
.errors
.iter()
.map(|error_info| error_info.error.clone())
.collect::<Vec<String>>()
.join(" & ");
Ok(ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_string(),
message: error_reason.clone(),
reason: Some(error_reason.clone()),
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
}
Err(error_msg) => {
event_builder.map(|event| event.set_error(serde_json::json!({"error": res.response.escape_ascii().to_string(), "status_code": res.status_code})));
router_env::logger::error!(deserialization_error =? error_msg);
connector_utils::handle_json_response_deserialization_failure(res, "worldpayvantiv")
}
}
}
#[async_trait::async_trait]
impl FileUpload for Worldpayvantiv {
fn validate_file_upload(
&self,
purpose: FilePurpose,
file_size: i32,
file_type: mime::Mime,
) -> CustomResult<(), errors::ConnectorError> {
match purpose {
FilePurpose::DisputeEvidence => {
let supported_file_types = [
"image/gif",
"image/jpeg",
"image/jpg",
"application/pdf",
"image/png",
"image/tiff",
];
if file_size > 2000000 {
Err(errors::ConnectorError::FileValidationFailed {
reason: "file_size exceeded the max file size of 2MB".to_owned(),
})?
}
if !supported_file_types.contains(&file_type.to_string().as_str()) {
Err(errors::ConnectorError::FileValidationFailed {
reason: "file_type does not match JPEG, JPG, PNG, or PDF format".to_owned(),
})?
}
}
}
Ok(())
}
}
static WORLDPAYVANTIV_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
common_enums::CaptureMethod::Automatic,
common_enums::CaptureMethod::Manual,
common_enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Discover,
];
let mut worldpayvantiv_supported_payment_methods = SupportedPaymentMethods::new();
worldpayvantiv_supported_payment_methods.add(
common_enums::PaymentMethod::Card,
common_enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
worldpayvantiv_supported_payment_methods.add(
common_enums::PaymentMethod::Card,
common_enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
#[cfg(feature = "v2")]
worldpayvantiv_supported_payment_methods.add(
common_enums::PaymentMethod::Card,
common_enums::PaymentMethodType::Card,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
worldpayvantiv_supported_payment_methods.add(
common_enums::PaymentMethod::Wallet,
common_enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
worldpayvantiv_supported_payment_methods.add(
common_enums::PaymentMethod::Wallet,
common_enums::PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
worldpayvantiv_supported_payment_methods
});
static WORLDPAYVANTIV_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Worldpay Vantiv",
description: "Worldpay Vantiv, also known as the Worldpay CNP API, is a robust XML-based interface used to process online (card-not-present) transactions such as e-commerce purchases, subscription billing, and digital payments",
connector_type: common_enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: common_enums::ConnectorIntegrationStatus::Sandbox,
};
static WORLDPAYVANTIV_SUPPORTED_WEBHOOK_FLOWS: [common_enums::EventClass; 0] = [];
impl ConnectorSpecifications for Worldpayvantiv {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&WORLDPAYVANTIV_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*WORLDPAYVANTIV_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::EventClass]> {
Some(&WORLDPAYVANTIV_SUPPORTED_WEBHOOK_FLOWS)
}
#[cfg(feature = "v1")]
fn generate_connector_request_reference_id(
&self,
payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
is_config_enabled_to_send_payment_id_as_connector_request_id: bool,
) -> String {
if is_config_enabled_to_send_payment_id_as_connector_request_id
&& payment_intent.is_payment_id_from_merchant.unwrap_or(false)
{
payment_attempt.payment_id.get_string_repr().to_owned()
} else {
let max_payment_reference_id_length =
worldpayvantiv::worldpayvantiv_constants::MAX_PAYMENT_REFERENCE_ID_LENGTH;
nanoid::nanoid!(max_payment_reference_id_length)
}
}
#[cfg(feature = "v2")]
fn generate_connector_request_reference_id(
&self,
payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> String {
if payment_intent.is_payment_id_from_merchant.unwrap_or(false) {
payment_attempt.payment_id.get_string_repr().to_owned()
} else {
connector_utils::generate_12_digit_number().to_string()
}
}
}
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_connectors_6616864874774605404
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_connectors
// File: crates/hyperswitch_connectors/src/connectors/thunes.rs
// Contains: 1 structs, 0 enums
pub mod transformers;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask};
use transformers as thunes;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Thunes {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Thunes {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Thunes {}
impl api::PaymentSession for Thunes {}
impl api::ConnectorAccessToken for Thunes {}
impl api::MandateSetup for Thunes {}
impl api::PaymentAuthorize for Thunes {}
impl api::PaymentSync for Thunes {}
impl api::PaymentCapture for Thunes {}
impl api::PaymentVoid for Thunes {}
impl api::Refund for Thunes {}
impl api::RefundExecute for Thunes {}
impl api::RefundSync for Thunes {}
impl api::PaymentToken for Thunes {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Thunes
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Thunes
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Thunes {
fn id(&self) -> &'static str {
"thunes"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
// TODO! Check connector documentation, on which unit they are processing the currency.
// If the connector accepts amount in lower unit ( i.e cents for USD) then return api::CurrencyUnit::Minor,
// if connector accepts amount in base unit (i.e dollars for USD) then return api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.thunes.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = thunes::ThunesAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.expose().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: thunes::ThunesErrorResponse = res
.response
.parse_struct("ThunesErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
message: response.message,
reason: response.reason,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Thunes {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Thunes {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Thunes {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Thunes {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Thunes {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = thunes::ThunesRouterData::from((amount, req));
let connector_req = thunes::ThunesPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: thunes::ThunesPaymentsResponse = res
.response
.parse_struct("Thunes PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Thunes {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: thunes::ThunesPaymentsResponse = res
.response
.parse_struct("thunes PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Thunes {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: thunes::ThunesPaymentsResponse = res
.response
.parse_struct("Thunes PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Thunes {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Thunes {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = thunes::ThunesRouterData::from((refund_amount, req));
let connector_req = thunes::ThunesRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: thunes::RefundResponse =
res.response
.parse_struct("thunes RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Thunes {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: thunes::RefundResponse = res
.response
.parse_struct("thunes RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Thunes {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static THUNES_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Thunes",
description: "Thunes Payouts is a global payment solution that enables businesses to send instant, secure, and cost-effective cross-border payments to bank accounts, mobile wallets, and cards in over 130 countries using a single API",
connector_type: common_enums::HyperswitchConnectorCategory::PayoutProcessor,
integration_status: common_enums::ConnectorIntegrationStatus::Sandbox,
};
impl ConnectorSpecifications for Thunes {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&THUNES_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
None
}
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> {
None
}
}
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/thunes.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_connectors_-5107081140401864307
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_connectors
// File: crates/hyperswitch_connectors/src/connectors/paysafe.rs
// Contains: 1 structs, 0 enums
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{
Authorize, Capture, CompleteAuthorize, CreateConnectorCustomer, PSync,
PaymentMethodToken, PreProcessing, Session, SetupMandate, Void,
},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, ConnectorCustomerData,
PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData,
PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData,
PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{Mask, PeekInterface};
use transformers as paysafe;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{
self, PaymentMethodDataType, PaymentsAuthorizeRequestData,
PaymentsPreProcessingRequestData, PaymentsSyncRequestData,
RefundsRequestData as OtherRefundsRequestData, RouterData as _,
},
};
#[derive(Clone)]
pub struct Paysafe {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Paysafe {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Paysafe {}
impl api::PaymentSession for Paysafe {}
impl api::ConnectorAccessToken for Paysafe {}
impl api::MandateSetup for Paysafe {}
impl api::PaymentAuthorize for Paysafe {}
impl api::PaymentSync for Paysafe {}
impl api::PaymentCapture for Paysafe {}
impl api::PaymentVoid for Paysafe {}
impl api::Refund for Paysafe {}
impl api::RefundExecute for Paysafe {}
impl api::RefundSync for Paysafe {}
impl api::PaymentToken for Paysafe {}
impl api::ConnectorCustomer for Paysafe {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Paysafe
{
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paysafe
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Paysafe {
fn id(&self) -> &'static str {
"paysafe"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.paysafe.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = paysafe::PaysafeAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_key = format!("{}:{}", auth.username.peek(), auth.password.peek());
let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth_header.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: paysafe::PaysafeErrorResponse = res
.response
.parse_struct("PaysafeErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let detail_message = response
.error
.details
.as_ref()
.and_then(|d| d.first().cloned());
let field_error_message = response
.error
.field_errors
.as_ref()
.and_then(|f| f.first().map(|fe| fe.error.clone()));
let reason = match (detail_message, field_error_message) {
(Some(detail), Some(field)) => Some(format!("{detail}, {field}")),
(Some(detail), None) => Some(detail),
(None, Some(field)) => Some(field),
(None, None) => Some(response.error.message.clone()),
};
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.code,
message: response.error.message,
reason,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Paysafe {
fn validate_psync_reference_id(
&self,
_data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
Ok(())
}
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd = std::collections::HashSet::from([PaymentMethodDataType::Card]);
utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Paysafe {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Paysafe {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Paysafe {
// Not Implemented (R)
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Paysafe".to_string())
.into(),
)
}
}
impl api::PaymentsPreProcessing for Paysafe {}
impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
for Paysafe
{
fn get_headers(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let base_url = self.base_url(connectors);
if req.request.is_customer_initiated_mandate_payment() {
let customer_id = req.get_connector_customer_id()?.to_string();
Ok(format!(
"{base_url}v1/customers/{customer_id}/paymenthandles"
))
} else {
Ok(format!("{}v1/paymenthandles", self.base_url(connectors)))
}
}
fn get_request_body(
&self,
req: &PaymentsPreProcessingRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_amount =
req.request
.minor_amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "minor_amount",
})?;
let currency =
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
let amount = utils::convert_amount(self.amount_converter, minor_amount, currency)?;
let connector_router_data = paysafe::PaysafeRouterData::from((amount, req));
let connector_req = paysafe::PaysafePaymentHandleRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsPreProcessingType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsPreProcessingType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsPreProcessingType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsPreProcessingRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: paysafe::PaysafePaymentHandleResponse = res
.response
.parse_struct("PaysafePaymentHandleResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>
for Paysafe
{
fn get_headers(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v1/customers", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &ConnectorCustomerRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = paysafe::PaysafeCustomerDetails::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::ConnectorCustomerType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::ConnectorCustomerType::get_headers(
self, req, connectors,
)?)
.set_body(types::ConnectorCustomerType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &ConnectorCustomerRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<ConnectorCustomerRouterData, errors::ConnectorError>
where
PaymentsResponseData: Clone,
{
let response: paysafe::PaysafeCustomerResponse = res
.response
.parse_struct("Paysafe PaysafeCustomerResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paysafe {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
match req.payment_method {
enums::PaymentMethod::Card if !req.is_three_ds() => {
Ok(format!("{}v1/payments", self.base_url(connectors)))
}
enums::PaymentMethod::Wallet
if req.request.payment_method_type == Some(enums::PaymentMethodType::ApplePay) =>
{
Ok(format!("{}v1/payments", self.base_url(connectors)))
}
_ => Ok(format!("{}v1/paymenthandles", self.base_url(connectors),)),
}
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = paysafe::PaysafeRouterData::from((amount, req));
match req.payment_method {
//Card No 3DS
enums::PaymentMethod::Card
if !req.is_three_ds() || req.request.get_connector_mandate_id().is_ok() =>
{
let connector_req =
paysafe::PaysafePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
enums::PaymentMethod::Wallet
if req.request.payment_method_type == Some(enums::PaymentMethodType::ApplePay) =>
{
let connector_req =
paysafe::PaysafePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
_ => {
let connector_req =
paysafe::PaysafePaymentHandleRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
}
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
match data.payment_method {
enums::PaymentMethod::Card if !data.is_three_ds() => {
let response: paysafe::PaysafePaymentsResponse = res
.response
.parse_struct("Paysafe PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
enums::PaymentMethod::Wallet
if data.request.payment_method_type == Some(enums::PaymentMethodType::ApplePay) =>
{
let response: paysafe::PaysafePaymentsResponse = res
.response
.parse_struct("Paysafe PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
_ => {
let response: paysafe::PaysafePaymentHandleResponse = res
.response
.parse_struct("Paysafe PaymentHandleResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::PaymentsCompleteAuthorize for Paysafe {}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Paysafe
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}v1/payments", self.base_url(connectors),))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = paysafe::PaysafeRouterData::from((amount, req));
let connector_req = paysafe::PaysafePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: paysafe::PaysafePaymentsResponse = res
.response
.parse_struct("Paysafe PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Paysafe {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.connector_request_reference_id.clone();
let connector_transaction_id = req.request.get_optional_connector_transaction_id();
let base_url = self.base_url(connectors);
let url = if connector_transaction_id.is_some() {
format!("{base_url}v1/payments?merchantRefNum={connector_payment_id}")
} else {
format!("{base_url}v1/paymenthandles?merchantRefNum={connector_payment_id}")
};
Ok(url)
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: paysafe::PaysafeSyncResponse = res
.response
.parse_struct("paysafe PaysafeSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Paysafe {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}v1/payments/{}/settlements",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = paysafe::PaysafeRouterData::from((amount, req));
let connector_req = paysafe::PaysafeCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: paysafe::PaysafeSettlementResponse = res
.response
.parse_struct("PaysafeSettlementResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Paysafe {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}v1/payments/{}/voidauths",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_amount =
req.request
.minor_amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "minor_amount",
})?;
let currency =
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
let amount = utils::convert_amount(self.amount_converter, minor_amount, currency)?;
let connector_router_data = paysafe::PaysafeRouterData::from((amount, req));
let connector_req = paysafe::PaysafeCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsVoidType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: paysafe::VoidResponse = res
.response
.parse_struct("PaysafeVoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paysafe {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}v1/settlements/{}/refunds",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = paysafe::PaysafeRouterData::from((refund_amount, req));
let connector_req = paysafe::PaysafeRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: paysafe::RefundResponse = res
.response
.parse_struct("paysafe RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Paysafe {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}v1/refunds/{}",
self.base_url(connectors),
connector_refund_id
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: paysafe::RefundResponse = res
.response
.parse_struct("paysafe RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Paysafe {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static PAYSAFE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
];
let supported_capture_methods2 = vec![enums::CaptureMethod::Automatic];
let supported_card_network = vec![
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::UnionPay,
];
let mut paysafe_supported_payment_methods = SupportedPaymentMethods::new();
paysafe_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
paysafe_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
paysafe_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
paysafe_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Skrill,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods2.clone(),
specific_features: None,
},
);
paysafe_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Interac,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods2.clone(),
specific_features: None,
},
);
paysafe_supported_payment_methods.add(
enums::PaymentMethod::GiftCard,
enums::PaymentMethodType::PaySafeCard,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods2.clone(),
specific_features: None,
},
);
paysafe_supported_payment_methods
});
static PAYSAFE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Paysafe",
description: "Paysafe gives ambitious businesses a launchpad with safe, secure online payment solutions, and gives consumers the ability to turn their transactions into meaningful experiences.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static PAYSAFE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Paysafe {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&PAYSAFE_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*PAYSAFE_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&PAYSAFE_SUPPORTED_WEBHOOK_FLOWS)
}
#[cfg(feature = "v1")]
fn should_call_connector_customer(
&self,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> bool {
matches!(
payment_attempt.setup_future_usage_applied,
Some(enums::FutureUsage::OffSession)
) && payment_attempt.customer_acceptance.is_some()
&& matches!(
payment_attempt.payment_method,
Some(enums::PaymentMethod::Card)
)
&& matches!(
payment_attempt.authentication_type,
Some(enums::AuthenticationType::NoThreeDs) | None
)
}
}
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/paysafe.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_connectors_-2869919127720780226
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_connectors
// File: crates/hyperswitch_connectors/src/connectors/nordea.rs
// Contains: 1 structs, 0 enums
mod requests;
mod responses;
pub mod transformers;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts, date_time,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, AccessTokenAuthenticationResponse, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
AccessTokenAuthentication, PreProcessing,
},
router_request_types::{
AccessTokenAuthenticationRequestData, AccessTokenRequestData,
PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData,
PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
AccessTokenAuthenticationRouterData, PaymentsAuthorizeRouterData,
PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefreshTokenRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, AuthenticationTokenType, RefreshTokenType, Response},
webhooks,
};
use lazy_static::lazy_static;
use masking::{ExposeInterface, Mask, PeekInterface, Secret};
use ring::{
digest,
signature::{RsaKeyPair, RSA_PKCS1_SHA256},
};
use transformers::{get_error_data, NordeaAuthType};
use url::Url;
use crate::{
connectors::nordea::{
requests::{
NordeaOAuthExchangeRequest, NordeaOAuthRequest, NordeaPaymentsConfirmRequest,
NordeaPaymentsRequest, NordeaRouterData,
},
responses::{
NordeaOAuthExchangeResponse, NordeaPaymentsConfirmResponse,
NordeaPaymentsInitiateResponse,
},
},
constants::headers,
types::ResponseRouterData,
utils::{self, RouterData as OtherRouterData},
};
#[derive(Clone)]
pub struct Nordea {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
struct SignatureParams<'a> {
content_type: &'a str,
host: &'a str,
path: &'a str,
payload_digest: Option<&'a str>,
date: &'a str,
http_method: Method,
}
impl Nordea {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
pub fn generate_digest(&self, payload: &[u8]) -> String {
let payload_digest = digest::digest(&digest::SHA256, payload);
format!("sha-256={}", consts::BASE64_ENGINE.encode(payload_digest))
}
pub fn generate_digest_from_request(&self, payload: &RequestContent) -> String {
let payload_bytes = match payload {
RequestContent::RawBytes(bytes) => bytes.clone(),
_ => payload.get_inner_value().expose().as_bytes().to_vec(),
};
self.generate_digest(&payload_bytes)
}
fn format_private_key(
&self,
private_key_str: &str,
) -> CustomResult<String, errors::ConnectorError> {
let key = private_key_str.to_string();
// Check if it already has PEM headers
let pem_data =
if key.contains("BEGIN") && key.contains("END") && key.contains("PRIVATE KEY") {
key
} else {
// Remove whitespace and format with 64-char lines
let cleaned_key = key
.chars()
.filter(|c| !c.is_whitespace())
.collect::<String>();
let formatted_key = cleaned_key
.chars()
.collect::<Vec<char>>()
.chunks(64)
.map(|chunk| chunk.iter().collect::<String>())
.collect::<Vec<String>>()
.join("\n");
format!(
"-----BEGIN RSA PRIVATE KEY-----\n{formatted_key}\n-----END RSA PRIVATE KEY-----",
)
};
Ok(pem_data)
}
// For non-production environments, signature generation can be skipped and instead `SKIP_SIGNATURE_VALIDATION_FOR_SANDBOX` can be passed.
fn generate_signature(
&self,
auth: &NordeaAuthType,
signature_params: SignatureParams<'_>,
) -> CustomResult<String, errors::ConnectorError> {
const REQUEST_WITHOUT_CONTENT_HEADERS: &str =
"(request-target) x-nordea-originating-host x-nordea-originating-date";
const REQUEST_WITH_CONTENT_HEADERS: &str = "(request-target) x-nordea-originating-host x-nordea-originating-date content-type digest";
let method_string = signature_params.http_method.to_string().to_lowercase();
let mut normalized_string = format!(
"(request-target): {} {}\nx-nordea-originating-host: {}\nx-nordea-originating-date: {}",
method_string, signature_params.path, signature_params.host, signature_params.date
);
let headers = if matches!(
signature_params.http_method,
Method::Post | Method::Put | Method::Patch
) {
let digest = signature_params.payload_digest.unwrap_or("");
normalized_string.push_str(&format!(
"\ncontent-type: {}\ndigest: {}",
signature_params.content_type, digest
));
REQUEST_WITH_CONTENT_HEADERS
} else {
REQUEST_WITHOUT_CONTENT_HEADERS
};
let signature_base64 = {
let private_key_pem =
self.format_private_key(&auth.eidas_private_key.clone().expose())?;
let private_key_der = pem::parse(&private_key_pem).change_context(
errors::ConnectorError::InvalidConnectorConfig {
config: "eIDAS Private Key",
},
)?;
let private_key_der_contents = private_key_der.contents();
let key_pair = RsaKeyPair::from_der(private_key_der_contents).change_context(
errors::ConnectorError::InvalidConnectorConfig {
config: "eIDAS Private Key",
},
)?;
let mut signature = vec![0u8; key_pair.public().modulus_len()];
key_pair
.sign(
&RSA_PKCS1_SHA256,
&ring::rand::SystemRandom::new(),
normalized_string.as_bytes(),
&mut signature,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
consts::BASE64_ENGINE.encode(signature)
};
Ok(format!(
r#"keyId="{}",algorithm="rsa-sha256",headers="{}",signature="{}""#,
auth.client_id.peek(),
headers,
signature_base64
))
}
// This helper function correctly serializes a struct into the required
// non-percent-encoded form URL string.
fn get_form_urlencoded_payload<T: serde::Serialize>(
&self,
form_data: &T,
) -> Result<Vec<u8>, error_stack::Report<errors::ConnectorError>> {
let json_value = serde_json::to_value(form_data)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let btree_map: std::collections::BTreeMap<String, serde_json::Value> =
serde_json::from_value(json_value)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(btree_map
.iter()
.map(|(k, v)| {
// Remove quotes from string values for proper form encoding
let value = match v {
serde_json::Value::String(s) => s.clone(),
_ => v.to_string(),
};
format!("{k}={value}")
})
.collect::<Vec<_>>()
.join("&")
.into_bytes())
}
}
impl api::Payment for Nordea {}
impl api::PaymentSession for Nordea {}
impl api::ConnectorAuthenticationToken for Nordea {}
impl api::ConnectorAccessToken for Nordea {}
impl api::MandateSetup for Nordea {}
impl api::PaymentAuthorize for Nordea {}
impl api::PaymentSync for Nordea {}
impl api::PaymentCapture for Nordea {}
impl api::PaymentVoid for Nordea {}
impl api::Refund for Nordea {}
impl api::RefundExecute for Nordea {}
impl api::RefundSync for Nordea {}
impl api::PaymentToken for Nordea {}
impl api::PaymentsPreProcessing for Nordea {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Nordea
{
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nordea {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nordea
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let access_token = req
.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let auth = NordeaAuthType::try_from(&req.connector_auth_type)?;
let content_type = self.get_content_type().to_string();
let http_method = self.get_http_method();
// Extract host from base URL
let nordea_host = Url::parse(self.base_url(connectors))
.change_context(errors::ConnectorError::RequestEncodingFailed)?
.host_str()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string();
let nordea_origin_date = date_time::now_rfc7231_http_date()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let full_url = self.get_url(req, connectors)?;
let url_parsed =
Url::parse(&full_url).change_context(errors::ConnectorError::RequestEncodingFailed)?;
let path = url_parsed.path();
let path_with_query = if let Some(query) = url_parsed.query() {
format!("{path}?{query}")
} else {
path.to_string()
};
let mut required_headers = vec![
(
headers::CONTENT_TYPE.to_string(),
content_type.clone().into(),
),
(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", access_token.token.peek()).into_masked(),
),
(
"X-IBM-Client-ID".to_string(),
auth.client_id.clone().expose().into_masked(),
),
(
"X-IBM-Client-Secret".to_string(),
auth.client_secret.clone().expose().into_masked(),
),
(
"X-Nordea-Originating-Date".to_string(),
nordea_origin_date.clone().into_masked(),
),
(
"X-Nordea-Originating-Host".to_string(),
nordea_host.clone().into_masked(),
),
];
if matches!(http_method, Method::Post | Method::Put | Method::Patch) {
let nordea_request = self.get_request_body(req, connectors)?;
let sha256_digest = self.generate_digest_from_request(&nordea_request);
// Add Digest header
required_headers.push((
"Digest".to_string(),
sha256_digest.to_string().into_masked(),
));
let signature = self.generate_signature(
&auth,
SignatureParams {
content_type: &content_type,
host: &nordea_host,
path,
payload_digest: Some(&sha256_digest),
date: &nordea_origin_date,
http_method,
},
)?;
required_headers.push(("Signature".to_string(), signature.into_masked()));
} else {
// Generate signature without digest for GET requests
let signature = self.generate_signature(
&auth,
SignatureParams {
content_type: &content_type,
host: &nordea_host,
path: &path_with_query,
payload_digest: None,
date: &nordea_origin_date,
http_method,
},
)?;
required_headers.push(("Signature".to_string(), signature.into_masked()));
}
Ok(required_headers)
}
}
impl ConnectorCommon for Nordea {
fn id(&self) -> &'static str {
"nordea"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.nordea.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: responses::NordeaErrorResponse = res
.response
.parse_struct("NordeaErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: get_error_data(response.error.as_ref())
.and_then(|failure| failure.code.clone())
.unwrap_or(NO_ERROR_CODE.to_string()),
message: get_error_data(response.error.as_ref())
.and_then(|failure| failure.description.clone())
.unwrap_or(NO_ERROR_MESSAGE.to_string()),
reason: get_error_data(response.error.as_ref())
.and_then(|failure| failure.failure_type.clone()),
attempt_status: None,
connector_transaction_id: None,
network_decline_code: None,
network_advice_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Nordea {}
impl
ConnectorIntegration<
AccessTokenAuthentication,
AccessTokenAuthenticationRequestData,
AccessTokenAuthenticationResponse,
> for Nordea
{
fn get_url(
&self,
_req: &AccessTokenAuthenticationRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/personal/v5/authorize",
self.base_url(connectors)
))
}
fn get_content_type(&self) -> &'static str {
"application/json"
}
fn get_request_body(
&self,
req: &AccessTokenAuthenticationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = NordeaOAuthRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &AccessTokenAuthenticationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let auth = NordeaAuthType::try_from(&req.connector_auth_type)?;
let content_type = self.common_get_content_type().to_string();
let http_method = Method::Post;
// Extract host from base URL
let nordea_host = Url::parse(self.base_url(connectors))
.change_context(errors::ConnectorError::RequestEncodingFailed)?
.host_str()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string();
let nordea_origin_date = date_time::now_rfc7231_http_date()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let full_url = self.get_url(req, connectors)?;
let url_parsed =
Url::parse(&full_url).change_context(errors::ConnectorError::RequestEncodingFailed)?;
let path = url_parsed.path();
let request_body = self.get_request_body(req, connectors)?;
let mut required_headers = vec![
(
headers::CONTENT_TYPE.to_string(),
content_type.clone().into(),
),
(
"X-IBM-Client-ID".to_string(),
auth.client_id.clone().expose().into_masked(),
),
(
"X-IBM-Client-Secret".to_string(),
auth.client_secret.clone().expose().into_masked(),
),
(
"X-Nordea-Originating-Date".to_string(),
nordea_origin_date.clone().into_masked(),
),
(
"X-Nordea-Originating-Host".to_string(),
nordea_host.clone().into_masked(),
),
];
let sha256_digest = self.generate_digest_from_request(&request_body);
// Add Digest header
required_headers.push((
"Digest".to_string(),
sha256_digest.to_string().into_masked(),
));
let signature = self.generate_signature(
&auth,
SignatureParams {
content_type: &content_type,
host: &nordea_host,
path,
payload_digest: Some(&sha256_digest),
date: &nordea_origin_date,
http_method,
},
)?;
required_headers.push(("Signature".to_string(), signature.into_masked()));
let request = Some(
RequestBuilder::new()
.method(http_method)
.attach_default_headers()
.headers(required_headers)
.url(&AuthenticationTokenType::get_url(self, req, connectors)?)
.set_body(request_body)
.build(),
);
Ok(request)
}
fn handle_response(
&self,
data: &AccessTokenAuthenticationRouterData,
_event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<AccessTokenAuthenticationRouterData, errors::ConnectorError> {
// Handle 302 redirect response
if res.status_code == 302 {
// Extract Location header
let headers =
res.headers
.as_ref()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "headers",
})?;
let location_header = headers
.get("Location")
.map(|value| value.to_str())
.and_then(|location_value| location_value.ok())
.ok_or(errors::ConnectorError::ParsingFailed)?;
// Parse auth code from query params
let url = Url::parse(location_header)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let code = url
.query_pairs()
.find(|(key, _)| key == "code")
.map(|(_, value)| value.to_string())
.ok_or(errors::ConnectorError::MissingRequiredField { field_name: "code" })?;
// Return auth code as "token" with short expiry
Ok(RouterData {
response: Ok(AccessTokenAuthenticationResponse {
code: Secret::new(code),
expires: 60, // 60 seconds - auth code validity
}),
..data.clone()
})
} else {
Err(
errors::ConnectorError::UnexpectedResponseError("Expected 302 redirect".into())
.into(),
)
}
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nordea {
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/personal/v5/authorize/token",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = NordeaOAuthExchangeRequest::try_from(req)?;
let body_bytes = self.get_form_urlencoded_payload(&Box::new(connector_req))?;
Ok(RequestContent::RawBytes(body_bytes))
}
fn build_request(
&self,
req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
// For the OAuth token exchange request, we don't have a bearer token yet
// We're exchanging the auth code for an access token
let auth = NordeaAuthType::try_from(&req.connector_auth_type)?;
let content_type = "application/x-www-form-urlencoded".to_string();
let http_method = Method::Post;
// Extract host from base URL
let nordea_host = Url::parse(self.base_url(connectors))
.change_context(errors::ConnectorError::RequestEncodingFailed)?
.host_str()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?
.to_string();
let nordea_origin_date = date_time::now_rfc7231_http_date()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let full_url = self.get_url(req, connectors)?;
let url_parsed =
Url::parse(&full_url).change_context(errors::ConnectorError::RequestEncodingFailed)?;
let path = url_parsed.path();
let request_body = self.get_request_body(req, connectors)?;
let mut required_headers = vec![
(
headers::CONTENT_TYPE.to_string(),
content_type.clone().into(),
),
(
"X-IBM-Client-ID".to_string(),
auth.client_id.clone().expose().into_masked(),
),
(
"X-IBM-Client-Secret".to_string(),
auth.client_secret.clone().expose().into_masked(),
),
(
"X-Nordea-Originating-Date".to_string(),
nordea_origin_date.clone().into_masked(),
),
(
"X-Nordea-Originating-Host".to_string(),
nordea_host.clone().into_masked(),
),
];
let sha256_digest = self.generate_digest_from_request(&request_body);
// Add Digest header
required_headers.push((
"Digest".to_string(),
sha256_digest.to_string().into_masked(),
));
let signature = self.generate_signature(
&auth,
SignatureParams {
content_type: &content_type,
host: &nordea_host,
path,
payload_digest: Some(&sha256_digest),
date: &nordea_origin_date,
http_method,
},
)?;
required_headers.push(("Signature".to_string(), signature.into_masked()));
let request = Some(
RequestBuilder::new()
.method(http_method)
.attach_default_headers()
.headers(required_headers)
.url(&RefreshTokenType::get_url(self, req, connectors)?)
.set_body(request_body)
.build(),
);
Ok(request)
}
fn handle_response(
&self,
data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: NordeaOAuthExchangeResponse = res
.response
.parse_struct("NordeaOAuthExchangeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Nordea {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Nordea".to_string())
.into(),
)
}
}
impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
for Nordea
{
fn get_headers(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
// Determine the payment endpoint based on country and currency
let country = req.get_billing_country()?;
let currency =
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
let endpoint = match (country, currency) {
(api_models::enums::CountryAlpha2::FI, api_models::enums::Currency::EUR) => {
"/personal/v5/payments/sepa-credit-transfers"
}
(api_models::enums::CountryAlpha2::DK, api_models::enums::Currency::DKK) => {
"/personal/v5/payments/domestic-credit-transfers"
}
(
api_models::enums::CountryAlpha2::FI
| api_models::enums::CountryAlpha2::DK
| api_models::enums::CountryAlpha2::SE
| api_models::enums::CountryAlpha2::NO,
_,
) => "/personal/v5/payments/cross-border-credit-transfers",
_ => {
return Err(errors::ConnectorError::NotSupported {
message: format!("Country {country:?} is not supported by Nordea"),
connector: "Nordea",
}
.into())
}
};
Ok(format!("{}{}", self.base_url(connectors), endpoint))
}
fn get_request_body(
&self,
req: &PaymentsPreProcessingRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_amount =
req.request
.minor_amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "minor_amount",
})?;
let currency =
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?;
let amount = utils::convert_amount(self.amount_converter, minor_amount, currency)?;
let connector_router_data = NordeaRouterData::from((amount, req));
let connector_req = NordeaPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsPreProcessingType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsPreProcessingType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsPreProcessingType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsPreProcessingRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: NordeaPaymentsInitiateResponse = res
.response
.parse_struct("NordeaPaymentsInitiateResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nordea {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_http_method(&self) -> Method {
Method::Put
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(_connectors),
"/personal/v5/payments"
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = NordeaRouterData::from((amount, req));
let connector_req = NordeaPaymentsConfirmRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(types::PaymentsAuthorizeType::get_http_method(self))
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: NordeaPaymentsConfirmResponse = res
.response
.parse_struct("NordeaPaymentsConfirmResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nordea {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let id = req.request.connector_transaction_id.clone();
let connector_transaction_id = id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}{}{}",
self.base_url(_connectors),
"/personal/v5/payments/",
connector_transaction_id
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(types::PaymentsSyncType::get_http_method(self))
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: NordeaPaymentsInitiateResponse = res
.response
.parse_struct("NordeaPaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nordea {
fn build_request(
&self,
_req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "Capture".to_string(),
connector: "Nordea",
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nordea {
fn build_request(
&self,
_req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "Payments Cancel".to_string(),
connector: "Nordea",
}
.into())
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nordea {
fn build_request(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "Personal API Refunds flow".to_string(),
connector: "Nordea",
}
.into())
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nordea {
// Default impl gets executed
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Nordea {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
lazy_static! {
static ref NORDEA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name:
"Nordea",
description:
"Nordea is one of the leading financial services group in the Nordics and the preferred choice for millions across the region.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: common_enums::ConnectorIntegrationStatus::Beta,
};
static ref NORDEA_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let nordea_supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::SequentialAutomatic,
];
let mut nordea_supported_payment_methods = SupportedPaymentMethods::new();
nordea_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
enums::PaymentMethodType::Sepa,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
// Supported only in corporate API (corporate accounts)
refunds: common_enums::FeatureStatus::NotSupported,
supported_capture_methods: nordea_supported_capture_methods.clone(),
specific_features: None,
},
);
nordea_supported_payment_methods
};
static ref NORDEA_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
}
impl ConnectorSpecifications for Nordea {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*NORDEA_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*NORDEA_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*NORDEA_SUPPORTED_WEBHOOK_FLOWS)
}
fn authentication_token_for_token_creation(&self) -> bool {
// Nordea requires authentication token for access token creation
true
}
}
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/nordea.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_connectors_-570032208230916105
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_connectors
// File: crates/hyperswitch_connectors/src/connectors/adyenplatform.rs
// Contains: 1 structs, 0 enums
pub mod transformers;
use api_models::{self, webhooks::IncomingWebhookEvent};
#[cfg(feature = "payouts")]
use base64::Engine;
#[cfg(feature = "payouts")]
use common_utils::crypto;
use common_utils::errors::CustomResult;
#[cfg(feature = "payouts")]
use common_utils::ext_traits::{ByteSliceExt as _, BytesExt};
#[cfg(feature = "payouts")]
use common_utils::request::RequestContent;
#[cfg(feature = "payouts")]
use common_utils::request::{Method, Request, RequestBuilder};
#[cfg(feature = "payouts")]
use common_utils::types::MinorUnitForConnector;
#[cfg(feature = "payouts")]
use common_utils::types::{AmountConvertor, MinorUnit};
#[cfg(not(feature = "payouts"))]
use error_stack::report;
use error_stack::ResultExt;
#[cfg(feature = "payouts")]
use http::HeaderName;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::router_data::{ErrorResponse, RouterData};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::router_flow_types::PoFulfill;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::types::{PayoutsData, PayoutsResponseData, PayoutsRouterData};
use hyperswitch_domain_models::{
api::ApplicationResponse,
router_data::{AccessToken, ConnectorAuthType},
router_flow_types::{
AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session,
SetupMandate, Void,
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::events::connector_api_logs::ConnectorEvent;
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::types::{PayoutFulfillType, Response};
use hyperswitch_interfaces::{
api::{self, ConnectorCommon, ConnectorIntegration, ConnectorSpecifications},
configs::Connectors,
errors::ConnectorError,
webhooks::{IncomingWebhook, IncomingWebhookFlowError, IncomingWebhookRequestDetails},
};
use masking::{Mask as _, Maskable, Secret};
#[cfg(feature = "payouts")]
use ring::hmac;
#[cfg(feature = "payouts")]
use router_env::{instrument, tracing};
#[cfg(feature = "payouts")]
use transformers::get_adyen_payout_webhook_event;
use self::transformers as adyenplatform;
use crate::constants::headers;
#[cfg(feature = "payouts")]
use crate::types::ResponseRouterData;
#[cfg(feature = "payouts")]
use crate::utils::convert_amount;
#[derive(Clone)]
pub struct Adyenplatform {
#[cfg(feature = "payouts")]
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Adyenplatform {
pub const fn new() -> &'static Self {
&Self {
#[cfg(feature = "payouts")]
amount_converter: &MinorUnitForConnector,
}
}
}
impl ConnectorCommon for Adyenplatform {
fn id(&self) -> &'static str {
"adyenplatform"
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let auth = adyenplatform::AdyenplatformAuthType::try_from(auth_type)
.change_context(ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.into_masked(),
)])
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.adyenplatform.base_url.as_ref()
}
#[cfg(feature = "payouts")]
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
let response: adyenplatform::AdyenTransferErrorResponse = res
.response
.parse_struct("AdyenTransferErrorResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let message = if let Some(invalid_fields) = &response.invalid_fields {
match serde_json::to_string(invalid_fields) {
Ok(invalid_fields_json) => format!(
"{}\nInvalid fields: {}",
response.title, invalid_fields_json
),
Err(_) => response.title.clone(),
}
} else if let Some(detail) = &response.detail {
format!("{}\nDetail: {}", response.title, detail)
} else {
response.title.clone()
};
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_code,
message,
reason: response.detail,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl api::Payment for Adyenplatform {}
impl api::PaymentAuthorize for Adyenplatform {}
impl api::PaymentSync for Adyenplatform {}
impl api::PaymentVoid for Adyenplatform {}
impl api::PaymentCapture for Adyenplatform {}
impl api::MandateSetup for Adyenplatform {}
impl api::ConnectorAccessToken for Adyenplatform {}
impl api::PaymentToken for Adyenplatform {}
impl api::ConnectorValidation for Adyenplatform {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Adyenplatform
{
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Adyenplatform {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Adyenplatform
{
}
impl api::PaymentSession for Adyenplatform {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Adyenplatform {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Adyenplatform {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Adyenplatform {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for Adyenplatform
{
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Adyenplatform {}
impl api::Payouts for Adyenplatform {}
#[cfg(feature = "payouts")]
impl api::PayoutFulfill for Adyenplatform {}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Adyenplatform {
fn get_url(
&self,
_req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!(
"{}btl/v4/transfers",
connectors.adyenplatform.base_url,
))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoFulfill>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
PayoutFulfillType::get_content_type(self).to_string().into(),
)];
let auth = adyenplatform::AdyenplatformAuthType::try_from(&req.connector_auth_type)
.change_context(ConnectorError::FailedToObtainAuthType)?;
let mut api_key = vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.into_masked(),
)];
header.append(&mut api_key);
Ok(header)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoFulfill>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.destination_currency,
)?;
let connector_router_data =
adyenplatform::AdyenPlatformRouterData::try_from((amount, req))?;
let connector_req = adyenplatform::AdyenTransferRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutFulfillType::get_headers(self, req, connectors)?)
.set_body(PayoutFulfillType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoFulfill>, ConnectorError> {
let response: adyenplatform::AdyenTransferResponse = res
.response
.parse_struct("AdyenTransferResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl api::Refund for Adyenplatform {}
impl api::RefundExecute for Adyenplatform {}
impl api::RefundSync for Adyenplatform {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Adyenplatform {}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Adyenplatform {}
#[async_trait::async_trait]
impl IncomingWebhook for Adyenplatform {
#[cfg(feature = "payouts")]
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
#[cfg(feature = "payouts")]
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, ConnectorError> {
let base64_signature = request
.headers
.get(HeaderName::from_static("hmacsignature"))
.ok_or(ConnectorError::WebhookSourceVerificationFailed)?;
Ok(base64_signature.as_bytes().to_vec())
}
#[cfg(feature = "payouts")]
fn get_webhook_source_verification_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, ConnectorError> {
Ok(request.body.to_vec())
}
#[cfg(feature = "payouts")]
async fn verify_webhook_source(
&self,
request: &IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<Secret<serde_json::Value>>,
connector_label: &str,
) -> CustomResult<bool, ConnectorError> {
use common_utils::consts;
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_label,
connector_webhook_details,
)
.await
.change_context(ConnectorError::WebhookSourceVerificationFailed)?;
let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(ConnectorError::WebhookSourceVerificationFailed)?;
let message = self
.get_webhook_source_verification_message(
request,
merchant_id,
&connector_webhook_secrets,
)
.change_context(ConnectorError::WebhookSourceVerificationFailed)?;
let raw_key = hex::decode(connector_webhook_secrets.secret)
.change_context(ConnectorError::WebhookVerificationSecretInvalid)?;
let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &raw_key);
let signed_messaged = hmac::sign(&signing_key, &message);
let payload_sign = consts::BASE64_ENGINE.encode(signed_messaged.as_ref());
Ok(payload_sign.as_bytes().eq(&signature))
}
fn get_webhook_object_reference_id(
&self,
#[cfg(feature = "payouts")] request: &IncomingWebhookRequestDetails<'_>,
#[cfg(not(feature = "payouts"))] _request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> {
#[cfg(feature = "payouts")]
{
let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request
.body
.parse_struct("AdyenplatformIncomingWebhook")
.change_context(ConnectorError::WebhookSourceVerificationFailed)?;
Ok(api_models::webhooks::ObjectReferenceId::PayoutId(
api_models::webhooks::PayoutIdType::PayoutAttemptId(webhook_body.data.reference),
))
}
#[cfg(not(feature = "payouts"))]
{
Err(report!(ConnectorError::WebhooksNotImplemented))
}
}
fn get_webhook_api_response(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
error_kind: Option<IncomingWebhookFlowError>,
) -> CustomResult<ApplicationResponse<serde_json::Value>, ConnectorError> {
if error_kind.is_some() {
Ok(ApplicationResponse::JsonWithHeaders((
serde_json::Value::Null,
vec![(
"x-http-code".to_string(),
Maskable::Masked(Secret::new("404".to_string())),
)],
)))
} else {
Ok(ApplicationResponse::StatusOk)
}
}
fn get_webhook_event_type(
&self,
#[cfg(feature = "payouts")] request: &IncomingWebhookRequestDetails<'_>,
#[cfg(not(feature = "payouts"))] _request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, ConnectorError> {
#[cfg(feature = "payouts")]
{
let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request
.body
.parse_struct("AdyenplatformIncomingWebhook")
.change_context(ConnectorError::WebhookSourceVerificationFailed)?;
Ok(get_adyen_payout_webhook_event(
webhook_body.webhook_type,
webhook_body.data.status,
webhook_body.data.tracking,
))
}
#[cfg(not(feature = "payouts"))]
{
Err(report!(ConnectorError::WebhooksNotImplemented))
}
}
fn get_webhook_resource_object(
&self,
#[cfg(feature = "payouts")] request: &IncomingWebhookRequestDetails<'_>,
#[cfg(not(feature = "payouts"))] _request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> {
#[cfg(feature = "payouts")]
{
let webhook_body: adyenplatform::AdyenplatformIncomingWebhook = request
.body
.parse_struct("AdyenplatformIncomingWebhook")
.change_context(ConnectorError::WebhookSourceVerificationFailed)?;
Ok(Box::new(webhook_body))
}
#[cfg(not(feature = "payouts"))]
{
Err(report!(ConnectorError::WebhooksNotImplemented))
}
}
}
static ADYENPLATFORM_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Adyen Platform",
description: "Adyen Platform for marketplace payouts and disbursements",
connector_type: common_enums::HyperswitchConnectorCategory::PayoutProcessor,
integration_status: common_enums::ConnectorIntegrationStatus::Sandbox,
};
impl ConnectorSpecifications for Adyenplatform {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&ADYENPLATFORM_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
None
}
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> {
None
}
}
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/adyenplatform.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
file_hyperswitch_connectors_-7714593763702651982
|
clm
|
file
|
// Repository: hyperswitch
// Crate: hyperswitch_connectors
// File: crates/hyperswitch_connectors/src/connectors/amazonpay.rs
// Contains: 1 structs, 0 enums
pub mod transformers;
use std::sync::LazyLock;
use base64::{engine::general_purpose::STANDARD, Engine};
use chrono::Utc;
use common_enums::enums;
use common_utils::{
crypto::{RsaPssSha256, SignMessage},
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hex;
use hyperswitch_domain_models::{
payment_method_data::{PaymentMethodData, WalletData as WalletDataPaymentMethod},
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask, Maskable, PeekInterface, Secret};
use sha2::{Digest, Sha256};
use transformers as amazonpay;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, PaymentsSyncRequestData},
};
const SIGNING_ALGO: &str = "AMZN-PAY-RSASSA-PSS-V2";
const HEADER_ACCEPT: &str = "accept";
const HEADER_CONTENT_TYPE: &str = "content-type";
const HEADER_DATE: &str = "x-amz-pay-date";
const HEADER_HOST: &str = "x-amz-pay-host";
const HEADER_IDEMPOTENCY_KEY: &str = "x-amz-pay-idempotency-key";
const HEADER_REGION: &str = "x-amz-pay-region";
const FINALIZE_SEGMENT: &str = "finalize";
const AMAZON_PAY_API_BASE_URL: &str = "https://pay-api.amazon.com";
const AMAZON_PAY_HOST: &str = "pay-api.amazon.com";
#[derive(Clone)]
pub struct Amazonpay {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Amazonpay {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
fn get_last_segment(canonical_uri: &str) -> String {
canonical_uri
.chars()
.rev()
.take_while(|&c| c != '/')
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect()
}
pub fn create_authorization_header(
&self,
auth: amazonpay::AmazonpayAuthType,
canonical_uri: &str,
http_method: &Method,
hashed_payload: &str,
header: &[(String, Maskable<String>)],
) -> String {
let amazonpay::AmazonpayAuthType {
public_key,
private_key,
} = auth;
let mut signed_headers =
format!("{HEADER_ACCEPT};{HEADER_CONTENT_TYPE};{HEADER_DATE};{HEADER_HOST};",);
if *http_method == Method::Post
&& Self::get_last_segment(canonical_uri) != *FINALIZE_SEGMENT.to_string()
{
signed_headers.push_str(HEADER_IDEMPOTENCY_KEY);
signed_headers.push(';');
}
signed_headers.push_str(HEADER_REGION);
format!(
"{} PublicKeyId={}, SignedHeaders={}, Signature={}",
SIGNING_ALGO,
public_key.expose().clone(),
signed_headers,
Self::create_signature(
&private_key,
*http_method,
canonical_uri,
&signed_headers,
hashed_payload,
header
)
.unwrap_or_else(|_| "Invalid signature".to_string())
)
}
fn create_signature(
private_key: &Secret<String>,
http_method: Method,
canonical_uri: &str,
signed_headers: &str,
hashed_payload: &str,
header: &[(String, Maskable<String>)],
) -> Result<String, String> {
let mut canonical_request = http_method.to_string() + "\n" + canonical_uri + "\n\n";
let mut lowercase_sorted_header_keys: Vec<String> =
header.iter().map(|(key, _)| key.to_lowercase()).collect();
lowercase_sorted_header_keys.sort();
for key in lowercase_sorted_header_keys {
if let Some((_, maskable_value)) = header.iter().find(|(k, _)| k.to_lowercase() == key)
{
let value: String = match maskable_value {
Maskable::Normal(v) => v.clone(),
Maskable::Masked(secret) => secret.clone().expose(),
};
canonical_request.push_str(&format!("{key}:{value}\n"));
}
}
canonical_request.push_str(&("\n".to_owned() + signed_headers + "\n" + hashed_payload));
let string_to_sign = format!(
"{}\n{}",
SIGNING_ALGO,
hex::encode(Sha256::digest(canonical_request.as_bytes()))
);
Self::sign(private_key, &string_to_sign)
.map_err(|e| format!("Failed to create signature: {e}"))
}
fn sign(
private_key_pem_str: &Secret<String>,
string_to_sign: &String,
) -> Result<String, String> {
let rsa_pss_sha256_signer = RsaPssSha256;
let signature_bytes = rsa_pss_sha256_signer
.sign_message(
private_key_pem_str.peek().as_bytes(),
string_to_sign.as_bytes(),
)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.map_err(|e| format!("Crypto operation failed: {e:?}"))?;
Ok(STANDARD.encode(signature_bytes))
}
}
impl api::Payment for Amazonpay {}
impl api::PaymentSession for Amazonpay {}
impl api::ConnectorAccessToken for Amazonpay {}
impl api::MandateSetup for Amazonpay {}
impl api::PaymentAuthorize for Amazonpay {}
impl api::PaymentSync for Amazonpay {}
impl api::PaymentCapture for Amazonpay {}
impl api::PaymentVoid for Amazonpay {}
impl api::Refund for Amazonpay {}
impl api::RefundExecute for Amazonpay {}
impl api::RefundSync for Amazonpay {}
impl api::PaymentToken for Amazonpay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Amazonpay
{
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Amazonpay
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let http_method = self.get_http_method();
let canonical_uri: String =
self.get_url(req, connectors)?
.replacen(AMAZON_PAY_API_BASE_URL, "", 1);
let mut header = vec![
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
(
headers::ACCEPT.to_string(),
"application/json".to_string().into(),
),
(
HEADER_DATE.to_string(),
Utc::now()
.format("%Y-%m-%dT%H:%M:%SZ")
.to_string()
.into_masked(),
),
(
HEADER_HOST.to_string(),
AMAZON_PAY_HOST.to_string().into_masked(),
),
(HEADER_REGION.to_string(), "na".to_string().into_masked()),
];
if http_method == Method::Post
&& Self::get_last_segment(&canonical_uri) != *FINALIZE_SEGMENT.to_string()
{
header.push((
HEADER_IDEMPOTENCY_KEY.to_string(),
req.connector_request_reference_id.clone().into_masked(),
));
}
let hashed_payload = if http_method == Method::Get {
hex::encode(Sha256::digest("".as_bytes()))
} else {
hex::encode(Sha256::digest(
self.get_request_body(req, connectors)?
.get_inner_value()
.expose()
.as_bytes(),
))
};
let authorization = self.create_authorization_header(
amazonpay::AmazonpayAuthType::try_from(&req.connector_auth_type)?,
&canonical_uri,
&http_method,
&hashed_payload,
&header,
);
header.push((
headers::AUTHORIZATION.to_string(),
authorization.clone().into_masked(),
));
Ok(header)
}
}
impl ConnectorCommon for Amazonpay {
fn id(&self) -> &'static str {
"amazonpay"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.amazonpay.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: amazonpay::AmazonpayErrorResponse = res
.response
.parse_struct("AmazonpayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.reason_code.clone(),
message: response.message.clone(),
attempt_status: None,
connector_transaction_id: None,
reason: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Amazonpay {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Amazonpay {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Amazonpay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Amazonpay
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Amazonpay {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
match req.request.payment_method_data.clone() {
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletDataPaymentMethod::AmazonPay(ref req_wallet) => Ok(format!(
"{}/checkoutSessions/{}/finalize",
self.base_url(connectors),
req_wallet.checkout_session_id.clone()
)),
WalletDataPaymentMethod::AliPayQr(_)
| WalletDataPaymentMethod::AliPayRedirect(_)
| WalletDataPaymentMethod::AliPayHkRedirect(_)
| WalletDataPaymentMethod::AmazonPayRedirect(_)
| WalletDataPaymentMethod::MomoRedirect(_)
| WalletDataPaymentMethod::KakaoPayRedirect(_)
| WalletDataPaymentMethod::GoPayRedirect(_)
| WalletDataPaymentMethod::GcashRedirect(_)
| WalletDataPaymentMethod::ApplePay(_)
| WalletDataPaymentMethod::ApplePayRedirect(_)
| WalletDataPaymentMethod::ApplePayThirdPartySdk(_)
| WalletDataPaymentMethod::DanaRedirect {}
| WalletDataPaymentMethod::GooglePay(_)
| WalletDataPaymentMethod::GooglePayRedirect(_)
| WalletDataPaymentMethod::GooglePayThirdPartySdk(_)
| WalletDataPaymentMethod::MbWayRedirect(_)
| WalletDataPaymentMethod::MobilePayRedirect(_)
| WalletDataPaymentMethod::PaypalRedirect(_)
| WalletDataPaymentMethod::PaypalSdk(_)
| WalletDataPaymentMethod::Paze(_)
| WalletDataPaymentMethod::SamsungPay(_)
| WalletDataPaymentMethod::TwintRedirect {}
| WalletDataPaymentMethod::VippsRedirect {}
| WalletDataPaymentMethod::BluecodeRedirect {}
| WalletDataPaymentMethod::TouchNGoRedirect(_)
| WalletDataPaymentMethod::WeChatPayRedirect(_)
| WalletDataPaymentMethod::WeChatPayQr(_)
| WalletDataPaymentMethod::CashappQr(_)
| WalletDataPaymentMethod::SwishQr(_)
| WalletDataPaymentMethod::RevolutPay(_)
| WalletDataPaymentMethod::Paysera(_)
| WalletDataPaymentMethod::Skrill(_)
| WalletDataPaymentMethod::Mifinity(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("amazonpay"),
)
.into())
}
},
_ => Err(errors::ConnectorError::NotImplemented("Payment method".to_string()).into()),
}
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = amazonpay::AmazonpayRouterData::from((amount, req));
let connector_req = amazonpay::AmazonpayFinalizeRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: amazonpay::AmazonpayFinalizeResponse = res
.response
.parse_struct("Amazonpay PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Amazonpay {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/charges/{}",
self.base_url(connectors),
req.request.get_connector_transaction_id()?
))
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: amazonpay::AmazonpayPaymentsResponse = res
.response
.parse_struct("Amazonpay PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Amazonpay {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("Capture".to_string()).into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Amazonpay {
fn build_request(
&self,
_req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("Void".to_string()).into())
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Amazonpay {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/refunds", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = amazonpay::AmazonpayRouterData::from((refund_amount, req));
let connector_req = amazonpay::AmazonpayRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: amazonpay::RefundResponse = res
.response
.parse_struct("amazonpay RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Amazonpay {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/refunds/{}",
self.base_url(connectors),
req.request.connector_refund_id.clone().unwrap_or_default()
))
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: amazonpay::RefundResponse = res
.response
.parse_struct("amazonpay RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Amazonpay {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static AMAZONPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
let mut amazonpay_supported_payment_methods = SupportedPaymentMethods::new();
amazonpay_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::AmazonPay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
amazonpay_supported_payment_methods
});
static AMAZONPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Amazon Pay",
description: "Amazon Pay is an Alternative Payment Method (APM) connector that allows merchants to accept payments using customers' stored Amazon account details, providing a seamless checkout experience.",
connector_type: enums::HyperswitchConnectorCategory::AlternativePaymentMethod,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static AMAZONPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Amazonpay {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&AMAZONPAY_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&AMAZONPAY_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&AMAZONPAY_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/amazonpay.rs",
"file_size": null,
"is_async": null,
"is_pub": null,
"num_enums": 0,
"num_structs": 1,
"num_tables": null,
"score": null,
"total_crates": null
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.