id
stringlengths 24
57
| type
stringclasses 1
value | granularity
stringclasses 4
values | content
stringlengths 8.08k
87.1k
| metadata
dict |
|---|---|---|---|---|
large_file_-3612199710970036087
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/mock_db.rs
</path>
<file>
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 {}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/mock_db.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2201
}
|
large_file_-2158814459434422572
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/merchant_account.rs
</path>
<file>
#[cfg(feature = "olap")]
use std::collections::HashMap;
use common_utils::ext_traits::AsyncExt;
use diesel_models::merchant_account as storage;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
behaviour::{Conversion, ReverseConversion},
master_key::MasterKeyInterface,
merchant_account::{self as domain, MerchantAccountInterface},
merchant_key_store::{MerchantKeyStore, MerchantKeyStoreInterface},
};
use masking::PeekInterface;
use router_env::{instrument, tracing};
#[cfg(feature = "accounts_cache")]
use crate::redis::{
cache,
cache::{CacheKind, ACCOUNTS_CACHE},
};
#[cfg(feature = "accounts_cache")]
use crate::RedisConnInterface;
use crate::{
kv_router_store,
store::MerchantAccountUpdateInternal,
utils::{pg_accounts_connection_read, pg_accounts_connection_write},
CustomResult, DatabaseStore, KeyManagerState, MockDb, RouterStore, StorageError,
};
#[async_trait::async_trait]
impl<T: DatabaseStore> MerchantAccountInterface for kv_router_store::KVRouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
async fn insert_merchant(
&self,
state: &KeyManagerState,
merchant_account: domain::MerchantAccount,
merchant_key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, StorageError> {
self.router_store
.insert_merchant(state, merchant_account, merchant_key_store)
.await
}
#[instrument(skip_all)]
async fn find_merchant_account_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
merchant_key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, StorageError> {
self.router_store
.find_merchant_account_by_merchant_id(state, merchant_id, merchant_key_store)
.await
}
#[instrument(skip_all)]
async fn update_merchant(
&self,
state: &KeyManagerState,
this: domain::MerchantAccount,
merchant_account: domain::MerchantAccountUpdate,
merchant_key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, StorageError> {
self.router_store
.update_merchant(state, this, merchant_account, merchant_key_store)
.await
}
#[instrument(skip_all)]
async fn update_specific_fields_in_merchant(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
merchant_account: domain::MerchantAccountUpdate,
merchant_key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, StorageError> {
self.router_store
.update_specific_fields_in_merchant(
state,
merchant_id,
merchant_account,
merchant_key_store,
)
.await
}
#[instrument(skip_all)]
async fn find_merchant_account_by_publishable_key(
&self,
state: &KeyManagerState,
publishable_key: &str,
) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> {
self.router_store
.find_merchant_account_by_publishable_key(state, publishable_key)
.await
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn list_merchant_accounts_by_organization_id(
&self,
state: &KeyManagerState,
organization_id: &common_utils::id_type::OrganizationId,
) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {
self.router_store
.list_merchant_accounts_by_organization_id(state, organization_id)
.await
}
#[instrument(skip_all)]
async fn delete_merchant_account_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, StorageError> {
self.router_store
.delete_merchant_account_by_merchant_id(merchant_id)
.await
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn list_multiple_merchant_accounts(
&self,
state: &KeyManagerState,
merchant_ids: Vec<common_utils::id_type::MerchantId>,
) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {
self.router_store
.list_multiple_merchant_accounts(state, merchant_ids)
.await
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn list_merchant_and_org_ids(
&self,
_state: &KeyManagerState,
limit: u32,
offset: Option<u32>,
) -> CustomResult<
Vec<(
common_utils::id_type::MerchantId,
common_utils::id_type::OrganizationId,
)>,
StorageError,
> {
self.router_store
.list_merchant_and_org_ids(_state, limit, offset)
.await
}
async fn update_all_merchant_account(
&self,
merchant_account: domain::MerchantAccountUpdate,
) -> CustomResult<usize, StorageError> {
self.router_store
.update_all_merchant_account(merchant_account)
.await
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> MerchantAccountInterface for RouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
async fn insert_merchant(
&self,
state: &KeyManagerState,
merchant_account: domain::MerchantAccount,
merchant_key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, StorageError> {
let conn = pg_accounts_connection_write(self).await?;
merchant_account
.construct_new()
.await
.change_context(StorageError::EncryptionError)?
.insert(&conn)
.await
.map_err(|error| report!(StorageError::from(error)))?
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[instrument(skip_all)]
async fn find_merchant_account_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
merchant_key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, StorageError> {
let fetch_func = || async {
let conn = pg_accounts_connection_read(self).await?;
storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id)
.await
.map_err(|error| report!(StorageError::from(error)))
};
#[cfg(not(feature = "accounts_cache"))]
{
fetch_func()
.await?
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_id.to_owned().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(feature = "accounts_cache")]
{
cache::get_or_populate_in_memory(
self,
merchant_id.get_string_repr(),
fetch_func,
&ACCOUNTS_CACHE,
)
.await?
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
}
#[instrument(skip_all)]
async fn update_merchant(
&self,
state: &KeyManagerState,
this: domain::MerchantAccount,
merchant_account: domain::MerchantAccountUpdate,
merchant_key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, StorageError> {
let conn = pg_accounts_connection_write(self).await?;
let updated_merchant_account = Conversion::convert(this)
.await
.change_context(StorageError::EncryptionError)?
.update(&conn, merchant_account.into())
.await
.map_err(|error| report!(StorageError::from(error)))?;
#[cfg(feature = "accounts_cache")]
{
publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?;
}
updated_merchant_account
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[instrument(skip_all)]
async fn update_specific_fields_in_merchant(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
merchant_account: domain::MerchantAccountUpdate,
merchant_key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, StorageError> {
let conn = pg_accounts_connection_write(self).await?;
let updated_merchant_account = storage::MerchantAccount::update_with_specific_fields(
&conn,
merchant_id,
merchant_account.into(),
)
.await
.map_err(|error| report!(StorageError::from(error)))?;
#[cfg(feature = "accounts_cache")]
{
publish_and_redact_merchant_account_cache(self, &updated_merchant_account).await?;
}
updated_merchant_account
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[instrument(skip_all)]
async fn find_merchant_account_by_publishable_key(
&self,
state: &KeyManagerState,
publishable_key: &str,
) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> {
let fetch_by_pub_key_func = || async {
let conn = pg_accounts_connection_read(self).await?;
storage::MerchantAccount::find_by_publishable_key(&conn, publishable_key)
.await
.map_err(|error| report!(StorageError::from(error)))
};
let merchant_account;
#[cfg(not(feature = "accounts_cache"))]
{
merchant_account = fetch_by_pub_key_func().await?;
}
#[cfg(feature = "accounts_cache")]
{
merchant_account = cache::get_or_populate_in_memory(
self,
publishable_key,
fetch_by_pub_key_func,
&ACCOUNTS_CACHE,
)
.await?;
}
let key_store = self
.get_merchant_key_store_by_merchant_id(
state,
merchant_account.get_id(),
&self.master_key().peek().to_vec().into(),
)
.await?;
let domain_merchant_account = merchant_account
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?;
Ok((domain_merchant_account, key_store))
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn list_merchant_accounts_by_organization_id(
&self,
state: &KeyManagerState,
organization_id: &common_utils::id_type::OrganizationId,
) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {
use futures::future::try_join_all;
let conn = pg_accounts_connection_read(self).await?;
let encrypted_merchant_accounts =
storage::MerchantAccount::list_by_organization_id(&conn, organization_id)
.await
.map_err(|error| report!(StorageError::from(error)))?;
let db_master_key = self.master_key().peek().to_vec().into();
let merchant_key_stores =
try_join_all(encrypted_merchant_accounts.iter().map(|merchant_account| {
self.get_merchant_key_store_by_merchant_id(
state,
merchant_account.get_id(),
&db_master_key,
)
}))
.await?;
let merchant_accounts = try_join_all(
encrypted_merchant_accounts
.into_iter()
.zip(merchant_key_stores.iter())
.map(|(merchant_account, key_store)| async {
merchant_account
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}),
)
.await?;
Ok(merchant_accounts)
}
#[instrument(skip_all)]
async fn delete_merchant_account_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, StorageError> {
let conn = pg_accounts_connection_write(self).await?;
let is_deleted_func = || async {
storage::MerchantAccount::delete_by_merchant_id(&conn, merchant_id)
.await
.map_err(|error| report!(StorageError::from(error)))
};
let is_deleted;
#[cfg(not(feature = "accounts_cache"))]
{
is_deleted = is_deleted_func().await?;
}
#[cfg(feature = "accounts_cache")]
{
let merchant_account =
storage::MerchantAccount::find_by_merchant_id(&conn, merchant_id)
.await
.map_err(|error| report!(StorageError::from(error)))?;
is_deleted = is_deleted_func().await?;
publish_and_redact_merchant_account_cache(self, &merchant_account).await?;
}
Ok(is_deleted)
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn list_multiple_merchant_accounts(
&self,
state: &KeyManagerState,
merchant_ids: Vec<common_utils::id_type::MerchantId>,
) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {
let conn = pg_accounts_connection_read(self).await?;
let encrypted_merchant_accounts =
storage::MerchantAccount::list_multiple_merchant_accounts(&conn, merchant_ids)
.await
.map_err(|error| report!(StorageError::from(error)))?;
let db_master_key = self.master_key().peek().to_vec().into();
let merchant_key_stores = self
.list_multiple_key_stores(
state,
encrypted_merchant_accounts
.iter()
.map(|merchant_account| merchant_account.get_id())
.cloned()
.collect(),
&db_master_key,
)
.await?;
let key_stores_by_id: HashMap<_, _> = merchant_key_stores
.iter()
.map(|key_store| (key_store.merchant_id.to_owned(), key_store))
.collect();
let merchant_accounts =
futures::future::try_join_all(encrypted_merchant_accounts.into_iter().map(
|merchant_account| async {
let key_store = key_stores_by_id.get(merchant_account.get_id()).ok_or(
StorageError::ValueNotFound(format!(
"merchant_key_store with merchant_id = {:?}",
merchant_account.get_id()
)),
)?;
merchant_account
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
},
))
.await?;
Ok(merchant_accounts)
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn list_merchant_and_org_ids(
&self,
_state: &KeyManagerState,
limit: u32,
offset: Option<u32>,
) -> CustomResult<
Vec<(
common_utils::id_type::MerchantId,
common_utils::id_type::OrganizationId,
)>,
StorageError,
> {
let conn = pg_accounts_connection_read(self).await?;
let encrypted_merchant_accounts =
storage::MerchantAccount::list_all_merchant_accounts(&conn, limit, offset)
.await
.map_err(|error| report!(StorageError::from(error)))?;
let merchant_and_org_ids = encrypted_merchant_accounts
.into_iter()
.map(|merchant_account| {
let merchant_id = merchant_account.get_id().clone();
let org_id = merchant_account.organization_id;
(merchant_id, org_id)
})
.collect();
Ok(merchant_and_org_ids)
}
async fn update_all_merchant_account(
&self,
merchant_account: domain::MerchantAccountUpdate,
) -> CustomResult<usize, StorageError> {
let conn = pg_accounts_connection_read(self).await?;
let db_func = || async {
storage::MerchantAccount::update_all_merchant_accounts(
&conn,
MerchantAccountUpdateInternal::from(merchant_account),
)
.await
.map_err(|error| report!(StorageError::from(error)))
};
let total;
#[cfg(not(feature = "accounts_cache"))]
{
let ma = db_func().await?;
total = ma.len();
}
#[cfg(feature = "accounts_cache")]
{
let ma = db_func().await?;
publish_and_redact_all_merchant_account_cache(self, &ma).await?;
total = ma.len();
}
Ok(total)
}
}
#[async_trait::async_trait]
impl MerchantAccountInterface for MockDb {
type Error = StorageError;
#[allow(clippy::panic)]
async fn insert_merchant(
&self,
state: &KeyManagerState,
merchant_account: domain::MerchantAccount,
merchant_key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, StorageError> {
let mut accounts = self.merchant_accounts.lock().await;
let account = Conversion::convert(merchant_account)
.await
.change_context(StorageError::EncryptionError)?;
accounts.push(account.clone());
account
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[allow(clippy::panic)]
async fn find_merchant_account_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
merchant_key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, StorageError> {
let accounts = self.merchant_accounts.lock().await;
accounts
.iter()
.find(|account| account.get_id() == merchant_id)
.cloned()
.ok_or(StorageError::ValueNotFound(format!(
"Merchant ID: {merchant_id:?} not found",
)))?
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
async fn update_merchant(
&self,
state: &KeyManagerState,
merchant_account: domain::MerchantAccount,
merchant_account_update: domain::MerchantAccountUpdate,
merchant_key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, StorageError> {
let merchant_id = merchant_account.get_id().to_owned();
let mut accounts = self.merchant_accounts.lock().await;
accounts
.iter_mut()
.find(|account| account.get_id() == merchant_account.get_id())
.async_map(|account| async {
let update = MerchantAccountUpdateInternal::from(merchant_account_update)
.apply_changeset(
Conversion::convert(merchant_account)
.await
.change_context(StorageError::EncryptionError)?,
);
*account = update.clone();
update
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
StorageError::ValueNotFound(format!("Merchant ID: {merchant_id:?} not found",))
.into(),
)
}
async fn update_specific_fields_in_merchant(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
merchant_account_update: domain::MerchantAccountUpdate,
merchant_key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantAccount, StorageError> {
let mut accounts = self.merchant_accounts.lock().await;
accounts
.iter_mut()
.find(|account| account.get_id() == merchant_id)
.async_map(|account| async {
let update = MerchantAccountUpdateInternal::from(merchant_account_update)
.apply_changeset(account.clone());
*account = update.clone();
update
.convert(
state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
StorageError::ValueNotFound(format!("Merchant ID: {merchant_id:?} not found",))
.into(),
)
}
async fn find_merchant_account_by_publishable_key(
&self,
state: &KeyManagerState,
publishable_key: &str,
) -> CustomResult<(domain::MerchantAccount, MerchantKeyStore), StorageError> {
let accounts = self.merchant_accounts.lock().await;
let account = accounts
.iter()
.find(|account| {
account
.publishable_key
.as_ref()
.is_some_and(|key| key == publishable_key)
})
.ok_or(StorageError::ValueNotFound(format!(
"Publishable Key: {publishable_key} not found",
)))?;
let key_store = self
.get_merchant_key_store_by_merchant_id(
state,
account.get_id(),
&self.get_master_key().to_vec().into(),
)
.await?;
let merchant_account = account
.clone()
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?;
Ok((merchant_account, key_store))
}
async fn update_all_merchant_account(
&self,
merchant_account_update: domain::MerchantAccountUpdate,
) -> CustomResult<usize, StorageError> {
let mut accounts = self.merchant_accounts.lock().await;
Ok(accounts.iter_mut().fold(0, |acc, account| {
let update = MerchantAccountUpdateInternal::from(merchant_account_update.clone())
.apply_changeset(account.clone());
*account = update;
acc + 1
}))
}
async fn delete_merchant_account_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, StorageError> {
let mut accounts = self.merchant_accounts.lock().await;
accounts.retain(|x| x.get_id() != merchant_id);
Ok(true)
}
#[cfg(feature = "olap")]
async fn list_merchant_accounts_by_organization_id(
&self,
state: &KeyManagerState,
organization_id: &common_utils::id_type::OrganizationId,
) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {
let accounts = self.merchant_accounts.lock().await;
let futures = accounts
.iter()
.filter(|account| account.organization_id == *organization_id)
.map(|account| async {
let key_store = self
.get_merchant_key_store_by_merchant_id(
state,
account.get_id(),
&self.get_master_key().to_vec().into(),
)
.await;
match key_store {
Ok(key) => account
.clone()
.convert(state, key.key.get_inner(), key.merchant_id.clone().into())
.await
.change_context(StorageError::DecryptionError),
Err(err) => Err(err),
}
});
futures::future::join_all(futures)
.await
.into_iter()
.collect()
}
#[cfg(feature = "olap")]
async fn list_multiple_merchant_accounts(
&self,
state: &KeyManagerState,
merchant_ids: Vec<common_utils::id_type::MerchantId>,
) -> CustomResult<Vec<domain::MerchantAccount>, StorageError> {
let accounts = self.merchant_accounts.lock().await;
let futures = accounts
.iter()
.filter(|account| merchant_ids.contains(account.get_id()))
.map(|account| async {
let key_store = self
.get_merchant_key_store_by_merchant_id(
state,
account.get_id(),
&self.get_master_key().to_vec().into(),
)
.await;
match key_store {
Ok(key) => account
.clone()
.convert(state, key.key.get_inner(), key.merchant_id.clone().into())
.await
.change_context(StorageError::DecryptionError),
Err(err) => Err(err),
}
});
futures::future::join_all(futures)
.await
.into_iter()
.collect()
}
#[cfg(feature = "olap")]
async fn list_merchant_and_org_ids(
&self,
_state: &KeyManagerState,
limit: u32,
offset: Option<u32>,
) -> CustomResult<
Vec<(
common_utils::id_type::MerchantId,
common_utils::id_type::OrganizationId,
)>,
StorageError,
> {
let accounts = self.merchant_accounts.lock().await;
let limit = limit.try_into().unwrap_or(accounts.len());
let offset = offset.unwrap_or(0).try_into().unwrap_or(0);
let merchant_and_org_ids = accounts
.iter()
.skip(offset)
.take(limit)
.map(|account| (account.get_id().clone(), account.organization_id.clone()))
.collect::<Vec<_>>();
Ok(merchant_and_org_ids)
}
}
#[cfg(feature = "accounts_cache")]
async fn publish_and_redact_merchant_account_cache(
store: &(dyn RedisConnInterface + Send + Sync),
merchant_account: &storage::MerchantAccount,
) -> CustomResult<(), StorageError> {
let publishable_key = merchant_account
.publishable_key
.as_ref()
.map(|publishable_key| CacheKind::Accounts(publishable_key.into()));
#[cfg(feature = "v1")]
let cgraph_key = merchant_account.default_profile.as_ref().map(|profile_id| {
CacheKind::CGraph(
format!(
"cgraph_{}_{}",
merchant_account.get_id().get_string_repr(),
profile_id.get_string_repr(),
)
.into(),
)
});
// TODO: we will not have default profile in v2
#[cfg(feature = "v2")]
let cgraph_key = None;
let mut cache_keys = vec![CacheKind::Accounts(
merchant_account.get_id().get_string_repr().into(),
)];
cache_keys.extend(publishable_key.into_iter());
cache_keys.extend(cgraph_key.into_iter());
cache::redact_from_redis_and_publish(store, cache_keys).await?;
Ok(())
}
#[cfg(feature = "accounts_cache")]
async fn publish_and_redact_all_merchant_account_cache(
cache: &(dyn RedisConnInterface + Send + Sync),
merchant_accounts: &[storage::MerchantAccount],
) -> CustomResult<(), StorageError> {
let merchant_ids = merchant_accounts
.iter()
.map(|merchant_account| merchant_account.get_id().get_string_repr().to_string());
let publishable_keys = merchant_accounts
.iter()
.filter_map(|m| m.publishable_key.clone());
let cache_keys: Vec<CacheKind<'_>> = merchant_ids
.chain(publishable_keys)
.map(|s| CacheKind::Accounts(s.into()))
.collect();
cache::redact_from_redis_and_publish(cache, cache_keys).await?;
Ok(())
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/merchant_account.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6114
}
|
large_file_-4619901670390511572
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/payment_method.rs
</path>
<file>
pub use diesel_models::payment_method::PaymentMethod;
use crate::redis::kv_store::KvStorePartition;
impl KvStorePartition for PaymentMethod {}
use common_enums::enums::MerchantStorageScheme;
use common_utils::{errors::CustomResult, id_type, types::keymanager::KeyManagerState};
#[cfg(feature = "v1")]
use diesel_models::kv;
use diesel_models::payment_method::{PaymentMethodUpdate, PaymentMethodUpdateInternal};
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::behaviour::ReverseConversion;
use hyperswitch_domain_models::{
behaviour::Conversion,
merchant_key_store::MerchantKeyStore,
payment_methods::{PaymentMethod as DomainPaymentMethod, PaymentMethodInterface},
};
use router_env::{instrument, tracing};
use super::MockDb;
use crate::{
diesel_error_to_data_error, errors,
kv_router_store::{FindResourceBy, KVRouterStore},
utils::{pg_connection_read, pg_connection_write},
DatabaseStore, RouterStore,
};
#[cfg(feature = "v1")]
use crate::{
kv_router_store::{FilterResourceParams, InsertResourceParams, UpdateResourceParams},
redis::kv_store::{Op, PartitionKey},
};
#[async_trait::async_trait]
impl<T: DatabaseStore> PaymentMethodInterface for KVRouterStore<T> {
type Error = errors::StorageError;
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.find_resource_by_id(
state,
key_store,
storage_scheme,
PaymentMethod::find_by_payment_method_id(&conn, payment_method_id),
FindResourceBy::LookupId(format!("payment_method_{payment_method_id}")),
)
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method_id: &id_type::GlobalPaymentMethodId,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.find_resource_by_id(
state,
key_store,
storage_scheme,
PaymentMethod::find_by_id(&conn, payment_method_id),
FindResourceBy::LookupId(format!(
"payment_method_{}",
payment_method_id.get_string_repr()
)),
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_method_by_locker_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
locker_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.find_resource_by_id(
state,
key_store,
storage_scheme,
PaymentMethod::find_by_locker_id(&conn, locker_id),
FindResourceBy::LookupId(format!("payment_method_locker_{locker_id}")),
)
.await
}
// not supported in kv
#[cfg(feature = "v1")]
#[instrument(skip_all)]
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, errors::StorageError> {
self.router_store
.get_payment_method_count_by_customer_id_merchant_id_status(
customer_id,
merchant_id,
status,
)
.await
}
#[instrument(skip_all)]
async fn get_payment_method_count_by_merchant_id_status(
&self,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError> {
self.router_store
.get_payment_method_count_by_merchant_id_status(merchant_id, status)
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn insert_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
self.router_store
.insert_payment_method(state, key_store, payment_method, storage_scheme)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn insert_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_write(self).await?;
let mut payment_method_new = payment_method
.construct_new()
.await
.change_context(errors::StorageError::DecryptionError)?;
payment_method_new.update_storage_scheme(storage_scheme);
let key = PartitionKey::MerchantIdCustomerId {
merchant_id: &payment_method_new.merchant_id.clone(),
customer_id: &payment_method_new.customer_id.clone(),
};
let identifier = format!("payment_method_id_{}", payment_method_new.get_id());
let lookup_id1 = format!("payment_method_{}", payment_method_new.get_id());
let mut reverse_lookups = vec![lookup_id1];
if let Some(locker_id) = &payment_method_new.locker_id {
reverse_lookups.push(format!("payment_method_locker_{locker_id}"))
}
let payment_method = (&payment_method_new.clone()).into();
self.insert_resource(
state,
key_store,
storage_scheme,
payment_method_new.clone().insert(&conn),
payment_method,
InsertResourceParams {
insertable: kv::Insertable::PaymentMethod(payment_method_new.clone()),
reverse_lookups,
key,
identifier,
resource_type: "payment_method",
},
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn update_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
payment_method_update: PaymentMethodUpdate,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method = Conversion::convert(payment_method)
.await
.change_context(errors::StorageError::DecryptionError)?;
let merchant_id = payment_method.merchant_id.clone();
let customer_id = payment_method.customer_id.clone();
let key = PartitionKey::MerchantIdCustomerId {
merchant_id: &merchant_id,
customer_id: &customer_id,
};
let conn = pg_connection_write(self).await?;
let field = format!("payment_method_id_{}", payment_method.get_id().clone());
let p_update: PaymentMethodUpdateInternal =
payment_method_update.convert_to_payment_method_update(storage_scheme);
let updated_payment_method = p_update.clone().apply_changeset(payment_method.clone());
self.update_resource(
state,
key_store,
storage_scheme,
payment_method
.clone()
.update_with_payment_method_id(&conn, p_update.clone()),
updated_payment_method,
UpdateResourceParams {
updateable: kv::Updateable::PaymentMethodUpdate(Box::new(
kv::PaymentMethodUpdateMems {
orig: payment_method.clone(),
update_data: p_update.clone(),
},
)),
operation: Op::Update(
key.clone(),
&field,
payment_method.clone().updated_by.as_deref(),
),
},
)
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn update_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
payment_method_update: PaymentMethodUpdate,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
self.router_store
.update_payment_method(
state,
key_store,
payment_method,
payment_method_update,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
limit: Option<i64>,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
self.router_store
.find_payment_method_by_customer_id_merchant_id_list(
state,
key_store,
customer_id,
merchant_id,
limit,
)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_method_list_by_global_customer_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::GlobalCustomerId,
limit: Option<i64>,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
self.router_store
.find_payment_method_list_by_global_customer_id(state, key_store, customer_id, limit)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
state: &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<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.filter_resources(
state,
key_store,
storage_scheme,
PaymentMethod::find_by_customer_id_merchant_id_status(
&conn,
customer_id,
merchant_id,
status,
limit,
),
|pm| pm.status == status,
FilterResourceParams {
key: PartitionKey::MerchantIdCustomerId {
merchant_id,
customer_id,
},
pattern: "payment_method_id_*",
limit,
},
)
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_payment_method_by_global_customer_id_merchant_id_status(
&self,
state: &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<DomainPaymentMethod>, errors::StorageError> {
self.router_store
.find_payment_method_by_global_customer_id_merchant_id_status(
state,
key_store,
customer_id,
merchant_id,
status,
limit,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
merchant_id: &id_type::MerchantId,
payment_method_id: &str,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
self.router_store
.delete_payment_method_by_merchant_id_payment_method_id(
state,
key_store,
merchant_id,
payment_method_id,
)
.await
}
// Soft delete, Check if KV stuff is needed here
#[cfg(feature = "v2")]
async fn delete_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
self.router_store
.delete_payment_method(state, key_store, payment_method)
.await
}
// Check if KV stuff is needed here
#[cfg(feature = "v2")]
async fn find_payment_method_by_fingerprint_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
fingerprint_id: &str,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
self.router_store
.find_payment_method_by_fingerprint_id(state, key_store, fingerprint_id)
.await
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> PaymentMethodInterface for RouterStore<T> {
type Error = errors::StorageError;
#[instrument(skip_all)]
#[cfg(feature = "v1")]
async fn find_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.call_database(
state,
key_store,
PaymentMethod::find_by_payment_method_id(&conn, payment_method_id),
)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method_id: &id_type::GlobalPaymentMethodId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.call_database(
state,
key_store,
PaymentMethod::find_by_id(&conn, payment_method_id),
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_method_by_locker_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
locker_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.call_database(
state,
key_store,
PaymentMethod::find_by_locker_id(&conn, locker_id),
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
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, errors::StorageError> {
let conn = pg_connection_read(self).await?;
PaymentMethod::get_count_by_customer_id_merchant_id_status(
&conn,
customer_id,
merchant_id,
status,
)
.await
.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})
}
#[instrument(skip_all)]
async fn get_payment_method_count_by_merchant_id_status(
&self,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError> {
let conn = pg_connection_read(self).await?;
PaymentMethod::get_count_by_merchant_id_status(&conn, merchant_id, status)
.await
.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})
}
#[instrument(skip_all)]
async fn insert_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method_new = payment_method
.construct_new()
.await
.change_context(errors::StorageError::DecryptionError)?;
let conn = pg_connection_write(self).await?;
self.call_database(state, key_store, payment_method_new.insert(&conn))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn update_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
payment_method_update: PaymentMethodUpdate,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method = Conversion::convert(payment_method)
.await
.change_context(errors::StorageError::DecryptionError)?;
let conn = pg_connection_write(self).await?;
self.call_database(
state,
key_store,
payment_method.update_with_payment_method_id(&conn, payment_method_update.into()),
)
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn update_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
payment_method_update: PaymentMethodUpdate,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method = Conversion::convert(payment_method)
.await
.change_context(errors::StorageError::DecryptionError)?;
let conn = pg_connection_write(self).await?;
self.call_database(
state,
key_store,
payment_method.update_with_id(&conn, payment_method_update.into()),
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
limit: Option<i64>,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.find_resources(
state,
key_store,
PaymentMethod::find_by_customer_id_merchant_id(&conn, customer_id, merchant_id, limit),
)
.await
}
// Need to fix this once we move to payment method for customer
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_payment_method_list_by_global_customer_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
id: &id_type::GlobalCustomerId,
limit: Option<i64>,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.find_resources(
state,
key_store,
PaymentMethod::find_by_global_customer_id(&conn, id, limit),
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
state: &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<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.find_resources(
state,
key_store,
PaymentMethod::find_by_customer_id_merchant_id_status(
&conn,
customer_id,
merchant_id,
status,
limit,
),
)
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_payment_method_by_global_customer_id_merchant_id_status(
&self,
state: &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<DomainPaymentMethod>, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.find_resources(
state,
key_store,
PaymentMethod::find_by_global_customer_id_merchant_id_status(
&conn,
customer_id,
merchant_id,
status,
limit,
),
)
.await
}
#[cfg(feature = "v1")]
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
merchant_id: &id_type::MerchantId,
payment_method_id: &str,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_write(self).await?;
self.call_database(
state,
key_store,
PaymentMethod::delete_by_merchant_id_payment_method_id(
&conn,
merchant_id,
payment_method_id,
),
)
.await
}
#[cfg(feature = "v2")]
async fn delete_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method = Conversion::convert(payment_method)
.await
.change_context(errors::StorageError::DecryptionError)?;
let conn = pg_connection_write(self).await?;
let payment_method_update = PaymentMethodUpdate::StatusUpdate {
status: Some(common_enums::PaymentMethodStatus::Inactive),
};
self.call_database(
state,
key_store,
payment_method.update_with_id(&conn, payment_method_update.into()),
)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_method_by_fingerprint_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
fingerprint_id: &str,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let conn = pg_connection_read(self).await?;
self.call_database(
state,
key_store,
PaymentMethod::find_by_fingerprint_id(&conn, fingerprint_id),
)
.await
}
}
#[async_trait::async_trait]
impl PaymentMethodInterface for MockDb {
type Error = errors::StorageError;
#[cfg(feature = "v1")]
async fn find_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
self.get_resource::<PaymentMethod, _>(
state,
key_store,
payment_methods,
|pm| pm.get_id() == payment_method_id,
"cannot find payment method".to_string(),
)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method_id: &id_type::GlobalPaymentMethodId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
self.get_resource::<PaymentMethod, _>(
state,
key_store,
payment_methods,
|pm| pm.get_id() == payment_method_id,
"cannot find payment method".to_string(),
)
.await
}
#[cfg(feature = "v1")]
async fn find_payment_method_by_locker_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
locker_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
self.get_resource::<PaymentMethod, _>(
state,
key_store,
payment_methods,
|pm| pm.locker_id == Some(locker_id.to_string()),
"cannot find payment method".to_string(),
)
.await
}
#[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, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let count = payment_methods
.iter()
.filter(|pm| {
pm.customer_id == *customer_id
&& pm.merchant_id == *merchant_id
&& pm.status == status
})
.count();
i64::try_from(count).change_context(errors::StorageError::MockDbError)
}
async fn get_payment_method_count_by_merchant_id_status(
&self,
merchant_id: &id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> CustomResult<i64, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let count = payment_methods
.iter()
.filter(|pm| pm.merchant_id == *merchant_id && pm.status == status)
.count();
i64::try_from(count).change_context(errors::StorageError::MockDbError)
}
async fn insert_payment_method(
&self,
_state: &KeyManagerState,
_key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let mut payment_methods = self.payment_methods.lock().await;
let pm = Conversion::convert(payment_method.clone())
.await
.change_context(errors::StorageError::DecryptionError)?;
payment_methods.push(pm);
Ok(payment_method)
}
#[cfg(feature = "v1")]
async fn find_payment_method_by_customer_id_merchant_id_list(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
_limit: Option<i64>,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
self.get_resources(
state,
key_store,
payment_methods,
|pm| pm.customer_id == *customer_id && pm.merchant_id == *merchant_id,
"cannot find payment method".to_string(),
)
.await
}
// Need to fix this once we complete v2 payment method
#[cfg(feature = "v2")]
async fn find_payment_method_list_by_global_customer_id(
&self,
_state: &KeyManagerState,
_key_store: &MerchantKeyStore,
_id: &id_type::GlobalCustomerId,
_limit: Option<i64>,
) -> CustomResult<Vec<DomainPaymentMethod>, errors::StorageError> {
todo!()
}
#[cfg(feature = "v1")]
async fn find_payment_method_by_customer_id_merchant_id_status(
&self,
state: &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<DomainPaymentMethod>, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
self.get_resources(
state,
key_store,
payment_methods,
|pm| {
pm.customer_id == *customer_id
&& pm.merchant_id == *merchant_id
&& pm.status == status
},
"cannot find payment method".to_string(),
)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_method_by_global_customer_id_merchant_id_status(
&self,
state: &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<DomainPaymentMethod>, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
let find_pm_by = |pm: &&PaymentMethod| {
pm.customer_id == *customer_id && pm.merchant_id == *merchant_id && pm.status == status
};
let error_message = "cannot find payment method".to_string();
self.get_resources(state, key_store, payment_methods, find_pm_by, error_message)
.await
}
#[cfg(feature = "v1")]
async fn delete_payment_method_by_merchant_id_payment_method_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
merchant_id: &id_type::MerchantId,
payment_method_id: &str,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let mut payment_methods = self.payment_methods.lock().await;
match payment_methods
.iter()
.position(|pm| pm.merchant_id == *merchant_id && pm.get_id() == payment_method_id)
{
Some(index) => {
let deleted_payment_method = payment_methods.remove(index);
Ok(deleted_payment_method
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(errors::StorageError::DecryptionError)?)
}
None => Err(errors::StorageError::ValueNotFound(
"cannot find payment method to delete".to_string(),
)
.into()),
}
}
async fn update_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
payment_method_update: PaymentMethodUpdate,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method_updated = PaymentMethodUpdateInternal::from(payment_method_update)
.apply_changeset(
Conversion::convert(payment_method.clone())
.await
.change_context(errors::StorageError::EncryptionError)?,
);
self.update_resource::<PaymentMethod, _>(
state,
key_store,
self.payment_methods.lock().await,
payment_method_updated,
|pm| pm.get_id() == payment_method.get_id(),
"cannot update payment method".to_string(),
)
.await
}
#[cfg(feature = "v2")]
async fn delete_payment_method(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
payment_method: DomainPaymentMethod,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_method_update = PaymentMethodUpdate::StatusUpdate {
status: Some(common_enums::PaymentMethodStatus::Inactive),
};
let payment_method_updated = PaymentMethodUpdateInternal::from(payment_method_update)
.apply_changeset(
Conversion::convert(payment_method.clone())
.await
.change_context(errors::StorageError::EncryptionError)?,
);
self.update_resource::<PaymentMethod, _>(
state,
key_store,
self.payment_methods.lock().await,
payment_method_updated,
|pm| pm.get_id() == payment_method.get_id(),
"cannot find payment method".to_string(),
)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_method_by_fingerprint_id(
&self,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
fingerprint_id: &str,
) -> CustomResult<DomainPaymentMethod, errors::StorageError> {
let payment_methods = self.payment_methods.lock().await;
self.get_resource::<PaymentMethod, _>(
state,
key_store,
payment_methods,
|pm| pm.locker_fingerprint_id == Some(fingerprint_id.to_string()),
"cannot find payment method".to_string(),
)
.await
}
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/payment_method.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7297
}
|
large_file_6999153258997339718
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/merchant_connector_account.rs
</path>
<file>
use async_bb8_diesel::AsyncConnection;
use common_utils::{encryption::Encryption, ext_traits::AsyncExt};
use diesel_models::merchant_connector_account as storage;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
behaviour::{Conversion, ReverseConversion},
merchant_connector_account::{self as domain, MerchantConnectorAccountInterface},
merchant_key_store::MerchantKeyStore,
};
use router_env::{instrument, tracing};
#[cfg(feature = "accounts_cache")]
use crate::redis::cache;
use crate::{
kv_router_store,
utils::{pg_accounts_connection_read, pg_accounts_connection_write},
CustomResult, DatabaseStore, KeyManagerState, MockDb, RouterStore, StorageError,
};
#[async_trait::async_trait]
impl<T: DatabaseStore> MerchantConnectorAccountInterface for kv_router_store::KVRouterStore<T> {
type Error = StorageError;
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_merchant_connector_account_by_merchant_id_connector_label(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
connector_label: &str,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
self.router_store
.find_merchant_connector_account_by_merchant_id_connector_label(
state,
merchant_id,
connector_label,
key_store,
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_merchant_connector_account_by_profile_id_connector_name(
&self,
state: &KeyManagerState,
profile_id: &common_utils::id_type::ProfileId,
connector_name: &str,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
self.router_store
.find_merchant_connector_account_by_profile_id_connector_name(
state,
profile_id,
connector_name,
key_store,
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_merchant_connector_account_by_merchant_id_connector_name(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> {
self.router_store
.find_merchant_connector_account_by_merchant_id_connector_name(
state,
merchant_id,
connector_name,
key_store,
)
.await
}
#[instrument(skip_all)]
#[cfg(feature = "v1")]
async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
self.router_store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
state,
merchant_id,
merchant_connector_id,
key_store,
)
.await
}
#[instrument(skip_all)]
#[cfg(feature = "v2")]
async fn find_merchant_connector_account_by_id(
&self,
state: &KeyManagerState,
id: &common_utils::id_type::MerchantConnectorAccountId,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
self.router_store
.find_merchant_connector_account_by_id(state, id, key_store)
.await
}
#[instrument(skip_all)]
async fn insert_merchant_connector_account(
&self,
state: &KeyManagerState,
t: domain::MerchantConnectorAccount,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
self.router_store
.insert_merchant_connector_account(state, t, key_store)
.await
}
async fn list_enabled_connector_accounts_by_profile_id(
&self,
state: &KeyManagerState,
profile_id: &common_utils::id_type::ProfileId,
key_store: &MerchantKeyStore,
connector_type: common_enums::ConnectorType,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> {
self.router_store
.list_enabled_connector_accounts_by_profile_id(
state,
profile_id,
key_store,
connector_type,
)
.await
}
#[instrument(skip_all)]
async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
get_disabled: bool,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccounts, Self::Error> {
self.router_store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
state,
merchant_id,
get_disabled,
key_store,
)
.await
}
#[instrument(skip_all)]
#[cfg(all(feature = "olap", feature = "v2"))]
async fn list_connector_account_by_profile_id(
&self,
state: &KeyManagerState,
profile_id: &common_utils::id_type::ProfileId,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> {
self.router_store
.list_connector_account_by_profile_id(state, profile_id, key_store)
.await
}
#[instrument(skip_all)]
async fn update_multiple_merchant_connector_accounts(
&self,
merchant_connector_accounts: Vec<(
domain::MerchantConnectorAccount,
storage::MerchantConnectorAccountUpdateInternal,
)>,
) -> CustomResult<(), Self::Error> {
self.router_store
.update_multiple_merchant_connector_accounts(merchant_connector_accounts)
.await
}
#[instrument(skip_all)]
#[cfg(feature = "v1")]
async fn update_merchant_connector_account(
&self,
state: &KeyManagerState,
this: domain::MerchantConnectorAccount,
merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
self.router_store
.update_merchant_connector_account(state, this, merchant_connector_account, key_store)
.await
}
#[instrument(skip_all)]
#[cfg(feature = "v2")]
async fn update_merchant_connector_account(
&self,
state: &KeyManagerState,
this: domain::MerchantConnectorAccount,
merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
self.update_merchant_connector_account(state, this, merchant_connector_account, key_store)
.await
}
#[instrument(skip_all)]
#[cfg(feature = "v1")]
async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
) -> CustomResult<bool, Self::Error> {
self.router_store
.delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
merchant_id,
merchant_connector_id,
)
.await
}
#[instrument(skip_all)]
#[cfg(feature = "v2")]
async fn delete_merchant_connector_account_by_id(
&self,
id: &common_utils::id_type::MerchantConnectorAccountId,
) -> CustomResult<bool, Self::Error> {
self.router_store
.delete_merchant_connector_account_by_id(id)
.await
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> MerchantConnectorAccountInterface for RouterStore<T> {
type Error = StorageError;
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_merchant_connector_account_by_merchant_id_connector_label(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
connector_label: &str,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
let find_call = || async {
let conn = pg_accounts_connection_read(self).await?;
storage::MerchantConnectorAccount::find_by_merchant_id_connector(
&conn,
merchant_id,
connector_label,
)
.await
.map_err(|error| report!(Self::Error::from(error)))
};
#[cfg(not(feature = "accounts_cache"))]
{
find_call()
.await?
.convert(state, key_store.key.get_inner(), merchant_id.clone().into())
.await
.change_context(Self::Error::DeserializationFailed)
}
#[cfg(feature = "accounts_cache")]
{
cache::get_or_populate_in_memory(
self,
&format!("{}_{}", merchant_id.get_string_repr(), connector_label),
find_call,
&cache::ACCOUNTS_CACHE,
)
.await
.async_and_then(|item| async {
item.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(Self::Error::DecryptionError)
})
.await
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_merchant_connector_account_by_profile_id_connector_name(
&self,
state: &KeyManagerState,
profile_id: &common_utils::id_type::ProfileId,
connector_name: &str,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
let find_call = || async {
let conn = pg_accounts_connection_read(self).await?;
storage::MerchantConnectorAccount::find_by_profile_id_connector_name(
&conn,
profile_id,
connector_name,
)
.await
.map_err(|error| report!(Self::Error::from(error)))
};
#[cfg(not(feature = "accounts_cache"))]
{
find_call()
.await?
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(Self::Error::DeserializationFailed)
}
#[cfg(feature = "accounts_cache")]
{
cache::get_or_populate_in_memory(
self,
&format!("{}_{}", profile_id.get_string_repr(), connector_name),
find_call,
&cache::ACCOUNTS_CACHE,
)
.await
.async_and_then(|item| async {
item.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(Self::Error::DecryptionError)
})
.await
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_merchant_connector_account_by_merchant_id_connector_name(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> {
let conn = pg_accounts_connection_read(self).await?;
storage::MerchantConnectorAccount::find_by_merchant_id_connector_name(
&conn,
merchant_id,
connector_name,
)
.await
.map_err(|error| report!(Self::Error::from(error)))
.async_and_then(|items| async {
let mut output = Vec::with_capacity(items.len());
for item in items.into_iter() {
output.push(
item.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(Self::Error::DecryptionError)?,
)
}
Ok(output)
})
.await
}
#[instrument(skip_all)]
#[cfg(feature = "v1")]
async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
let find_call = || async {
let conn = pg_accounts_connection_read(self).await?;
storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id(
&conn,
merchant_id,
merchant_connector_id,
)
.await
.map_err(|error| report!(Self::Error::from(error)))
};
#[cfg(not(feature = "accounts_cache"))]
{
find_call()
.await?
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(Self::Error::DecryptionError)
}
#[cfg(feature = "accounts_cache")]
{
cache::get_or_populate_in_memory(
self,
&format!(
"{}_{}",
merchant_id.get_string_repr(),
merchant_connector_id.get_string_repr()
),
find_call,
&cache::ACCOUNTS_CACHE,
)
.await?
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(Self::Error::DecryptionError)
}
}
#[instrument(skip_all)]
#[cfg(feature = "v2")]
async fn find_merchant_connector_account_by_id(
&self,
state: &KeyManagerState,
id: &common_utils::id_type::MerchantConnectorAccountId,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
let find_call = || async {
let conn = pg_accounts_connection_read(self).await?;
storage::MerchantConnectorAccount::find_by_id(&conn, id)
.await
.map_err(|error| report!(Self::Error::from(error)))
};
#[cfg(not(feature = "accounts_cache"))]
{
find_call()
.await?
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone(),
)
.await
.change_context(Self::Error::DecryptionError)
}
#[cfg(feature = "accounts_cache")]
{
cache::get_or_populate_in_memory(
self,
id.get_string_repr(),
find_call,
&cache::ACCOUNTS_CACHE,
)
.await?
.convert(
state,
key_store.key.get_inner(),
common_utils::types::keymanager::Identifier::Merchant(
key_store.merchant_id.clone(),
),
)
.await
.change_context(Self::Error::DecryptionError)
}
}
#[instrument(skip_all)]
async fn insert_merchant_connector_account(
&self,
state: &KeyManagerState,
t: domain::MerchantConnectorAccount,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
let conn = pg_accounts_connection_write(self).await?;
t.construct_new()
.await
.change_context(Self::Error::EncryptionError)?
.insert(&conn)
.await
.map_err(|error| report!(Self::Error::from(error)))
.async_and_then(|item| async {
item.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(Self::Error::DecryptionError)
})
.await
}
async fn list_enabled_connector_accounts_by_profile_id(
&self,
state: &KeyManagerState,
profile_id: &common_utils::id_type::ProfileId,
key_store: &MerchantKeyStore,
connector_type: common_enums::ConnectorType,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> {
let conn = pg_accounts_connection_read(self).await?;
storage::MerchantConnectorAccount::list_enabled_by_profile_id(
&conn,
profile_id,
connector_type,
)
.await
.map_err(|error| report!(Self::Error::from(error)))
.async_and_then(|items| async {
let mut output = Vec::with_capacity(items.len());
for item in items.into_iter() {
output.push(
item.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(Self::Error::DecryptionError)?,
)
}
Ok(output)
})
.await
}
#[instrument(skip_all)]
async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
get_disabled: bool,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccounts, Self::Error> {
let conn = pg_accounts_connection_read(self).await?;
let merchant_connector_account_vec =
storage::MerchantConnectorAccount::find_by_merchant_id(
&conn,
merchant_id,
get_disabled,
)
.await
.map_err(|error| report!(Self::Error::from(error)))
.async_and_then(|items| async {
let mut output = Vec::with_capacity(items.len());
for item in items.into_iter() {
output.push(
item.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(Self::Error::DecryptionError)?,
)
}
Ok(output)
})
.await?;
Ok(domain::MerchantConnectorAccounts::new(
merchant_connector_account_vec,
))
}
#[instrument(skip_all)]
#[cfg(all(feature = "olap", feature = "v2"))]
async fn list_connector_account_by_profile_id(
&self,
state: &KeyManagerState,
profile_id: &common_utils::id_type::ProfileId,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, Self::Error> {
let conn = pg_accounts_connection_read(self).await?;
storage::MerchantConnectorAccount::list_by_profile_id(&conn, profile_id)
.await
.map_err(|error| report!(Self::Error::from(error)))
.async_and_then(|items| async {
let mut output = Vec::with_capacity(items.len());
for item in items.into_iter() {
output.push(
item.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(Self::Error::DecryptionError)?,
)
}
Ok(output)
})
.await
}
#[instrument(skip_all)]
async fn update_multiple_merchant_connector_accounts(
&self,
merchant_connector_accounts: Vec<(
domain::MerchantConnectorAccount,
storage::MerchantConnectorAccountUpdateInternal,
)>,
) -> CustomResult<(), Self::Error> {
let conn = pg_accounts_connection_write(self).await?;
async fn update_call(
connection: &diesel_models::PgPooledConn,
(merchant_connector_account, mca_update): (
domain::MerchantConnectorAccount,
storage::MerchantConnectorAccountUpdateInternal,
),
) -> Result<(), error_stack::Report<StorageError>> {
Conversion::convert(merchant_connector_account)
.await
.change_context(StorageError::EncryptionError)?
.update(connection, mca_update)
.await
.map_err(|error| report!(StorageError::from(error)))?;
Ok(())
}
conn.transaction_async(|connection_pool| async move {
for (merchant_connector_account, update_merchant_connector_account) in
merchant_connector_accounts
{
#[cfg(feature = "v1")]
let _connector_name = merchant_connector_account.connector_name.clone();
#[cfg(feature = "v2")]
let _connector_name = merchant_connector_account.connector_name.to_string();
let _profile_id = merchant_connector_account.profile_id.clone();
let _merchant_id = merchant_connector_account.merchant_id.clone();
let _merchant_connector_id = merchant_connector_account.get_id().clone();
let update = update_call(
&connection_pool,
(
merchant_connector_account,
update_merchant_connector_account,
),
);
#[cfg(feature = "accounts_cache")]
// Redact all caches as any of might be used because of backwards compatibility
Box::pin(cache::publish_and_redact_multiple(
self,
[
cache::CacheKind::Accounts(
format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(),
),
cache::CacheKind::Accounts(
format!(
"{}_{}",
_merchant_id.get_string_repr(),
_merchant_connector_id.get_string_repr()
)
.into(),
),
cache::CacheKind::CGraph(
format!(
"cgraph_{}_{}",
_merchant_id.get_string_repr(),
_profile_id.get_string_repr()
)
.into(),
),
],
|| update,
))
.await
.map_err(|error| {
// Returning `DatabaseConnectionError` after logging the actual error because
// -> it is not possible to get the underlying from `error_stack::Report<C>`
// -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>`
// because of Rust's orphan rules
router_env::logger::error!(
?error,
"DB transaction for updating multiple merchant connector account failed"
);
Self::Error::DatabaseConnectionError
})?;
#[cfg(not(feature = "accounts_cache"))]
{
update.await.map_err(|error| {
// Returning `DatabaseConnectionError` after logging the actual error because
// -> it is not possible to get the underlying from `error_stack::Report<C>`
// -> it is not possible to write a `From` impl to convert the `diesel::result::Error` to `error_stack::Report<StorageError>`
// because of Rust's orphan rules
router_env::logger::error!(
?error,
"DB transaction for updating multiple merchant connector account failed"
);
Self::Error::DatabaseConnectionError
})?;
}
}
Ok::<_, Self::Error>(())
})
.await?;
Ok(())
}
#[instrument(skip_all)]
#[cfg(feature = "v1")]
async fn update_merchant_connector_account(
&self,
state: &KeyManagerState,
this: domain::MerchantConnectorAccount,
merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
let _connector_name = this.connector_name.clone();
let _profile_id = this.profile_id.clone();
let _merchant_id = this.merchant_id.clone();
let _merchant_connector_id = this.merchant_connector_id.clone();
let update_call = || async {
let conn = pg_accounts_connection_write(self).await?;
Conversion::convert(this)
.await
.change_context(Self::Error::EncryptionError)?
.update(&conn, merchant_connector_account)
.await
.map_err(|error| report!(Self::Error::from(error)))
.async_and_then(|item| async {
item.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(Self::Error::DecryptionError)
})
.await
};
#[cfg(feature = "accounts_cache")]
{
// Redact all caches as any of might be used because of backwards compatibility
cache::publish_and_redact_multiple(
self,
[
cache::CacheKind::Accounts(
format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(),
),
cache::CacheKind::Accounts(
format!(
"{}_{}",
_merchant_id.get_string_repr(),
_merchant_connector_id.get_string_repr()
)
.into(),
),
cache::CacheKind::CGraph(
format!(
"cgraph_{}_{}",
_merchant_id.get_string_repr(),
_profile_id.get_string_repr()
)
.into(),
),
cache::CacheKind::PmFiltersCGraph(
format!(
"pm_filters_cgraph_{}_{}",
_merchant_id.get_string_repr(),
_profile_id.get_string_repr(),
)
.into(),
),
],
update_call,
)
.await
}
#[cfg(not(feature = "accounts_cache"))]
{
update_call().await
}
}
#[instrument(skip_all)]
#[cfg(feature = "v2")]
async fn update_merchant_connector_account(
&self,
state: &KeyManagerState,
this: domain::MerchantConnectorAccount,
merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, Self::Error> {
let _connector_name = this.connector_name;
let _profile_id = this.profile_id.clone();
let _merchant_id = this.merchant_id.clone();
let _merchant_connector_id = this.get_id().clone();
let update_call = || async {
let conn = pg_accounts_connection_write(self).await?;
Conversion::convert(this)
.await
.change_context(Self::Error::EncryptionError)?
.update(&conn, merchant_connector_account)
.await
.map_err(|error| report!(Self::Error::from(error)))
.async_and_then(|item| async {
item.convert(
state,
key_store.key.get_inner(),
common_utils::types::keymanager::Identifier::Merchant(
key_store.merchant_id.clone(),
),
)
.await
.change_context(Self::Error::DecryptionError)
})
.await
};
#[cfg(feature = "accounts_cache")]
{
// Redact all caches as any of might be used because of backwards compatibility
cache::publish_and_redact_multiple(
self,
[
cache::CacheKind::Accounts(
format!("{}_{}", _profile_id.get_string_repr(), _connector_name).into(),
),
cache::CacheKind::Accounts(
_merchant_connector_id.get_string_repr().to_string().into(),
),
cache::CacheKind::CGraph(
format!(
"cgraph_{}_{}",
_merchant_id.get_string_repr(),
_profile_id.get_string_repr()
)
.into(),
),
cache::CacheKind::PmFiltersCGraph(
format!(
"pm_filters_cgraph_{}_{}",
_merchant_id.get_string_repr(),
_profile_id.get_string_repr()
)
.into(),
),
],
update_call,
)
.await
}
#[cfg(not(feature = "accounts_cache"))]
{
update_call().await
}
}
#[instrument(skip_all)]
#[cfg(feature = "v1")]
async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
) -> CustomResult<bool, Self::Error> {
let conn = pg_accounts_connection_write(self).await?;
let delete_call = || async {
storage::MerchantConnectorAccount::delete_by_merchant_id_merchant_connector_id(
&conn,
merchant_id,
merchant_connector_id,
)
.await
.map_err(|error| report!(Self::Error::from(error)))
};
#[cfg(feature = "accounts_cache")]
{
// We need to fetch mca here because the key that's saved in cache in
// {merchant_id}_{connector_label}.
// Used function from storage model to reuse the connection that made here instead of
// creating new.
let mca = storage::MerchantConnectorAccount::find_by_merchant_id_merchant_connector_id(
&conn,
merchant_id,
merchant_connector_id,
)
.await
.map_err(|error| report!(Self::Error::from(error)))?;
let _profile_id = mca
.profile_id
.ok_or(Self::Error::ValueNotFound("profile_id".to_string()))?;
cache::publish_and_redact_multiple(
self,
[
cache::CacheKind::Accounts(
format!(
"{}_{}",
mca.merchant_id.get_string_repr(),
_profile_id.get_string_repr()
)
.into(),
),
cache::CacheKind::CGraph(
format!(
"cgraph_{}_{}",
mca.merchant_id.get_string_repr(),
_profile_id.get_string_repr()
)
.into(),
),
cache::CacheKind::PmFiltersCGraph(
format!(
"pm_filters_cgraph_{}_{}",
mca.merchant_id.get_string_repr(),
_profile_id.get_string_repr()
)
.into(),
),
],
delete_call,
)
.await
}
#[cfg(not(feature = "accounts_cache"))]
{
delete_call().await
}
}
#[instrument(skip_all)]
#[cfg(feature = "v2")]
async fn delete_merchant_connector_account_by_id(
&self,
id: &common_utils::id_type::MerchantConnectorAccountId,
) -> CustomResult<bool, Self::Error> {
let conn = pg_accounts_connection_write(self).await?;
let delete_call = || async {
storage::MerchantConnectorAccount::delete_by_id(&conn, id)
.await
.map_err(|error| report!(Self::Error::from(error)))
};
#[cfg(feature = "accounts_cache")]
{
// We need to fetch mca here because the key that's saved in cache in
// {merchant_id}_{connector_label}.
// Used function from storage model to reuse the connection that made here instead of
// creating new.
let mca = storage::MerchantConnectorAccount::find_by_id(&conn, id)
.await
.map_err(|error| report!(Self::Error::from(error)))?;
let _profile_id = mca.profile_id;
cache::publish_and_redact_multiple(
self,
[
cache::CacheKind::Accounts(
format!(
"{}_{}",
mca.merchant_id.get_string_repr(),
_profile_id.get_string_repr()
)
.into(),
),
cache::CacheKind::CGraph(
format!(
"cgraph_{}_{}",
mca.merchant_id.get_string_repr(),
_profile_id.get_string_repr()
)
.into(),
),
cache::CacheKind::PmFiltersCGraph(
format!(
"pm_filters_cgraph_{}_{}",
mca.merchant_id.get_string_repr(),
_profile_id.get_string_repr()
)
.into(),
),
],
delete_call,
)
.await
}
#[cfg(not(feature = "accounts_cache"))]
{
delete_call().await
}
}
}
#[async_trait::async_trait]
impl MerchantConnectorAccountInterface for MockDb {
type Error = StorageError;
async fn update_multiple_merchant_connector_accounts(
&self,
_merchant_connector_accounts: Vec<(
domain::MerchantConnectorAccount,
storage::MerchantConnectorAccountUpdateInternal,
)>,
) -> CustomResult<(), StorageError> {
// No need to implement this function for `MockDb` as this function will be removed after the
// apple pay certificate migration
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn find_merchant_connector_account_by_merchant_id_connector_label(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
connector: &str,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
match self
.merchant_connector_accounts
.lock()
.await
.iter()
.find(|account| {
account.merchant_id == *merchant_id
&& account.connector_label == Some(connector.to_string())
})
.cloned()
.async_map(|account| async {
account
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
{
Some(result) => result,
None => {
return Err(StorageError::ValueNotFound(
"cannot find merchant connector account".to_string(),
)
.into())
}
}
}
async fn list_enabled_connector_accounts_by_profile_id(
&self,
_state: &KeyManagerState,
_profile_id: &common_utils::id_type::ProfileId,
_key_store: &MerchantKeyStore,
_connector_type: common_enums::ConnectorType,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, StorageError> {
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn find_merchant_connector_account_by_merchant_id_connector_name(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, StorageError> {
let accounts = self
.merchant_connector_accounts
.lock()
.await
.iter()
.filter(|account| {
account.merchant_id == *merchant_id && account.connector_name == connector_name
})
.cloned()
.collect::<Vec<_>>();
let mut output = Vec::with_capacity(accounts.len());
for account in accounts.into_iter() {
output.push(
account
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?,
)
}
Ok(output)
}
#[cfg(feature = "v1")]
async fn find_merchant_connector_account_by_profile_id_connector_name(
&self,
state: &KeyManagerState,
profile_id: &common_utils::id_type::ProfileId,
connector_name: &str,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
let maybe_mca = self
.merchant_connector_accounts
.lock()
.await
.iter()
.find(|account| {
account.profile_id.eq(&Some(profile_id.to_owned()))
&& account.connector_name == connector_name
})
.cloned();
match maybe_mca {
Some(mca) => mca
.to_owned()
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError),
None => Err(StorageError::ValueNotFound(
"cannot find merchant connector account".to_string(),
)
.into()),
}
}
#[cfg(feature = "v1")]
async fn find_by_merchant_connector_account_merchant_id_merchant_connector_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
match self
.merchant_connector_accounts
.lock()
.await
.iter()
.find(|account| {
account.merchant_id == *merchant_id
&& account.merchant_connector_id == *merchant_connector_id
})
.cloned()
.async_map(|account| async {
account
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
{
Some(result) => result,
None => {
return Err(StorageError::ValueNotFound(
"cannot find merchant connector account".to_string(),
)
.into())
}
}
}
#[cfg(feature = "v2")]
async fn find_merchant_connector_account_by_id(
&self,
state: &KeyManagerState,
id: &common_utils::id_type::MerchantConnectorAccountId,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
match self
.merchant_connector_accounts
.lock()
.await
.iter()
.find(|account| account.get_id() == *id)
.cloned()
.async_map(|account| async {
account
.convert(
state,
key_store.key.get_inner(),
common_utils::types::keymanager::Identifier::Merchant(
key_store.merchant_id.clone(),
),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
{
Some(result) => result,
None => {
return Err(StorageError::ValueNotFound(
"cannot find merchant connector account".to_string(),
)
.into())
}
}
}
#[cfg(feature = "v1")]
async fn insert_merchant_connector_account(
&self,
state: &KeyManagerState,
t: domain::MerchantConnectorAccount,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
let mut accounts = self.merchant_connector_accounts.lock().await;
let account = storage::MerchantConnectorAccount {
merchant_id: t.merchant_id,
connector_name: t.connector_name,
connector_account_details: t.connector_account_details.into(),
test_mode: t.test_mode,
disabled: t.disabled,
merchant_connector_id: t.merchant_connector_id.clone(),
id: Some(t.merchant_connector_id),
payment_methods_enabled: t.payment_methods_enabled,
metadata: t.metadata,
frm_configs: None,
frm_config: t.frm_configs,
connector_type: t.connector_type,
connector_label: t.connector_label,
business_country: t.business_country,
business_label: t.business_label,
business_sub_label: t.business_sub_label,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
connector_webhook_details: t.connector_webhook_details,
profile_id: Some(t.profile_id),
applepay_verified_domains: t.applepay_verified_domains,
pm_auth_config: t.pm_auth_config,
status: t.status,
connector_wallets_details: t.connector_wallets_details.map(Encryption::from),
additional_merchant_data: t.additional_merchant_data.map(|data| data.into()),
version: t.version,
};
accounts.push(account.clone());
account
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(feature = "v2")]
async fn insert_merchant_connector_account(
&self,
state: &KeyManagerState,
t: domain::MerchantConnectorAccount,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
let mut accounts = self.merchant_connector_accounts.lock().await;
let account = storage::MerchantConnectorAccount {
id: t.id,
merchant_id: t.merchant_id,
connector_name: t.connector_name,
connector_account_details: t.connector_account_details.into(),
disabled: t.disabled,
payment_methods_enabled: t.payment_methods_enabled,
metadata: t.metadata,
frm_config: t.frm_configs,
connector_type: t.connector_type,
connector_label: t.connector_label,
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
connector_webhook_details: t.connector_webhook_details,
profile_id: t.profile_id,
applepay_verified_domains: t.applepay_verified_domains,
pm_auth_config: t.pm_auth_config,
status: t.status,
connector_wallets_details: t.connector_wallets_details.map(Encryption::from),
additional_merchant_data: t.additional_merchant_data.map(|data| data.into()),
version: t.version,
feature_metadata: t.feature_metadata.map(From::from),
};
accounts.push(account.clone());
account
.convert(
state,
key_store.key.get_inner(),
common_utils::types::keymanager::Identifier::Merchant(
key_store.merchant_id.clone(),
),
)
.await
.change_context(StorageError::DecryptionError)
}
async fn find_merchant_connector_account_by_merchant_id_and_disabled_list(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
get_disabled: bool,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccounts, StorageError> {
let accounts = self
.merchant_connector_accounts
.lock()
.await
.iter()
.filter(|account: &&storage::MerchantConnectorAccount| {
if get_disabled {
account.merchant_id == *merchant_id
} else {
account.merchant_id == *merchant_id && account.disabled == Some(false)
}
})
.cloned()
.collect::<Vec<storage::MerchantConnectorAccount>>();
let mut output = Vec::with_capacity(accounts.len());
for account in accounts.into_iter() {
output.push(
account
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?,
)
}
Ok(domain::MerchantConnectorAccounts::new(output))
}
#[cfg(all(feature = "olap", feature = "v2"))]
async fn list_connector_account_by_profile_id(
&self,
state: &KeyManagerState,
profile_id: &common_utils::id_type::ProfileId,
key_store: &MerchantKeyStore,
) -> CustomResult<Vec<domain::MerchantConnectorAccount>, StorageError> {
let accounts = self
.merchant_connector_accounts
.lock()
.await
.iter()
.filter(|account: &&storage::MerchantConnectorAccount| {
account.profile_id == *profile_id
})
.cloned()
.collect::<Vec<storage::MerchantConnectorAccount>>();
let mut output = Vec::with_capacity(accounts.len());
for account in accounts.into_iter() {
output.push(
account
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?,
)
}
Ok(output)
}
#[cfg(feature = "v1")]
async fn update_merchant_connector_account(
&self,
state: &KeyManagerState,
this: domain::MerchantConnectorAccount,
merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
let mca_update_res = self
.merchant_connector_accounts
.lock()
.await
.iter_mut()
.find(|account| account.merchant_connector_id == this.merchant_connector_id)
.map(|a| {
let updated =
merchant_connector_account.create_merchant_connector_account(a.clone());
*a = updated.clone();
updated
})
.async_map(|account| async {
account
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await;
match mca_update_res {
Some(result) => result,
None => {
return Err(StorageError::ValueNotFound(
"cannot find merchant connector account to update".to_string(),
)
.into())
}
}
}
#[cfg(feature = "v2")]
async fn update_merchant_connector_account(
&self,
state: &KeyManagerState,
this: domain::MerchantConnectorAccount,
merchant_connector_account: storage::MerchantConnectorAccountUpdateInternal,
key_store: &MerchantKeyStore,
) -> CustomResult<domain::MerchantConnectorAccount, StorageError> {
let mca_update_res = self
.merchant_connector_accounts
.lock()
.await
.iter_mut()
.find(|account| account.get_id() == this.get_id())
.map(|a| {
let updated =
merchant_connector_account.create_merchant_connector_account(a.clone());
*a = updated.clone();
updated
})
.async_map(|account| async {
account
.convert(
state,
key_store.key.get_inner(),
common_utils::types::keymanager::Identifier::Merchant(
key_store.merchant_id.clone(),
),
)
.await
.change_context(StorageError::DecryptionError)
})
.await;
match mca_update_res {
Some(result) => result,
None => {
return Err(StorageError::ValueNotFound(
"cannot find merchant connector account to update".to_string(),
)
.into())
}
}
}
#[cfg(feature = "v1")]
async fn delete_merchant_connector_account_by_merchant_id_merchant_connector_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
) -> CustomResult<bool, StorageError> {
let mut accounts = self.merchant_connector_accounts.lock().await;
match accounts.iter().position(|account| {
account.merchant_id == *merchant_id
&& account.merchant_connector_id == *merchant_connector_id
}) {
Some(index) => {
accounts.remove(index);
return Ok(true);
}
None => {
return Err(StorageError::ValueNotFound(
"cannot find merchant connector account to delete".to_string(),
)
.into())
}
}
}
#[cfg(feature = "v2")]
async fn delete_merchant_connector_account_by_id(
&self,
id: &common_utils::id_type::MerchantConnectorAccountId,
) -> CustomResult<bool, StorageError> {
let mut accounts = self.merchant_connector_accounts.lock().await;
match accounts.iter().position(|account| account.get_id() == *id) {
Some(index) => {
accounts.remove(index);
return Ok(true);
}
None => {
return Err(StorageError::ValueNotFound(
"cannot find merchant connector account to delete".to_string(),
)
.into())
}
}
}
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/merchant_connector_account.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 10476
}
|
large_file_4023498033037075140
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/configs.rs
</path>
<file>
use diesel_models::configs as storage;
use error_stack::report;
use hyperswitch_domain_models::configs::ConfigInterface;
use router_env::{instrument, tracing};
use crate::{
connection,
errors::StorageError,
kv_router_store,
redis::{
cache,
cache::{CacheKind, CONFIG_CACHE},
},
store::ConfigUpdateInternal,
CustomResult, DatabaseStore, MockDb, RouterStore,
};
#[async_trait::async_trait]
impl<T: DatabaseStore> ConfigInterface for kv_router_store::KVRouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
async fn insert_config(
&self,
config: storage::ConfigNew,
) -> CustomResult<storage::Config, Self::Error> {
self.router_store.insert_config(config).await
}
#[instrument(skip_all)]
async fn update_config_in_database(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, StorageError> {
self.router_store
.update_config_in_database(key, config_update)
.await
}
//update in DB and remove in redis and cache
#[instrument(skip_all)]
async fn update_config_by_key(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, StorageError> {
self.router_store
.update_config_by_key(key, config_update)
.await
}
#[instrument(skip_all)]
async fn find_config_by_key_from_db(
&self,
key: &str,
) -> CustomResult<storage::Config, StorageError> {
self.router_store.find_config_by_key_from_db(key).await
}
//check in cache, then redis then finally DB, and on the way back populate redis and cache
#[instrument(skip_all)]
async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> {
self.router_store.find_config_by_key(key).await
}
#[instrument(skip_all)]
async fn find_config_by_key_unwrap_or(
&self,
key: &str,
// If the config is not found it will be cached with the default value.
default_config: Option<String>,
) -> CustomResult<storage::Config, StorageError> {
self.router_store
.find_config_by_key_unwrap_or(key, default_config)
.await
}
#[instrument(skip_all)]
async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> {
self.router_store.delete_config_by_key(key).await
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> ConfigInterface for RouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
async fn insert_config(
&self,
config: storage::ConfigNew,
) -> CustomResult<storage::Config, StorageError> {
let conn = connection::pg_connection_write(self).await?;
let inserted = config
.insert(&conn)
.await
.map_err(|error| report!(StorageError::from(error)))?;
cache::redact_from_redis_and_publish(self, [CacheKind::Config((&inserted.key).into())])
.await?;
Ok(inserted)
}
#[instrument(skip_all)]
async fn update_config_in_database(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Config::update_by_key(&conn, key, config_update)
.await
.map_err(|error| report!(StorageError::from(error)))
}
//update in DB and remove in redis and cache
#[instrument(skip_all)]
async fn update_config_by_key(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, StorageError> {
cache::publish_and_redact(self, CacheKind::Config(key.into()), || {
self.update_config_in_database(key, config_update)
})
.await
}
#[instrument(skip_all)]
async fn find_config_by_key_from_db(
&self,
key: &str,
) -> CustomResult<storage::Config, StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Config::find_by_key(&conn, key)
.await
.map_err(|error| report!(StorageError::from(error)))
}
//check in cache, then redis then finally DB, and on the way back populate redis and cache
#[instrument(skip_all)]
async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> {
let find_config_by_key_from_db = || async {
let conn = connection::pg_connection_write(self).await?;
storage::Config::find_by_key(&conn, key)
.await
.map_err(|error| report!(StorageError::from(error)))
};
cache::get_or_populate_in_memory(self, key, find_config_by_key_from_db, &CONFIG_CACHE).await
}
#[instrument(skip_all)]
async fn find_config_by_key_unwrap_or(
&self,
key: &str,
// If the config is not found it will be cached with the default value.
default_config: Option<String>,
) -> CustomResult<storage::Config, StorageError> {
let find_else_unwrap_or = || async {
let conn = connection::pg_connection_write(self).await?;
match storage::Config::find_by_key(&conn, key)
.await
.map_err(|error| report!(StorageError::from(error)))
{
Ok(a) => Ok(a),
Err(err) => {
if err.current_context().is_db_not_found() {
default_config
.map(|c| {
storage::ConfigNew {
key: key.to_string(),
config: c,
}
.into()
})
.ok_or(err)
} else {
Err(err)
}
}
}
};
cache::get_or_populate_in_memory(self, key, find_else_unwrap_or, &CONFIG_CACHE).await
}
#[instrument(skip_all)]
async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, StorageError> {
let conn = connection::pg_connection_write(self).await?;
let deleted = storage::Config::delete_by_key(&conn, key)
.await
.map_err(|error| report!(StorageError::from(error)))?;
cache::redact_from_redis_and_publish(self, [CacheKind::Config((&deleted.key).into())])
.await?;
Ok(deleted)
}
}
#[async_trait::async_trait]
impl ConfigInterface for MockDb {
type Error = StorageError;
#[instrument(skip_all)]
async fn insert_config(
&self,
config: storage::ConfigNew,
) -> CustomResult<storage::Config, Self::Error> {
let mut configs = self.configs.lock().await;
let config_new = storage::Config {
key: config.key,
config: config.config,
};
configs.push(config_new.clone());
Ok(config_new)
}
async fn update_config_in_database(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, Self::Error> {
self.update_config_by_key(key, config_update).await
}
async fn update_config_by_key(
&self,
key: &str,
config_update: storage::ConfigUpdate,
) -> CustomResult<storage::Config, Self::Error> {
let result = self
.configs
.lock()
.await
.iter_mut()
.find(|c| c.key == key)
.ok_or_else(|| {
StorageError::ValueNotFound("cannot find config to update".to_string()).into()
})
.map(|c| {
let config_updated =
ConfigUpdateInternal::from(config_update).create_config(c.clone());
*c = config_updated.clone();
config_updated
});
result
}
async fn delete_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error> {
let mut configs = self.configs.lock().await;
let result = configs
.iter()
.position(|c| c.key == key)
.map(|index| configs.remove(index))
.ok_or_else(|| {
StorageError::ValueNotFound("cannot find config to delete".to_string()).into()
});
result
}
async fn find_config_by_key(&self, key: &str) -> CustomResult<storage::Config, Self::Error> {
let configs = self.configs.lock().await;
let config = configs.iter().find(|c| c.key == key).cloned();
config.ok_or_else(|| StorageError::ValueNotFound("cannot find config".to_string()).into())
}
async fn find_config_by_key_unwrap_or(
&self,
key: &str,
_default_config: Option<String>,
) -> CustomResult<storage::Config, Self::Error> {
self.find_config_by_key(key).await
}
async fn find_config_by_key_from_db(
&self,
key: &str,
) -> CustomResult<storage::Config, Self::Error> {
self.find_config_by_key(key).await
}
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/configs.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2108
}
|
large_file_-8658755190753490785
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/lib.rs
</path>
<file>
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"
}
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/lib.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3574
}
|
large_file_-8974719706452346473
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/business_profile.rs
</path>
<file>
use common_utils::ext_traits::AsyncExt;
use diesel_models::business_profile::{self, ProfileUpdateInternal};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
behaviour::{Conversion, ReverseConversion},
business_profile as domain,
business_profile::ProfileInterface,
merchant_key_store::MerchantKeyStore,
};
use router_env::{instrument, tracing};
use crate::{
kv_router_store,
utils::{pg_accounts_connection_read, pg_accounts_connection_write},
CustomResult, DatabaseStore, KeyManagerState, MockDb, RouterStore, StorageError,
};
#[async_trait::async_trait]
impl<T: DatabaseStore> ProfileInterface for kv_router_store::KVRouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
async fn insert_business_profile(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
business_profile: domain::Profile,
) -> CustomResult<domain::Profile, StorageError> {
self.router_store
.insert_business_profile(key_manager_state, merchant_key_store, business_profile)
.await
}
#[instrument(skip_all)]
async fn find_business_profile_by_profile_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
) -> CustomResult<domain::Profile, StorageError> {
self.router_store
.find_business_profile_by_profile_id(key_manager_state, merchant_key_store, profile_id)
.await
}
async fn find_business_profile_by_merchant_id_profile_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
) -> CustomResult<domain::Profile, StorageError> {
self.router_store
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
merchant_key_store,
merchant_id,
profile_id,
)
.await
}
#[instrument(skip_all)]
async fn find_business_profile_by_profile_name_merchant_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
profile_name: &str,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<domain::Profile, StorageError> {
self.router_store
.find_business_profile_by_profile_name_merchant_id(
key_manager_state,
merchant_key_store,
profile_name,
merchant_id,
)
.await
}
#[instrument(skip_all)]
async fn update_profile_by_profile_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
current_state: domain::Profile,
profile_update: domain::ProfileUpdate,
) -> CustomResult<domain::Profile, StorageError> {
self.router_store
.update_profile_by_profile_id(
key_manager_state,
merchant_key_store,
current_state,
profile_update,
)
.await
}
#[instrument(skip_all)]
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, StorageError> {
self.router_store
.delete_profile_by_profile_id_merchant_id(profile_id, merchant_id)
.await
}
#[instrument(skip_all)]
async fn list_profile_by_merchant_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<domain::Profile>, StorageError> {
self.router_store
.list_profile_by_merchant_id(key_manager_state, merchant_key_store, merchant_id)
.await
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> ProfileInterface for RouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
async fn insert_business_profile(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
business_profile: domain::Profile,
) -> CustomResult<domain::Profile, StorageError> {
let conn = pg_accounts_connection_write(self).await?;
business_profile
.construct_new()
.await
.change_context(StorageError::EncryptionError)?
.insert(&conn)
.await
.map_err(|error| report!(StorageError::from(error)))?
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[instrument(skip_all)]
async fn find_business_profile_by_profile_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
) -> CustomResult<domain::Profile, StorageError> {
let conn = pg_accounts_connection_read(self).await?;
self.call_database(
key_manager_state,
merchant_key_store,
business_profile::Profile::find_by_profile_id(&conn, profile_id),
)
.await
}
async fn find_business_profile_by_merchant_id_profile_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
) -> CustomResult<domain::Profile, StorageError> {
let conn = pg_accounts_connection_read(self).await?;
self.call_database(
key_manager_state,
merchant_key_store,
business_profile::Profile::find_by_merchant_id_profile_id(
&conn,
merchant_id,
profile_id,
),
)
.await
}
#[instrument(skip_all)]
async fn find_business_profile_by_profile_name_merchant_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
profile_name: &str,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<domain::Profile, StorageError> {
let conn = pg_accounts_connection_read(self).await?;
self.call_database(
key_manager_state,
merchant_key_store,
business_profile::Profile::find_by_profile_name_merchant_id(
&conn,
profile_name,
merchant_id,
),
)
.await
}
#[instrument(skip_all)]
async fn update_profile_by_profile_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
current_state: domain::Profile,
profile_update: domain::ProfileUpdate,
) -> CustomResult<domain::Profile, StorageError> {
let conn = pg_accounts_connection_write(self).await?;
Conversion::convert(current_state)
.await
.change_context(StorageError::EncryptionError)?
.update_by_profile_id(&conn, ProfileUpdateInternal::from(profile_update))
.await
.map_err(|error| report!(StorageError::from(error)))?
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[instrument(skip_all)]
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, StorageError> {
let conn = pg_accounts_connection_write(self).await?;
business_profile::Profile::delete_by_profile_id_merchant_id(&conn, profile_id, merchant_id)
.await
.map_err(|error| report!(StorageError::from(error)))
}
#[instrument(skip_all)]
async fn list_profile_by_merchant_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<domain::Profile>, StorageError> {
let conn = pg_accounts_connection_read(self).await?;
self.find_resources(
key_manager_state,
merchant_key_store,
business_profile::Profile::list_profile_by_merchant_id(&conn, merchant_id),
)
.await
}
}
#[async_trait::async_trait]
impl ProfileInterface for MockDb {
type Error = StorageError;
async fn insert_business_profile(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
business_profile: domain::Profile,
) -> CustomResult<domain::Profile, StorageError> {
let stored_business_profile = Conversion::convert(business_profile)
.await
.change_context(StorageError::EncryptionError)?;
self.business_profiles
.lock()
.await
.push(stored_business_profile.clone());
stored_business_profile
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
async fn find_business_profile_by_profile_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
profile_id: &common_utils::id_type::ProfileId,
) -> CustomResult<domain::Profile, StorageError> {
self.business_profiles
.lock()
.await
.iter()
.find(|business_profile| business_profile.get_id() == profile_id)
.cloned()
.async_map(|business_profile| async {
business_profile
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
StorageError::ValueNotFound(format!(
"No business profile found for profile_id = {profile_id:?}"
))
.into(),
)
}
async fn find_business_profile_by_merchant_id_profile_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
) -> CustomResult<domain::Profile, StorageError> {
self.business_profiles
.lock()
.await
.iter()
.find(|business_profile| {
business_profile.merchant_id == *merchant_id
&& business_profile.get_id() == profile_id
})
.cloned()
.async_map(|business_profile| async {
business_profile
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
StorageError::ValueNotFound(format!(
"No business profile found for merchant_id = {merchant_id:?} and profile_id = {profile_id:?}"
))
.into(),
)
}
async fn update_profile_by_profile_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
current_state: domain::Profile,
profile_update: domain::ProfileUpdate,
) -> CustomResult<domain::Profile, StorageError> {
let profile_id = current_state.get_id().to_owned();
self.business_profiles
.lock()
.await
.iter_mut()
.find(|business_profile| business_profile.get_id() == current_state.get_id())
.async_map(|business_profile| async {
let profile_updated = ProfileUpdateInternal::from(profile_update).apply_changeset(
Conversion::convert(current_state)
.await
.change_context(StorageError::EncryptionError)?,
);
*business_profile = profile_updated.clone();
profile_updated
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
StorageError::ValueNotFound(format!(
"No business profile found for profile_id = {profile_id:?}",
))
.into(),
)
}
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, StorageError> {
let mut business_profiles = self.business_profiles.lock().await;
let index = business_profiles
.iter()
.position(|business_profile| {
business_profile.get_id() == profile_id
&& business_profile.merchant_id == *merchant_id
})
.ok_or::<StorageError>(StorageError::ValueNotFound(format!(
"No business profile found for profile_id = {profile_id:?} and merchant_id = {merchant_id:?}"
)))?;
business_profiles.remove(index);
Ok(true)
}
async fn list_profile_by_merchant_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Vec<domain::Profile>, StorageError> {
let business_profiles = self
.business_profiles
.lock()
.await
.iter()
.filter(|business_profile| business_profile.merchant_id == *merchant_id)
.cloned()
.collect::<Vec<_>>();
let mut domain_business_profiles = Vec::with_capacity(business_profiles.len());
for business_profile in business_profiles {
let domain_profile = business_profile
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?;
domain_business_profiles.push(domain_profile);
}
Ok(domain_business_profiles)
}
async fn find_business_profile_by_profile_name_merchant_id(
&self,
key_manager_state: &KeyManagerState,
merchant_key_store: &MerchantKeyStore,
profile_name: &str,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<domain::Profile, StorageError> {
self.business_profiles
.lock()
.await
.iter()
.find(|business_profile| {
business_profile.profile_name == profile_name
&& business_profile.merchant_id == *merchant_id
})
.cloned()
.async_map(|business_profile| async {
business_profile
.convert(
key_manager_state,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
.transpose()?
.ok_or(
StorageError::ValueNotFound(format!(
"No business profile found for profile_name = {profile_name} and merchant_id = {merchant_id:?}"
))
.into(),
)
}
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/business_profile.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3433
}
|
large_file_4469905062043723593
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/errors.rs
</path>
<file>
pub use common_enums::{ApiClientError, ApplicationError, ApplicationResult};
pub use redis_interface::errors::RedisError;
use crate::store::errors::DatabaseError;
pub type StorageResult<T> = error_stack::Result<T, StorageError>;
#[derive(Debug, thiserror::Error)]
pub enum StorageError {
#[error("Initialization Error")]
InitializationError,
#[error("DatabaseError: {0:?}")]
DatabaseError(error_stack::Report<DatabaseError>),
#[error("ValueNotFound: {0}")]
ValueNotFound(String),
#[error("DuplicateValue: {entity} already exists {key:?}")]
DuplicateValue {
entity: &'static str,
key: Option<String>,
},
#[error("Timed out while trying to connect to the database")]
DatabaseConnectionError,
#[error("KV error")]
KVError,
#[error("Serialization failure")]
SerializationFailed,
#[error("MockDb error")]
MockDbError,
#[error("Kafka error")]
KafkaError,
#[error("Customer with this id is Redacted")]
CustomerRedacted,
#[error("Deserialization failure")]
DeserializationFailed,
#[error("Error while encrypting data")]
EncryptionError,
#[error("Error while decrypting data from database")]
DecryptionError,
#[error("RedisError: {0:?}")]
RedisError(error_stack::Report<RedisError>),
}
impl From<error_stack::Report<RedisError>> for StorageError {
fn from(err: error_stack::Report<RedisError>) -> Self {
match err.current_context() {
RedisError::NotFound => Self::ValueNotFound("redis value not found".to_string()),
RedisError::JsonSerializationFailed => Self::SerializationFailed,
RedisError::JsonDeserializationFailed => Self::DeserializationFailed,
_ => Self::RedisError(err),
}
}
}
impl From<diesel::result::Error> for StorageError {
fn from(err: diesel::result::Error) -> Self {
Self::from(error_stack::report!(DatabaseError::from(err)))
}
}
impl From<error_stack::Report<DatabaseError>> for StorageError {
fn from(err: error_stack::Report<DatabaseError>) -> Self {
match err.current_context() {
DatabaseError::DatabaseConnectionError => Self::DatabaseConnectionError,
DatabaseError::NotFound => Self::ValueNotFound(String::from("db value not found")),
DatabaseError::UniqueViolation => Self::DuplicateValue {
entity: "db entity",
key: None,
},
_ => Self::DatabaseError(err),
}
}
}
impl StorageError {
pub fn is_db_not_found(&self) -> bool {
match self {
Self::DatabaseError(err) => matches!(err.current_context(), DatabaseError::NotFound),
Self::ValueNotFound(_) => true,
Self::RedisError(err) => matches!(err.current_context(), RedisError::NotFound),
_ => false,
}
}
pub fn is_db_unique_violation(&self) -> bool {
match self {
Self::DatabaseError(err) => {
matches!(err.current_context(), DatabaseError::UniqueViolation,)
}
Self::DuplicateValue { .. } => true,
_ => false,
}
}
}
pub trait RedisErrorExt {
#[track_caller]
fn to_redis_failed_response(self, key: &str) -> error_stack::Report<StorageError>;
}
impl RedisErrorExt for error_stack::Report<RedisError> {
fn to_redis_failed_response(self, key: &str) -> error_stack::Report<StorageError> {
match self.current_context() {
RedisError::NotFound => self.change_context(StorageError::ValueNotFound(format!(
"Data does not exist for key {key}",
))),
RedisError::SetNxFailed | RedisError::SetAddMembersFailed => {
self.change_context(StorageError::DuplicateValue {
entity: "redis",
key: Some(key.to_string()),
})
}
_ => self.change_context(StorageError::KVError),
}
}
}
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum ConnectorError {
#[error("Error while obtaining URL for the integration")]
FailedToObtainIntegrationUrl,
#[error("Failed to encode connector request")]
RequestEncodingFailed,
#[error("Request encoding failed : {0}")]
RequestEncodingFailedWithReason(String),
#[error("Parsing failed")]
ParsingFailed,
#[error("Failed to deserialize connector response")]
ResponseDeserializationFailed,
#[error("Failed to execute a processing step: {0:?}")]
ProcessingStepFailed(Option<bytes::Bytes>),
#[error("The connector returned an unexpected response: {0:?}")]
UnexpectedResponseError(bytes::Bytes),
#[error("Failed to parse custom routing rules from merchant account")]
RoutingRulesParsingError,
#[error("Failed to obtain preferred connector from merchant account")]
FailedToObtainPreferredConnector,
#[error("An invalid connector name was provided")]
InvalidConnectorName,
#[error("An invalid Wallet was used")]
InvalidWallet,
#[error("Failed to handle connector response")]
ResponseHandlingFailed,
#[error("Missing required field: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error("Missing required fields: {field_names:?}")]
MissingRequiredFields { field_names: Vec<&'static str> },
#[error("Failed to obtain authentication type")]
FailedToObtainAuthType,
#[error("Failed to obtain certificate")]
FailedToObtainCertificate,
#[error("Connector meta data not found")]
NoConnectorMetaData,
#[error("Failed to obtain certificate key")]
FailedToObtainCertificateKey,
#[error("This step has not been implemented for: {0}")]
NotImplemented(String),
#[error("{message} is not supported by {connector}")]
NotSupported {
message: String,
connector: &'static str,
payment_experience: String,
},
#[error("{flow} flow not supported by {connector} connector")]
FlowNotSupported { flow: String, connector: String },
#[error("Connector '{connector}' rejected field '{field_name}': length {received_length} exceeds maximum of {max_length}'")]
MaxFieldLengthViolated {
connector: String,
field_name: String,
max_length: usize,
received_length: usize,
},
#[error("Capture method not supported")]
CaptureMethodNotSupported,
#[error("Missing connector transaction ID")]
MissingConnectorTransactionID,
#[error("Missing connector refund ID")]
MissingConnectorRefundID,
#[error("Webhooks not implemented for this connector")]
WebhooksNotImplemented,
#[error("Failed to decode webhook event body")]
WebhookBodyDecodingFailed,
#[error("Signature not found for incoming webhook")]
WebhookSignatureNotFound,
#[error("Failed to verify webhook source")]
WebhookSourceVerificationFailed,
#[error("Could not find merchant secret in DB for incoming webhook source verification")]
WebhookVerificationSecretNotFound,
#[error("Incoming webhook object reference ID not found")]
WebhookReferenceIdNotFound,
#[error("Incoming webhook event type not found")]
WebhookEventTypeNotFound,
#[error("Incoming webhook event resource object not found")]
WebhookResourceObjectNotFound,
#[error("Could not respond to the incoming webhook event")]
WebhookResponseEncodingFailed,
#[error("Invalid Date/time format")]
InvalidDateFormat,
#[error("Date Formatting Failed")]
DateFormattingFailed,
#[error("Invalid Data format")]
InvalidDataFormat { field_name: &'static str },
#[error("Payment Method data / Payment Method Type / Payment Experience Mismatch ")]
MismatchedPaymentData,
#[error("Field {fields} doesn't match with the ones used during mandate creation")]
MandatePaymentDataMismatch { fields: String },
#[error("Failed to parse Wallet token")]
InvalidWalletToken { wallet_name: String },
#[error("Missing Connector Related Transaction ID")]
MissingConnectorRelatedTransactionID { id: String },
#[error("File Validation failed")]
FileValidationFailed { reason: String },
#[error("Missing 3DS redirection payload: {field_name}")]
MissingConnectorRedirectionPayload { field_name: &'static str },
}
#[derive(Debug, thiserror::Error)]
pub enum HealthCheckDBError {
#[error("Error while connecting to database")]
DBError,
#[error("Error while writing to database")]
DBWriteError,
#[error("Error while reading element in the database")]
DBReadError,
#[error("Error while deleting element in the database")]
DBDeleteError,
#[error("Unpredictable error occurred")]
UnknownError,
#[error("Error in database transaction")]
TransactionError,
#[error("Error while executing query in Sqlx Analytics")]
SqlxAnalyticsError,
#[error("Error while executing query in Clickhouse Analytics")]
ClickhouseAnalyticsError,
#[error("Error while executing query in Opensearch")]
OpensearchError,
}
impl From<diesel::result::Error> for HealthCheckDBError {
fn from(error: diesel::result::Error) -> Self {
match error {
diesel::result::Error::DatabaseError(_, _) => Self::DBError,
diesel::result::Error::RollbackErrorOnCommit { .. }
| diesel::result::Error::RollbackTransaction
| diesel::result::Error::AlreadyInTransaction
| diesel::result::Error::NotInTransaction
| diesel::result::Error::BrokenTransactionManager => Self::TransactionError,
_ => Self::UnknownError,
}
}
}
#[derive(Debug, thiserror::Error)]
pub enum HealthCheckRedisError {
#[error("Failed to establish Redis connection")]
RedisConnectionError,
#[error("Failed to set key value in Redis")]
SetFailed,
#[error("Failed to get key value in Redis")]
GetFailed,
#[error("Failed to delete key value in Redis")]
DeleteFailed,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum HealthCheckLockerError {
#[error("Failed to establish Locker connection")]
FailedToCallLocker,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum HealthCheckGRPCServiceError {
#[error("Failed to establish connection with gRPC service")]
FailedToCallService,
}
#[derive(thiserror::Error, Debug, Clone)]
pub enum RecoveryError {
#[error("Failed to make a recovery payment")]
PaymentCallFailed,
#[error("Encountered a Process Tracker Task Failure")]
ProcessTrackerFailure,
#[error("The encountered task is invalid")]
InvalidTask,
#[error("The Process Tracker data was not found")]
ValueNotFound,
#[error("Failed to update billing connector")]
RecordBackToBillingConnectorFailed,
#[error("Failed to fetch billing connector account id")]
BillingMerchantConnectorAccountIdNotFound,
#[error("Failed to generate payment sync data")]
PaymentsResponseGenerationFailed,
#[error("Outgoing Webhook Failed")]
RevenueRecoveryOutgoingWebhookFailed,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum HealthCheckDecisionEngineError {
#[error("Failed to establish Decision Engine connection")]
FailedToCallDecisionEngineService,
}
#[derive(Debug, Clone, thiserror::Error)]
pub enum HealthCheckUnifiedConnectorServiceError {
#[error("Failed to establish Unified Connector Service connection")]
FailedToCallUnifiedConnectorService,
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/errors.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2457
}
|
large_file_1484038564034034151
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/customers.rs
</path>
<file>
use common_utils::{id_type, pii};
use diesel_models::{customers, kv};
use error_stack::ResultExt;
use futures::future::try_join_all;
use hyperswitch_domain_models::{
behaviour::{Conversion, ReverseConversion},
customer as domain,
merchant_key_store::MerchantKeyStore,
};
use masking::PeekInterface;
use router_env::{instrument, tracing};
use crate::{
diesel_error_to_data_error,
errors::StorageError,
kv_router_store,
redis::kv_store::{decide_storage_scheme, KvStorePartition, Op, PartitionKey},
store::enums::MerchantStorageScheme,
utils::{pg_connection_read, pg_connection_write},
CustomResult, DatabaseStore, KeyManagerState, MockDb, RouterStore,
};
impl KvStorePartition for customers::Customer {}
#[cfg(feature = "v2")]
mod label {
use common_utils::id_type;
pub(super) const MODEL_NAME: &str = "customer_v2";
pub(super) const CLUSTER_LABEL: &str = "cust";
pub(super) fn get_global_id_label(global_customer_id: &id_type::GlobalCustomerId) -> String {
format!(
"customer_global_id_{}",
global_customer_id.get_string_repr()
)
}
pub(super) fn get_merchant_scoped_id_label(
merchant_id: &id_type::MerchantId,
merchant_reference_id: &id_type::CustomerId,
) -> String {
format!(
"customer_mid_{}_mrefid_{}",
merchant_id.get_string_repr(),
merchant_reference_id.get_string_repr()
)
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> domain::CustomerInterface for kv_router_store::KVRouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
// check customer not found in kv and fallback to db
#[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<domain::Customer>, StorageError> {
let conn = pg_connection_read(self).await?;
let maybe_result = self
.find_optional_resource_by_id(
state,
key_store,
storage_scheme,
customers::Customer::find_optional_by_customer_id_merchant_id(
&conn,
customer_id,
merchant_id,
),
kv_router_store::FindResourceBy::Id(
format!("cust_{}", customer_id.get_string_repr()),
PartitionKey::MerchantIdCustomerId {
merchant_id,
customer_id,
},
),
)
.await?;
maybe_result.map_or(Ok(None), |customer: domain::Customer| match customer.name {
Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?,
_ => Ok(Some(customer)),
})
}
#[instrument(skip_all)]
// check customer not found in kv and fallback to db
#[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<domain::Customer>, StorageError> {
let conn = pg_connection_read(self).await?;
self.find_optional_resource_by_id(
state,
key_store,
storage_scheme,
customers::Customer::find_optional_by_customer_id_merchant_id(
&conn,
customer_id,
merchant_id,
),
kv_router_store::FindResourceBy::Id(
format!("cust_{}", customer_id.get_string_repr()),
PartitionKey::MerchantIdCustomerId {
merchant_id,
customer_id,
},
),
)
.await
}
#[cfg(feature = "v2")]
async fn find_optional_by_merchant_id_merchant_reference_id(
&self,
state: &KeyManagerState,
merchant_reference_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<domain::Customer>, StorageError> {
let conn = pg_connection_read(self).await?;
let maybe_result = self
.find_optional_resource_by_id(
state,
key_store,
storage_scheme,
customers::Customer::find_optional_by_merchant_id_merchant_reference_id(
&conn,
merchant_reference_id,
merchant_id,
),
kv_router_store::FindResourceBy::Id(
format!("cust_{}", merchant_reference_id.get_string_repr()),
PartitionKey::MerchantIdMerchantReferenceId {
merchant_id,
merchant_reference_id: merchant_reference_id.get_string_repr(),
},
),
)
.await?;
maybe_result.map_or(Ok(None), |customer: domain::Customer| match customer.name {
Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?,
_ => Ok(Some(customer)),
})
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn update_customer_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
customer: domain::Customer,
customer_update: domain::CustomerUpdate,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
let conn = pg_connection_write(self).await?;
let customer = Conversion::convert(customer)
.await
.change_context(StorageError::EncryptionError)?;
let updated_customer = diesel_models::CustomerUpdateInternal::from(customer_update.clone())
.apply_changeset(customer.clone());
let key = PartitionKey::MerchantIdCustomerId {
merchant_id: &merchant_id,
customer_id: &customer_id,
};
let field = format!("cust_{}", customer_id.get_string_repr());
self.update_resource(
state,
key_store,
storage_scheme,
customers::Customer::update_by_customer_id_merchant_id(
&conn,
customer_id.clone(),
merchant_id.clone(),
customer_update.clone().into(),
),
updated_customer,
kv_router_store::UpdateResourceParams {
updateable: kv::Updateable::CustomerUpdate(kv::CustomerUpdateMems {
orig: customer.clone(),
update_data: customer_update.clone().into(),
}),
operation: Op::Update(key.clone(), &field, customer.updated_by.as_deref()),
},
)
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
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<domain::Customer, StorageError> {
let conn = pg_connection_read(self).await?;
let result: domain::Customer = self
.find_resource_by_id(
state,
key_store,
storage_scheme,
customers::Customer::find_by_merchant_reference_id_merchant_id(
&conn,
merchant_reference_id,
merchant_id,
),
kv_router_store::FindResourceBy::Id(
format!("cust_{}", merchant_reference_id.get_string_repr()),
PartitionKey::MerchantIdMerchantReferenceId {
merchant_id,
merchant_reference_id: merchant_reference_id.get_string_repr(),
},
),
)
.await?;
match result.name {
Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?,
_ => Ok(result),
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
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<domain::Customer, StorageError> {
let conn = pg_connection_read(self).await?;
let result: domain::Customer = self
.find_resource_by_id(
state,
key_store,
storage_scheme,
customers::Customer::find_by_customer_id_merchant_id(
&conn,
customer_id,
merchant_id,
),
kv_router_store::FindResourceBy::Id(
format!("cust_{}", customer_id.get_string_repr()),
PartitionKey::MerchantIdCustomerId {
merchant_id,
customer_id,
},
),
)
.await?;
match result.name {
Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?,
_ => Ok(result),
}
}
#[instrument(skip_all)]
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
constraints: domain::CustomerListConstraints,
) -> CustomResult<Vec<domain::Customer>, StorageError> {
self.router_store
.list_customers_by_merchant_id(state, merchant_id, key_store, constraints)
.await
}
#[instrument(skip_all)]
async fn list_customers_by_merchant_id_with_count(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
constraints: domain::CustomerListConstraints,
) -> CustomResult<(Vec<domain::Customer>, usize), StorageError> {
self.router_store
.list_customers_by_merchant_id_with_count(state, merchant_id, key_store, constraints)
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn insert_customer(
&self,
customer_data: domain::Customer,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
let conn = pg_connection_write(self).await?;
let id = customer_data.id.clone();
let key = PartitionKey::GlobalId {
id: id.get_string_repr(),
};
let identifier = format!("cust_{}", id.get_string_repr());
let mut new_customer = customer_data
.construct_new()
.await
.change_context(StorageError::EncryptionError)?;
let decided_storage_scheme = Box::pin(decide_storage_scheme::<_, customers::Customer>(
self,
storage_scheme,
Op::Insert,
))
.await;
new_customer.update_storage_scheme(decided_storage_scheme);
let mut reverse_lookups = Vec::new();
if let Some(ref merchant_ref_id) = new_customer.merchant_reference_id {
let reverse_lookup_merchant_scoped_id =
label::get_merchant_scoped_id_label(&new_customer.merchant_id, merchant_ref_id);
reverse_lookups.push(reverse_lookup_merchant_scoped_id);
}
self.insert_resource(
state,
key_store,
decided_storage_scheme,
new_customer.clone().insert(&conn),
new_customer.clone().into(),
kv_router_store::InsertResourceParams {
insertable: kv::Insertable::Customer(new_customer.clone()),
reverse_lookups,
identifier,
key,
resource_type: "customer",
},
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn insert_customer(
&self,
customer_data: domain::Customer,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
let conn = pg_connection_write(self).await?;
let key = PartitionKey::MerchantIdCustomerId {
merchant_id: &customer_data.merchant_id.clone(),
customer_id: &customer_data.customer_id.clone(),
};
let identifier = format!("cust_{}", customer_data.customer_id.get_string_repr());
let mut new_customer = customer_data
.construct_new()
.await
.change_context(StorageError::EncryptionError)?;
let storage_scheme = Box::pin(decide_storage_scheme::<_, customers::Customer>(
self,
storage_scheme,
Op::Insert,
))
.await;
new_customer.update_storage_scheme(storage_scheme);
let customer = new_customer.clone().into();
self.insert_resource(
state,
key_store,
storage_scheme,
new_customer.clone().insert(&conn),
customer,
kv_router_store::InsertResourceParams {
insertable: kv::Insertable::Customer(new_customer.clone()),
reverse_lookups: vec![],
identifier,
key,
resource_type: "customer",
},
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn delete_customer_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, StorageError> {
self.router_store
.delete_customer_by_customer_id_merchant_id(customer_id, merchant_id)
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_customer_by_global_id(
&self,
state: &KeyManagerState,
id: &id_type::GlobalCustomerId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
let conn = pg_connection_read(self).await?;
let result: domain::Customer = self
.find_resource_by_id(
state,
key_store,
storage_scheme,
customers::Customer::find_by_global_id(&conn, id),
kv_router_store::FindResourceBy::Id(
format!("cust_{}", id.get_string_repr()),
PartitionKey::GlobalId {
id: id.get_string_repr(),
},
),
)
.await?;
if result.status == common_enums::DeleteStatus::Redacted {
Err(StorageError::CustomerRedacted)?
} else {
Ok(result)
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn update_customer_by_global_id(
&self,
state: &KeyManagerState,
id: &id_type::GlobalCustomerId,
customer: domain::Customer,
customer_update: domain::CustomerUpdate,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
let conn = pg_connection_write(self).await?;
let customer = Conversion::convert(customer)
.await
.change_context(StorageError::EncryptionError)?;
let database_call =
customers::Customer::update_by_id(&conn, id.clone(), customer_update.clone().into());
let key = PartitionKey::GlobalId {
id: id.get_string_repr(),
};
let field = format!("cust_{}", id.get_string_repr());
self.update_resource(
state,
key_store,
storage_scheme,
database_call,
diesel_models::CustomerUpdateInternal::from(customer_update.clone())
.apply_changeset(customer.clone()),
kv_router_store::UpdateResourceParams {
updateable: kv::Updateable::CustomerUpdate(kv::CustomerUpdateMems {
orig: customer.clone(),
update_data: customer_update.into(),
}),
operation: Op::Update(key.clone(), &field, customer.updated_by.as_deref()),
},
)
.await
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> domain::CustomerInterface for RouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
#[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<domain::Customer>, StorageError> {
let conn = pg_connection_read(self).await?;
let maybe_customer: Option<domain::Customer> = self
.find_optional_resource(
state,
key_store,
customers::Customer::find_optional_by_customer_id_merchant_id(
&conn,
customer_id,
merchant_id,
),
)
.await?;
maybe_customer.map_or(Ok(None), |customer| {
// in the future, once #![feature(is_some_and)] is stable, we can make this more concise:
// `if customer.name.is_some_and(|ref name| name == pii::REDACTED) ...`
match customer.name {
Some(ref name) if name.peek() == pii::REDACTED => {
Err(StorageError::CustomerRedacted)?
}
_ => Ok(Some(customer)),
}
})
}
#[instrument(skip_all)]
#[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<domain::Customer>, StorageError> {
let conn = pg_connection_read(self).await?;
self.find_optional_resource(
state,
key_store,
customers::Customer::find_optional_by_customer_id_merchant_id(
&conn,
customer_id,
merchant_id,
),
)
.await
}
#[instrument(skip_all)]
#[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<domain::Customer>, StorageError> {
let conn = pg_connection_read(self).await?;
let maybe_customer: Option<domain::Customer> = self
.find_optional_resource(
state,
key_store,
customers::Customer::find_optional_by_merchant_id_merchant_reference_id(
&conn,
customer_id,
merchant_id,
),
)
.await?;
maybe_customer.map_or(Ok(None), |customer| {
// in the future, once #![feature(is_some_and)] is stable, we can make this more concise:
// `if customer.name.is_some_and(|ref name| name == pii::REDACTED) ...`
match customer.name {
Some(ref name) if name.peek() == pii::REDACTED => {
Err(StorageError::CustomerRedacted)?
}
_ => Ok(Some(customer)),
}
})
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn update_customer_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
_customer: domain::Customer,
customer_update: domain::CustomerUpdate,
key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
let conn = pg_connection_write(self).await?;
self.call_database(
state,
key_store,
customers::Customer::update_by_customer_id_merchant_id(
&conn,
customer_id,
merchant_id.clone(),
customer_update.into(),
),
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
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<domain::Customer, StorageError> {
let conn = pg_connection_read(self).await?;
let customer: domain::Customer = self
.call_database(
state,
key_store,
customers::Customer::find_by_customer_id_merchant_id(
&conn,
customer_id,
merchant_id,
),
)
.await?;
match customer.name {
Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?,
_ => Ok(customer),
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
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<domain::Customer, StorageError> {
let conn = pg_connection_read(self).await?;
let customer: domain::Customer = self
.call_database(
state,
key_store,
customers::Customer::find_by_merchant_reference_id_merchant_id(
&conn,
merchant_reference_id,
merchant_id,
),
)
.await?;
match customer.name {
Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?,
_ => Ok(customer),
}
}
#[instrument(skip_all)]
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
constraints: domain::CustomerListConstraints,
) -> CustomResult<Vec<domain::Customer>, StorageError> {
let conn = pg_connection_read(self).await?;
let customer_list_constraints =
diesel_models::query::customers::CustomerListConstraints::from(constraints);
self.find_resources(
state,
key_store,
customers::Customer::list_customers_by_merchant_id_and_constraints(
&conn,
merchant_id,
customer_list_constraints,
),
)
.await
}
#[instrument(skip_all)]
async fn list_customers_by_merchant_id_with_count(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
constraints: domain::CustomerListConstraints,
) -> CustomResult<(Vec<domain::Customer>, usize), StorageError> {
let conn = pg_connection_read(self).await?;
let customer_list_constraints =
diesel_models::query::customers::CustomerListConstraints::from(constraints);
let customers_constraints = diesel_models::query::customers::CustomerListConstraints {
limit: customer_list_constraints.limit,
offset: customer_list_constraints.offset,
customer_id: customer_list_constraints.customer_id.clone(),
time_range: customer_list_constraints.time_range,
};
let customers = self
.find_resources(
state,
key_store,
customers::Customer::list_customers_by_merchant_id_and_constraints(
&conn,
merchant_id,
customers_constraints,
),
)
.await?;
let total_count = customers::Customer::get_customer_count_by_merchant_id_and_constraints(
&conn,
merchant_id,
customer_list_constraints,
)
.await
.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})?;
Ok((customers, total_count))
}
#[instrument(skip_all)]
async fn insert_customer(
&self,
customer_data: domain::Customer,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
let conn = pg_connection_write(self).await?;
let customer_new = customer_data
.construct_new()
.await
.change_context(StorageError::EncryptionError)?;
self.call_database(state, key_store, customer_new.insert(&conn))
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn delete_customer_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, StorageError> {
let conn = pg_connection_write(self).await?;
customers::Customer::delete_by_customer_id_merchant_id(&conn, customer_id, merchant_id)
.await
.map_err(|error| {
let new_err = diesel_error_to_data_error(*error.current_context());
error.change_context(new_err)
})
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn update_customer_by_global_id(
&self,
state: &KeyManagerState,
id: &id_type::GlobalCustomerId,
_customer: domain::Customer,
customer_update: domain::CustomerUpdate,
key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
let conn = pg_connection_write(self).await?;
self.call_database(
state,
key_store,
customers::Customer::update_by_id(&conn, id.clone(), customer_update.into()),
)
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_customer_by_global_id(
&self,
state: &KeyManagerState,
id: &id_type::GlobalCustomerId,
key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
let conn = pg_connection_read(self).await?;
let customer: domain::Customer = self
.call_database(
state,
key_store,
customers::Customer::find_by_global_id(&conn, id),
)
.await?;
match customer.name {
Some(ref name) if name.peek() == pii::REDACTED => Err(StorageError::CustomerRedacted)?,
_ => Ok(customer),
}
}
}
#[async_trait::async_trait]
impl domain::CustomerInterface for MockDb {
type Error = StorageError;
#[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<domain::Customer>, StorageError> {
let customers = self.customers.lock().await;
self.find_resource(state, key_store, customers, |customer| {
customer.customer_id == *customer_id && &customer.merchant_id == merchant_id
})
.await
}
#[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<domain::Customer>, StorageError> {
let customers = self.customers.lock().await;
self.find_resource(state, key_store, customers, |customer| {
customer.customer_id == *customer_id && &customer.merchant_id == merchant_id
})
.await
}
#[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<domain::Customer>, StorageError> {
todo!()
}
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
constraints: domain::CustomerListConstraints,
) -> CustomResult<Vec<domain::Customer>, StorageError> {
let customers = self.customers.lock().await;
let customers = try_join_all(
customers
.iter()
.filter(|customer| customer.merchant_id == *merchant_id)
.take(usize::from(constraints.limit))
.skip(usize::try_from(constraints.offset.unwrap_or(0)).unwrap_or(0))
.map(|customer| async {
customer
.to_owned()
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}),
)
.await?;
Ok(customers)
}
async fn list_customers_by_merchant_id_with_count(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
constraints: domain::CustomerListConstraints,
) -> CustomResult<(Vec<domain::Customer>, usize), StorageError> {
let customers = self.customers.lock().await;
let customers_list = try_join_all(
customers
.iter()
.filter(|customer| customer.merchant_id == *merchant_id)
.take(usize::from(constraints.limit))
.skip(usize::try_from(constraints.offset.unwrap_or(0)).unwrap_or(0))
.map(|customer| async {
customer
.to_owned()
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}),
)
.await?;
let total_count = customers
.iter()
.filter(|customer| customer.merchant_id == *merchant_id)
.count();
Ok((customers_list, total_count))
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn update_customer_by_customer_id_merchant_id(
&self,
_state: &KeyManagerState,
_customer_id: id_type::CustomerId,
_merchant_id: id_type::MerchantId,
_customer: domain::Customer,
_customer_update: domain::CustomerUpdate,
_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[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<domain::Customer, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[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<domain::Customer, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[allow(clippy::panic)]
async fn insert_customer(
&self,
customer_data: domain::Customer,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
let mut customers = self.customers.lock().await;
let customer = Conversion::convert(customer_data)
.await
.change_context(StorageError::EncryptionError)?;
customers.push(customer.clone());
customer
.convert(
state,
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[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, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn update_customer_by_global_id(
&self,
_state: &KeyManagerState,
_id: &id_type::GlobalCustomerId,
_customer: domain::Customer,
_customer_update: domain::CustomerUpdate,
_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v2")]
async fn find_customer_by_global_id(
&self,
_state: &KeyManagerState,
_id: &id_type::GlobalCustomerId,
_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/customers.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7549
}
|
large_file_-1614440293481408760
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/kv_router_store.rs
</path>
<file>
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> {}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/kv_router_store.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3907
}
|
large_file_-112081176689092671
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/merchant_key_store.rs
</path>
<file>
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
behaviour::{Conversion, ReverseConversion},
merchant_key_store as domain,
merchant_key_store::MerchantKeyStoreInterface,
};
use masking::Secret;
use router_env::{instrument, tracing};
#[cfg(feature = "accounts_cache")]
use crate::redis::{
cache,
cache::{CacheKind, ACCOUNTS_CACHE},
};
use crate::{
kv_router_store,
utils::{pg_accounts_connection_read, pg_accounts_connection_write},
CustomResult, DatabaseStore, KeyManagerState, MockDb, RouterStore, StorageError,
};
#[async_trait::async_trait]
impl<T: DatabaseStore> MerchantKeyStoreInterface for kv_router_store::KVRouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
async fn insert_merchant_key_store(
&self,
state: &KeyManagerState,
merchant_key_store: domain::MerchantKeyStore,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::MerchantKeyStore, Self::Error> {
self.router_store
.insert_merchant_key_store(state, merchant_key_store, key)
.await
}
#[instrument(skip_all)]
async fn get_merchant_key_store_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::MerchantKeyStore, Self::Error> {
self.router_store
.get_merchant_key_store_by_merchant_id(state, merchant_id, key)
.await
}
#[instrument(skip_all)]
async fn delete_merchant_key_store_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, Self::Error> {
self.router_store
.delete_merchant_key_store_by_merchant_id(merchant_id)
.await
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn list_multiple_key_stores(
&self,
state: &KeyManagerState,
merchant_ids: Vec<common_utils::id_type::MerchantId>,
key: &Secret<Vec<u8>>,
) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> {
self.router_store
.list_multiple_key_stores(state, merchant_ids, key)
.await
}
async fn get_all_key_stores(
&self,
state: &KeyManagerState,
key: &Secret<Vec<u8>>,
from: u32,
to: u32,
) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> {
self.router_store
.get_all_key_stores(state, key, from, to)
.await
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> MerchantKeyStoreInterface for RouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
async fn insert_merchant_key_store(
&self,
state: &KeyManagerState,
merchant_key_store: domain::MerchantKeyStore,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::MerchantKeyStore, Self::Error> {
let conn = pg_accounts_connection_write(self).await?;
let merchant_id = merchant_key_store.merchant_id.clone();
merchant_key_store
.construct_new()
.await
.change_context(Self::Error::EncryptionError)?
.insert(&conn)
.await
.map_err(|error| report!(Self::Error::from(error)))?
.convert(state, key, merchant_id.into())
.await
.change_context(Self::Error::DecryptionError)
}
#[instrument(skip_all)]
async fn get_merchant_key_store_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::MerchantKeyStore, Self::Error> {
let fetch_func = || async {
let conn = pg_accounts_connection_read(self).await?;
diesel_models::merchant_key_store::MerchantKeyStore::find_by_merchant_id(
&conn,
merchant_id,
)
.await
.map_err(|error| report!(Self::Error::from(error)))
};
#[cfg(not(feature = "accounts_cache"))]
{
fetch_func()
.await?
.convert(state, key, merchant_id.clone().into())
.await
.change_context(Self::Error::DecryptionError)
}
#[cfg(feature = "accounts_cache")]
{
let key_store_cache_key =
format!("merchant_key_store_{}", merchant_id.get_string_repr());
cache::get_or_populate_in_memory(
self,
&key_store_cache_key,
fetch_func,
&ACCOUNTS_CACHE,
)
.await?
.convert(state, key, merchant_id.clone().into())
.await
.change_context(Self::Error::DecryptionError)
}
}
#[instrument(skip_all)]
async fn delete_merchant_key_store_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, Self::Error> {
let delete_func = || async {
let conn = pg_accounts_connection_write(self).await?;
diesel_models::merchant_key_store::MerchantKeyStore::delete_by_merchant_id(
&conn,
merchant_id,
)
.await
.map_err(|error| report!(Self::Error::from(error)))
};
#[cfg(not(feature = "accounts_cache"))]
{
delete_func().await
}
#[cfg(feature = "accounts_cache")]
{
let key_store_cache_key =
format!("merchant_key_store_{}", merchant_id.get_string_repr());
cache::publish_and_redact(
self,
CacheKind::Accounts(key_store_cache_key.into()),
delete_func,
)
.await
}
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn list_multiple_key_stores(
&self,
state: &KeyManagerState,
merchant_ids: Vec<common_utils::id_type::MerchantId>,
key: &Secret<Vec<u8>>,
) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> {
let fetch_func = || async {
let conn = pg_accounts_connection_read(self).await?;
diesel_models::merchant_key_store::MerchantKeyStore::list_multiple_key_stores(
&conn,
merchant_ids,
)
.await
.map_err(|error| report!(Self::Error::from(error)))
};
futures::future::try_join_all(fetch_func().await?.into_iter().map(|key_store| async {
let merchant_id = key_store.merchant_id.clone();
key_store
.convert(state, key, merchant_id.into())
.await
.change_context(Self::Error::DecryptionError)
}))
.await
}
async fn get_all_key_stores(
&self,
state: &KeyManagerState,
key: &Secret<Vec<u8>>,
from: u32,
to: u32,
) -> CustomResult<Vec<domain::MerchantKeyStore>, Self::Error> {
let conn = pg_accounts_connection_read(self).await?;
let stores = diesel_models::merchant_key_store::MerchantKeyStore::list_all_key_stores(
&conn, from, to,
)
.await
.map_err(|err| report!(Self::Error::from(err)))?;
futures::future::try_join_all(stores.into_iter().map(|key_store| async {
let merchant_id = key_store.merchant_id.clone();
key_store
.convert(state, key, merchant_id.into())
.await
.change_context(Self::Error::DecryptionError)
}))
.await
}
}
#[async_trait::async_trait]
impl MerchantKeyStoreInterface for MockDb {
type Error = StorageError;
async fn insert_merchant_key_store(
&self,
state: &KeyManagerState,
merchant_key_store: domain::MerchantKeyStore,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::MerchantKeyStore, Self::Error> {
let mut locked_merchant_key_store = self.merchant_key_store.lock().await;
if locked_merchant_key_store
.iter()
.any(|merchant_key| merchant_key.merchant_id == merchant_key_store.merchant_id)
{
Err(StorageError::DuplicateValue {
entity: "merchant_key_store",
key: Some(merchant_key_store.merchant_id.get_string_repr().to_owned()),
})?;
}
let merchant_key = Conversion::convert(merchant_key_store)
.await
.change_context(StorageError::MockDbError)?;
locked_merchant_key_store.push(merchant_key.clone());
let merchant_id = merchant_key.merchant_id.clone();
merchant_key
.convert(state, key, merchant_id.into())
.await
.change_context(StorageError::DecryptionError)
}
async fn get_merchant_key_store_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
key: &Secret<Vec<u8>>,
) -> CustomResult<domain::MerchantKeyStore, StorageError> {
self.merchant_key_store
.lock()
.await
.iter()
.find(|merchant_key| merchant_key.merchant_id == *merchant_id)
.cloned()
.ok_or(StorageError::ValueNotFound(String::from(
"merchant_key_store",
)))?
.convert(state, key, merchant_id.clone().into())
.await
.change_context(StorageError::DecryptionError)
}
async fn delete_merchant_key_store_by_merchant_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<bool, StorageError> {
let mut merchant_key_stores = self.merchant_key_store.lock().await;
let index = merchant_key_stores
.iter()
.position(|mks| mks.merchant_id == *merchant_id)
.ok_or(StorageError::ValueNotFound(format!(
"No merchant key store found for merchant_id = {merchant_id:?}",
)))?;
merchant_key_stores.remove(index);
Ok(true)
}
#[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<domain::MerchantKeyStore>, StorageError> {
let merchant_key_stores = self.merchant_key_store.lock().await;
futures::future::try_join_all(
merchant_key_stores
.iter()
.filter(|merchant_key| merchant_ids.contains(&merchant_key.merchant_id))
.map(|merchant_key| async {
merchant_key
.to_owned()
.convert(state, key, merchant_key.merchant_id.clone().into())
.await
.change_context(StorageError::DecryptionError)
}),
)
.await
}
async fn get_all_key_stores(
&self,
state: &KeyManagerState,
key: &Secret<Vec<u8>>,
_from: u32,
_to: u32,
) -> CustomResult<Vec<domain::MerchantKeyStore>, StorageError> {
let merchant_key_stores = self.merchant_key_store.lock().await;
futures::future::try_join_all(merchant_key_stores.iter().map(|merchant_key| async {
merchant_key
.to_owned()
.convert(state, key, merchant_key.merchant_id.clone().into())
.await
.change_context(StorageError::DecryptionError)
}))
.await
}
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/merchant_key_store.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2623
}
|
large_file_686143703090603477
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/payments/payment_intent.rs
</path>
<file>
#[cfg(feature = "olap")]
use api_models::payments::{AmountFilter, Order, SortBy, SortOn};
#[cfg(feature = "olap")]
use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
#[cfg(feature = "v2")]
use common_utils::fallback_reverse_lookup_not_found;
use common_utils::{
ext_traits::{AsyncExt, Encode},
types::keymanager::KeyManagerState,
};
#[cfg(feature = "olap")]
use diesel::{associations::HasTable, ExpressionMethods, JoinOnDsl, QueryDsl};
#[cfg(feature = "v1")]
use diesel_models::payment_intent::PaymentIntentUpdate as DieselPaymentIntentUpdate;
#[cfg(feature = "v2")]
use diesel_models::payment_intent::PaymentIntentUpdateInternal;
#[cfg(feature = "olap")]
use diesel_models::query::generics::db_metrics;
#[cfg(feature = "v2")]
use diesel_models::reverse_lookup::ReverseLookupNew;
#[cfg(all(feature = "v1", feature = "olap"))]
use diesel_models::schema::{
payment_attempt::{self as payment_attempt_schema, dsl as pa_dsl},
payment_intent::dsl as pi_dsl,
};
#[cfg(all(feature = "v2", feature = "olap"))]
use diesel_models::schema_v2::{
payment_attempt::{self as payment_attempt_schema, dsl as pa_dsl},
payment_intent::dsl as pi_dsl,
};
use diesel_models::{
enums::MerchantStorageScheme, kv, payment_intent::PaymentIntent as DieselPaymentIntent,
};
use error_stack::ResultExt;
#[cfg(feature = "olap")]
use hyperswitch_domain_models::payments::{
payment_attempt::PaymentAttempt, payment_intent::PaymentIntentFetchConstraints,
};
use hyperswitch_domain_models::{
behaviour::Conversion,
merchant_key_store::MerchantKeyStore,
payments::{
payment_intent::{PaymentIntentInterface, PaymentIntentUpdate},
PaymentIntent,
},
};
use redis_interface::HsetnxReply;
#[cfg(feature = "olap")]
use router_env::logger;
use router_env::{instrument, tracing};
#[cfg(feature = "olap")]
use crate::connection;
use crate::{
diesel_error_to_data_error,
errors::{RedisErrorExt, StorageError},
kv_router_store::KVRouterStore,
redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey},
utils::{self, pg_connection_read, pg_connection_write},
DatabaseStore,
};
#[cfg(feature = "v2")]
use crate::{errors, lookup::ReverseLookupInterface};
#[async_trait::async_trait]
impl<T: DatabaseStore> PaymentIntentInterface for KVRouterStore<T> {
type Error = StorageError;
#[cfg(feature = "v1")]
async fn insert_payment_intent(
&self,
state: &KeyManagerState,
payment_intent: PaymentIntent,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let merchant_id = payment_intent.merchant_id.clone();
let payment_id = payment_intent.get_id().to_owned();
let field = payment_intent.get_id().get_hash_key_for_kv_store();
let key = PartitionKey::MerchantIdPaymentId {
merchant_id: &merchant_id,
payment_id: &payment_id,
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.insert_payment_intent(
state,
payment_intent,
merchant_key_store,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let new_payment_intent = payment_intent
.clone()
.construct_new()
.await
.change_context(StorageError::EncryptionError)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::PaymentIntent(Box::new(
new_payment_intent,
))),
},
};
let diesel_payment_intent = payment_intent
.clone()
.convert()
.await
.change_context(StorageError::EncryptionError)?;
match Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>(
self,
KvOperation::<DieselPaymentIntent>::HSetNx(
&field,
&diesel_payment_intent,
redis_entry,
),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
{
Ok(HsetnxReply::KeyNotSet) => Err(StorageError::DuplicateValue {
entity: "payment_intent",
key: Some(key_str),
}
.into()),
Ok(HsetnxReply::KeySet) => Ok(payment_intent),
Err(error) => Err(error.change_context(StorageError::KVError)),
}
}
}
}
#[cfg(feature = "v2")]
async fn insert_payment_intent(
&self,
state: &KeyManagerState,
payment_intent: PaymentIntent,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.insert_payment_intent(
state,
payment_intent,
merchant_key_store,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let id = payment_intent.id.clone();
let key = PartitionKey::GlobalPaymentId { id: &id };
let field = format!("pi_{}", id.get_string_repr());
let key_str = key.to_string();
let new_payment_intent = payment_intent
.clone()
.construct_new()
.await
.change_context(StorageError::EncryptionError)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::PaymentIntent(Box::new(
new_payment_intent,
))),
},
};
let diesel_payment_intent = payment_intent
.clone()
.convert()
.await
.change_context(StorageError::EncryptionError)?;
if let Some(merchant_reference_id) = &payment_intent.merchant_reference_id {
let reverse_lookup = ReverseLookupNew {
lookup_id: format!(
"pi_merchant_reference_{}_{}",
payment_intent.profile_id.get_string_repr(),
merchant_reference_id.get_string_repr()
),
pk_id: key_str.clone(),
sk_id: field.clone(),
source: "payment_intent".to_string(),
updated_by: storage_scheme.to_string(),
};
self.insert_reverse_lookup(reverse_lookup, storage_scheme)
.await?;
}
match Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>(
self,
KvOperation::<DieselPaymentIntent>::HSetNx(
&field,
&diesel_payment_intent,
redis_entry,
),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
{
Ok(HsetnxReply::KeyNotSet) => Err(StorageError::DuplicateValue {
entity: "payment_intent",
key: Some(key_str),
}
.into()),
Ok(HsetnxReply::KeySet) => Ok(payment_intent),
Err(error) => Err(error.change_context(StorageError::KVError)),
}
}
}
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all)]
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<(PaymentIntent, Option<PaymentAttempt>)>, StorageError> {
self.router_store
.get_filtered_payment_intents_attempt(
state,
merchant_id,
constraints,
merchant_key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn update_payment_intent(
&self,
state: &KeyManagerState,
this: PaymentIntent,
payment_intent_update: PaymentIntentUpdate,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let merchant_id = this.merchant_id.clone();
let payment_id = this.get_id().to_owned();
let key = PartitionKey::MerchantIdPaymentId {
merchant_id: &merchant_id,
payment_id: &payment_id,
};
let field = format!("pi_{}", this.get_id().get_string_repr());
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>(
self,
storage_scheme,
Op::Update(key.clone(), &field, Some(&this.updated_by)),
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.update_payment_intent(
state,
this,
payment_intent_update,
merchant_key_store,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let diesel_intent_update = DieselPaymentIntentUpdate::from(payment_intent_update);
let origin_diesel_intent = this
.convert()
.await
.change_context(StorageError::EncryptionError)?;
let diesel_intent = diesel_intent_update
.clone()
.apply_changeset(origin_diesel_intent.clone());
// Check for database presence as well Maybe use a read replica here ?
let redis_value = diesel_intent
.encode_to_string_of_json()
.change_context(StorageError::SerializationFailed)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
updatable: Box::new(kv::Updateable::PaymentIntentUpdate(Box::new(
kv::PaymentIntentUpdateMems {
orig: origin_diesel_intent,
update_data: diesel_intent_update,
},
))),
},
};
Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), redis_entry),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hset()
.change_context(StorageError::KVError)?;
let payment_intent = PaymentIntent::convert_back(
state,
diesel_intent,
merchant_key_store.key.get_inner(),
merchant_id.into(),
)
.await
.change_context(StorageError::DecryptionError)?;
Ok(payment_intent)
}
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn update_payment_intent(
&self,
state: &KeyManagerState,
this: PaymentIntent,
payment_intent_update: PaymentIntentUpdate,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.update_payment_intent(
state,
this,
payment_intent_update,
merchant_key_store,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let id = this.id.clone();
let merchant_id = this.merchant_id.clone();
let key = PartitionKey::GlobalPaymentId { id: &id };
let field = format!("pi_{}", id.get_string_repr());
let key_str = key.to_string();
let diesel_intent_update =
PaymentIntentUpdateInternal::try_from(payment_intent_update)
.change_context(StorageError::DeserializationFailed)?;
let origin_diesel_intent = this
.convert()
.await
.change_context(StorageError::EncryptionError)?;
let diesel_intent = diesel_intent_update
.clone()
.apply_changeset(origin_diesel_intent.clone());
let redis_value = diesel_intent
.encode_to_string_of_json()
.change_context(StorageError::SerializationFailed)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
updatable: Box::new(kv::Updateable::PaymentIntentUpdate(Box::new(
kv::PaymentIntentUpdateMems {
orig: origin_diesel_intent,
update_data: diesel_intent_update,
},
))),
},
};
Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<DieselPaymentIntent>::Hset((&field, redis_value), redis_entry),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hset()
.change_context(StorageError::KVError)?;
let payment_intent = PaymentIntent::convert_back(
state,
diesel_intent,
merchant_key_store.key.get_inner(),
merchant_id.into(),
)
.await
.change_context(StorageError::DecryptionError)?;
Ok(payment_intent)
}
}
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_intent_by_payment_id_merchant_id(
&self,
state: &KeyManagerState,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let database_call = || async {
let conn = pg_connection_read(self).await?;
DieselPaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>(
self,
storage_scheme,
Op::Find,
))
.await;
let diesel_payment_intent = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdPaymentId {
merchant_id,
payment_id,
};
let field = payment_id.get_hash_key_for_kv_store();
Box::pin(utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>(
self,
KvOperation::<DieselPaymentIntent>::HGet(&field),
key,
))
.await?
.try_into_hget()
},
database_call,
))
.await
}
}?;
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_id.to_owned().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_payment_intent_by_id(
&self,
state: &KeyManagerState,
id: &common_utils::id_type::GlobalPaymentId,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPaymentIntent>(
self,
storage_scheme,
Op::Find,
))
.await;
let database_call = || async {
let conn: bb8::PooledConnection<
'_,
async_bb8_diesel::ConnectionManager<diesel::PgConnection>,
> = pg_connection_read(self).await?;
DieselPaymentIntent::find_by_global_id(&conn, id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
};
let diesel_payment_intent = match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::GlobalPaymentId { id };
let field = format!("pi_{}", id.get_string_repr());
Box::pin(utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>(
self,
KvOperation::<DieselPaymentIntent>::HGet(&field),
key,
))
.await?
.try_into_hget()
},
database_call,
))
.await
}
}?;
let merchant_id = diesel_payment_intent.merchant_id.clone();
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_id.into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_payment_intent_by_constraints(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, StorageError> {
self.router_store
.filter_payment_intent_by_constraints(
state,
merchant_id,
filters,
merchant_key_store,
storage_scheme,
)
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_payment_intents_by_time_range_constraints(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
time_range: &common_utils::types::TimeRange,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, StorageError> {
self.router_store
.filter_payment_intents_by_time_range_constraints(
state,
merchant_id,
time_range,
merchant_key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "olap")]
async fn get_intent_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
self.router_store
.get_intent_status_with_count(merchant_id, profile_id_list, time_range)
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> {
self.router_store
.get_filtered_payment_intents_attempt(
state,
merchant_id,
filters,
merchant_key_store,
storage_scheme,
)
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, StorageError> {
self.router_store
.get_filtered_active_attempt_ids_for_total_count(
merchant_id,
constraints,
storage_scheme,
)
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Option<String>>, StorageError> {
self.router_store
.get_filtered_active_attempt_ids_for_total_count(
merchant_id,
constraints,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_payment_intent_by_merchant_reference_id_profile_id(
&self,
state: &KeyManagerState,
merchant_reference_id: &common_utils::id_type::PaymentReferenceId,
profile_id: &common_utils::id_type::ProfileId,
merchant_key_store: &MerchantKeyStore,
storage_scheme: &MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.find_payment_intent_by_merchant_reference_id_profile_id(
state,
merchant_reference_id,
profile_id,
merchant_key_store,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let lookup_id = format!(
"pi_merchant_reference_{}_{}",
profile_id.get_string_repr(),
merchant_reference_id.get_string_repr()
);
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, *storage_scheme)
.await,
self.router_store
.find_payment_intent_by_merchant_reference_id_profile_id(
state,
merchant_reference_id,
profile_id,
merchant_key_store,
storage_scheme,
)
.await
);
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
let database_call = || async {
let conn = pg_connection_read(self).await?;
DieselPaymentIntent::find_by_merchant_reference_id_profile_id(
&conn,
merchant_reference_id,
profile_id,
)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
};
let diesel_payment_intent = Box::pin(utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper::<DieselPaymentIntent, _, _>(
self,
KvOperation::<DieselPaymentIntent>::HGet(&lookup.sk_id),
key,
))
.await?
.try_into_hget()
},
database_call,
))
.await?;
let merchant_id = diesel_payment_intent.merchant_id.clone();
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_id.into(),
)
.await
.change_context(StorageError::DecryptionError)
}
}
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> PaymentIntentInterface for crate::RouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
async fn insert_payment_intent(
&self,
state: &KeyManagerState,
payment_intent: PaymentIntent,
merchant_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let conn = pg_connection_write(self).await?;
let diesel_payment_intent = payment_intent
.construct_new()
.await
.change_context(StorageError::EncryptionError)?
.insert(&conn)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})?;
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn update_payment_intent(
&self,
state: &KeyManagerState,
this: PaymentIntent,
payment_intent: PaymentIntentUpdate,
merchant_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let conn = pg_connection_write(self).await?;
let diesel_payment_intent_update = DieselPaymentIntentUpdate::from(payment_intent);
let diesel_payment_intent = this
.convert()
.await
.change_context(StorageError::EncryptionError)?
.update(&conn, diesel_payment_intent_update)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})?;
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn update_payment_intent(
&self,
state: &KeyManagerState,
this: PaymentIntent,
payment_intent: PaymentIntentUpdate,
merchant_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let conn = pg_connection_write(self).await?;
let diesel_payment_intent_update = PaymentIntentUpdateInternal::try_from(payment_intent)
.change_context(StorageError::DeserializationFailed)?;
let diesel_payment_intent = this
.convert()
.await
.change_context(StorageError::EncryptionError)?
.update(&conn, diesel_payment_intent_update)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})?;
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
async fn find_payment_intent_by_payment_id_merchant_id(
&self,
state: &KeyManagerState,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
merchant_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let conn = pg_connection_read(self).await?;
DieselPaymentIntent::find_by_payment_id_merchant_id(&conn, payment_id, merchant_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.async_and_then(|diesel_payment_intent| async {
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)
})
.await
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_payment_intent_by_id(
&self,
state: &KeyManagerState,
id: &common_utils::id_type::GlobalPaymentId,
merchant_key_store: &MerchantKeyStore,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let conn = pg_connection_read(self).await?;
let diesel_payment_intent = DieselPaymentIntent::find_by_global_id(&conn, id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})?;
let merchant_id = diesel_payment_intent.merchant_id.clone();
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_id.to_owned().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
async fn find_payment_intent_by_merchant_reference_id_profile_id(
&self,
state: &KeyManagerState,
merchant_reference_id: &common_utils::id_type::PaymentReferenceId,
profile_id: &common_utils::id_type::ProfileId,
merchant_key_store: &MerchantKeyStore,
_storage_scheme: &MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let conn = pg_connection_read(self).await?;
let diesel_payment_intent = DieselPaymentIntent::find_by_merchant_reference_id_profile_id(
&conn,
merchant_reference_id,
profile_id,
)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})?;
let merchant_id = diesel_payment_intent.merchant_id.clone();
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_id.to_owned().into(),
)
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn filter_payment_intent_by_constraints(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
filters: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, StorageError> {
use futures::{future::try_join_all, FutureExt};
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
//[#350]: Replace this with Boxable Expression and pass it into generic filter
// when https://github.com/rust-lang/rust/issues/52662 becomes stable
let mut query = <DieselPaymentIntent as HasTable>::table()
.filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
.order(pi_dsl::created_at.desc())
.into_boxed();
match filters {
PaymentIntentFetchConstraints::Single { payment_intent_id } => {
query = query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()));
}
PaymentIntentFetchConstraints::List(params) => {
if let Some(limit) = params.limit {
query = query.limit(limit.into());
}
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone()));
}
query = match (params.starting_at, ¶ms.starting_after_id) {
(Some(starting_at), _) => query.filter(pi_dsl::created_at.ge(starting_at)),
(None, Some(starting_after_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let starting_at = self
.find_payment_intent_by_payment_id_merchant_id(
state,
starting_after_id,
merchant_id,
merchant_key_store,
storage_scheme,
)
.await?
.created_at;
query.filter(pi_dsl::created_at.ge(starting_at))
}
(None, None) => query,
};
query = match (params.ending_at, ¶ms.ending_before_id) {
(Some(ending_at), _) => query.filter(pi_dsl::created_at.le(ending_at)),
(None, Some(ending_before_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let ending_at = self
.find_payment_intent_by_payment_id_merchant_id(
state,
ending_before_id,
merchant_id,
merchant_key_store,
storage_scheme,
)
.await?
.created_at;
query.filter(pi_dsl::created_at.le(ending_at))
}
(None, None) => query,
};
query = query.offset(params.offset.into());
query = match ¶ms.currency {
Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())),
None => query,
};
query = match ¶ms.status {
Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())),
None => query,
};
if let Some(currency) = ¶ms.currency {
query = query.filter(pi_dsl::currency.eq_any(currency.clone()));
}
if let Some(status) = ¶ms.status {
query = query.filter(pi_dsl::status.eq_any(status.clone()));
}
}
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>(
query.get_results_async::<DieselPaymentIntent>(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.map(|payment_intents| {
try_join_all(payment_intents.into_iter().map(|diesel_payment_intent| {
PaymentIntent::convert_back(
state,
diesel_payment_intent,
merchant_key_store.key.get_inner(),
merchant_key_store.merchant_id.clone().into(),
)
}))
.map(|join_result| join_result.change_context(StorageError::DecryptionError))
})
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payment records"),
)
})?
.await
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn filter_payment_intents_by_time_range_constraints(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
time_range: &common_utils::types::TimeRange,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentIntent>, StorageError> {
// TODO: Remove this redundant function
let payment_filters = (*time_range).into();
self.filter_payment_intent_by_constraints(
state,
merchant_id,
&payment_filters,
merchant_key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn get_intent_status_with_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
time_range: &common_utils::types::TimeRange,
) -> error_stack::Result<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = <DieselPaymentIntent as HasTable>::table()
.group_by(pi_dsl::status)
.select((pi_dsl::status, diesel::dsl::count_star()))
.filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
.into_boxed();
if let Some(profile_id) = profile_id_list {
query = query.filter(pi_dsl::profile_id.eq_any(profile_id));
}
query = query.filter(pi_dsl::created_at.ge(time_range.start_time));
query = match time_range.end_time {
Some(ending_at) => query.filter(pi_dsl::created_at.le(ending_at)),
None => query,
};
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>(
query.get_results_async::<(common_enums::IntentStatus, i64)>(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payment records"),
)
.into()
})
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<(PaymentIntent, PaymentAttempt)>, StorageError> {
use futures::{future::try_join_all, FutureExt};
use crate::DataModelExt;
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPaymentIntent::table()
.filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
.inner_join(
payment_attempt_schema::table.on(pa_dsl::attempt_id.eq(pi_dsl::active_attempt_id)),
)
.filter(pa_dsl::merchant_id.eq(merchant_id.to_owned())) // Ensure merchant_ids match, as different merchants can share payment/attempt IDs.
.into_boxed();
query = match constraints {
PaymentIntentFetchConstraints::Single { payment_intent_id } => {
query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()))
}
PaymentIntentFetchConstraints::List(params) => {
query = match params.order {
Order {
on: SortOn::Amount,
by: SortBy::Asc,
} => query.order(pi_dsl::amount.asc()),
Order {
on: SortOn::Amount,
by: SortBy::Desc,
} => query.order(pi_dsl::amount.desc()),
Order {
on: SortOn::Created,
by: SortBy::Asc,
} => query.order(pi_dsl::created_at.asc()),
Order {
on: SortOn::Created,
by: SortBy::Desc,
} => query.order(pi_dsl::created_at.desc()),
};
if let Some(limit) = params.limit {
query = query.limit(limit.into());
}
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(merchant_order_reference_id) = ¶ms.merchant_order_reference_id {
query = query.filter(
pi_dsl::merchant_order_reference_id.eq(merchant_order_reference_id.clone()),
)
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone()));
}
query = match (params.starting_at, ¶ms.starting_after_id) {
(Some(starting_at), _) => query.filter(pi_dsl::created_at.ge(starting_at)),
(None, Some(starting_after_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let starting_at = self
.find_payment_intent_by_payment_id_merchant_id(
state,
starting_after_id,
merchant_id,
merchant_key_store,
storage_scheme,
)
.await?
.created_at;
query.filter(pi_dsl::created_at.ge(starting_at))
}
(None, None) => query,
};
query = match (params.ending_at, ¶ms.ending_before_id) {
(Some(ending_at), _) => query.filter(pi_dsl::created_at.le(ending_at)),
(None, Some(ending_before_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let ending_at = self
.find_payment_intent_by_payment_id_merchant_id(
state,
ending_before_id,
merchant_id,
merchant_key_store,
storage_scheme,
)
.await?
.created_at;
query.filter(pi_dsl::created_at.le(ending_at))
}
(None, None) => query,
};
query = query.offset(params.offset.into());
query = match params.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => query.filter(pi_dsl::amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.le(end)),
_ => query,
};
query = match ¶ms.currency {
Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())),
None => query,
};
let connectors = params
.connector
.as_ref()
.map(|c| c.iter().map(|c| c.to_string()).collect::<Vec<String>>());
query = match connectors {
Some(connectors) => query.filter(pa_dsl::connector.eq_any(connectors)),
None => query,
};
query = match ¶ms.status {
Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())),
None => query,
};
query = match ¶ms.payment_method {
Some(payment_method) => {
query.filter(pa_dsl::payment_method.eq_any(payment_method.clone()))
}
None => query,
};
query = match ¶ms.payment_method_type {
Some(payment_method_type) => query
.filter(pa_dsl::payment_method_type.eq_any(payment_method_type.clone())),
None => query,
};
query = match ¶ms.authentication_type {
Some(authentication_type) => query
.filter(pa_dsl::authentication_type.eq_any(authentication_type.clone())),
None => query,
};
query = match ¶ms.merchant_connector_id {
Some(merchant_connector_id) => query.filter(
pa_dsl::merchant_connector_id.eq_any(merchant_connector_id.clone()),
),
None => query,
};
if let Some(card_network) = ¶ms.card_network {
query = query.filter(pa_dsl::card_network.eq_any(card_network.clone()));
}
if let Some(card_discovery) = ¶ms.card_discovery {
query = query.filter(pa_dsl::card_discovery.eq_any(card_discovery.clone()));
}
query
}
};
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
.get_results_async::<(
DieselPaymentIntent,
diesel_models::payment_attempt::PaymentAttempt,
)>(conn)
.await
.map(|results| {
try_join_all(results.into_iter().map(|(pi, pa)| {
PaymentIntent::convert_back(
state,
pi,
merchant_key_store.key.get_inner(),
merchant_id.to_owned().into(),
)
.map(|payment_intent| {
payment_intent.map(|payment_intent| {
(payment_intent, PaymentAttempt::from_storage_model(pa))
})
})
}))
.map(|join_result| join_result.change_context(StorageError::DecryptionError))
})
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payment records"),
)
})?
.await
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all)]
async fn get_filtered_payment_intents_attempt(
&self,
state: &KeyManagerState,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
merchant_key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<(PaymentIntent, Option<PaymentAttempt>)>, StorageError> {
use diesel::NullableExpressionMethods as _;
use futures::{future::try_join_all, FutureExt};
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPaymentIntent::table()
.filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
.left_join(
payment_attempt_schema::table
.on(pi_dsl::active_attempt_id.eq(pa_dsl::id.nullable())),
)
// Filtering on merchant_id for payment_attempt is not required for v2 as payment_attempt_ids are globally unique
.into_boxed();
query = match constraints {
PaymentIntentFetchConstraints::List(params) => {
query = match params.order {
Order {
on: SortOn::Amount,
by: SortBy::Asc,
} => query.order(pi_dsl::amount.asc()),
Order {
on: SortOn::Amount,
by: SortBy::Desc,
} => query.order(pi_dsl::amount.desc()),
Order {
on: SortOn::Created,
by: SortBy::Asc,
} => query.order(pi_dsl::created_at.asc()),
Order {
on: SortOn::Created,
by: SortBy::Desc,
} => query.order(pi_dsl::created_at.desc()),
};
if let Some(limit) = params.limit {
query = query.limit(limit.into());
}
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(merchant_order_reference_id) = ¶ms.merchant_order_reference_id {
query = query.filter(
pi_dsl::merchant_reference_id.eq(merchant_order_reference_id.clone()),
)
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(pi_dsl::profile_id.eq(profile_id.clone()));
}
query = match (params.starting_at, ¶ms.starting_after_id) {
(Some(starting_at), _) => query.filter(pi_dsl::created_at.ge(starting_at)),
(None, Some(starting_after_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let starting_at = self
.find_payment_intent_by_id(
state,
starting_after_id,
merchant_key_store,
storage_scheme,
)
.await?
.created_at;
query.filter(pi_dsl::created_at.ge(starting_at))
}
(None, None) => query,
};
query = match (params.ending_at, ¶ms.ending_before_id) {
(Some(ending_at), _) => query.filter(pi_dsl::created_at.le(ending_at)),
(None, Some(ending_before_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let ending_at = self
.find_payment_intent_by_id(
state,
ending_before_id,
merchant_key_store,
storage_scheme,
)
.await?
.created_at;
query.filter(pi_dsl::created_at.le(ending_at))
}
(None, None) => query,
};
query = query.offset(params.offset.into());
query = match params.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => query.filter(pi_dsl::amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.le(end)),
_ => query,
};
query = match ¶ms.currency {
Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())),
None => query,
};
query = match ¶ms.connector {
Some(connector) => query.filter(pa_dsl::connector.eq_any(connector.clone())),
None => query,
};
query = match ¶ms.status {
Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())),
None => query,
};
query = match ¶ms.payment_method_type {
Some(payment_method_type) => query
.filter(pa_dsl::payment_method_type_v2.eq_any(payment_method_type.clone())),
None => query,
};
query = match ¶ms.payment_method_subtype {
Some(payment_method_subtype) => query.filter(
pa_dsl::payment_method_subtype.eq_any(payment_method_subtype.clone()),
),
None => query,
};
query = match ¶ms.authentication_type {
Some(authentication_type) => query
.filter(pa_dsl::authentication_type.eq_any(authentication_type.clone())),
None => query,
};
query = match ¶ms.merchant_connector_id {
Some(merchant_connector_id) => query.filter(
pa_dsl::merchant_connector_id.eq_any(merchant_connector_id.clone()),
),
None => query,
};
if let Some(card_network) = ¶ms.card_network {
query = query.filter(pa_dsl::card_network.eq_any(card_network.clone()));
}
if let Some(payment_id) = ¶ms.payment_id {
query = query.filter(pi_dsl::id.eq(payment_id.clone()));
}
query
}
};
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
.get_results_async::<(
DieselPaymentIntent,
Option<diesel_models::payment_attempt::PaymentAttempt>,
)>(conn)
.await
.change_context(StorageError::DecryptionError)
.async_and_then(|output| async {
try_join_all(output.into_iter().map(
|(pi, pa): (_, Option<diesel_models::payment_attempt::PaymentAttempt>)| async {
let payment_intent = PaymentIntent::convert_back(
state,
pi,
merchant_key_store.key.get_inner(),
merchant_id.to_owned().into(),
);
let payment_attempt = pa
.async_map(|val| {
PaymentAttempt::convert_back(
state,
val,
merchant_key_store.key.get_inner(),
merchant_id.to_owned().into(),
)
})
.map(|val| val.transpose());
let output = futures::try_join!(payment_intent, payment_attempt);
output.change_context(StorageError::DecryptionError)
},
))
.await
})
.await
.change_context(StorageError::DecryptionError)
}
#[cfg(all(feature = "v2", feature = "olap"))]
#[instrument(skip_all)]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Option<String>>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPaymentIntent::table()
.select(pi_dsl::active_attempt_id)
.filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
.order(pi_dsl::created_at.desc())
.into_boxed();
query = match constraints {
PaymentIntentFetchConstraints::List(params) => {
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(merchant_order_reference_id) = ¶ms.merchant_order_reference_id {
query = query.filter(
pi_dsl::merchant_reference_id.eq(merchant_order_reference_id.clone()),
)
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(pi_dsl::profile_id.eq(profile_id.clone()));
}
query = match params.starting_at {
Some(starting_at) => query.filter(pi_dsl::created_at.ge(starting_at)),
None => query,
};
query = match params.ending_at {
Some(ending_at) => query.filter(pi_dsl::created_at.le(ending_at)),
None => query,
};
query = match params.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => query.filter(pi_dsl::amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.le(end)),
_ => query,
};
query = match ¶ms.currency {
Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())),
None => query,
};
query = match ¶ms.status {
Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())),
None => query,
};
if let Some(payment_id) = ¶ms.payment_id {
query = query.filter(pi_dsl::id.eq(payment_id.clone()));
}
query
}
};
db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>(
query.get_results_async::<Option<String>>(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payment records"),
)
.into()
})
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PaymentIntentFetchConstraints,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPaymentIntent::table()
.select(pi_dsl::active_attempt_id)
.filter(pi_dsl::merchant_id.eq(merchant_id.to_owned()))
.order(pi_dsl::created_at.desc())
.into_boxed();
query = match constraints {
PaymentIntentFetchConstraints::Single { payment_intent_id } => {
query.filter(pi_dsl::payment_id.eq(payment_intent_id.to_owned()))
}
PaymentIntentFetchConstraints::List(params) => {
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(pi_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(merchant_order_reference_id) = ¶ms.merchant_order_reference_id {
query = query.filter(
pi_dsl::merchant_order_reference_id.eq(merchant_order_reference_id.clone()),
)
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone()));
}
query = match params.starting_at {
Some(starting_at) => query.filter(pi_dsl::created_at.ge(starting_at)),
None => query,
};
query = match params.ending_at {
Some(ending_at) => query.filter(pi_dsl::created_at.le(ending_at)),
None => query,
};
query = match params.amount_filter {
Some(AmountFilter {
start_amount: Some(start),
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.between(start, end)),
Some(AmountFilter {
start_amount: Some(start),
end_amount: None,
}) => query.filter(pi_dsl::amount.ge(start)),
Some(AmountFilter {
start_amount: None,
end_amount: Some(end),
}) => query.filter(pi_dsl::amount.le(end)),
_ => query,
};
query = match ¶ms.currency {
Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())),
None => query,
};
query = match ¶ms.status {
Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())),
None => query,
};
query
}
};
db_metrics::track_database_call::<<DieselPaymentIntent as HasTable>::Table, _, _>(
query.get_results_async::<String>(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payment records"),
)
.into()
})
}
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/payments/payment_intent.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 12603
}
|
large_file_1532394503520628117
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/redis/cache.rs
</path>
<file>
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
);
}
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/redis/cache.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4017
}
|
large_file_2676446709589536942
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/redis/kv_store.rs
</path>
<file>
use std::{fmt::Debug, sync::Arc};
use common_utils::errors::CustomResult;
use diesel_models::enums::MerchantStorageScheme;
use error_stack::report;
use redis_interface::errors::RedisError;
use router_derive::TryGetEnumVariant;
use router_env::logger;
use serde::de;
use crate::{kv_router_store::KVRouterStore, metrics, store::kv::TypedSql, UniqueConstraints};
pub trait KvStorePartition {
fn partition_number(key: PartitionKey<'_>, num_partitions: u8) -> u32 {
crc32fast::hash(key.to_string().as_bytes()) % u32::from(num_partitions)
}
fn shard_key(key: PartitionKey<'_>, num_partitions: u8) -> String {
format!("shard_{}", Self::partition_number(key, num_partitions))
}
}
#[allow(unused)]
#[derive(Clone)]
pub enum PartitionKey<'a> {
MerchantIdPaymentId {
merchant_id: &'a common_utils::id_type::MerchantId,
payment_id: &'a common_utils::id_type::PaymentId,
},
CombinationKey {
combination: &'a str,
},
MerchantIdCustomerId {
merchant_id: &'a common_utils::id_type::MerchantId,
customer_id: &'a common_utils::id_type::CustomerId,
},
#[cfg(feature = "v2")]
MerchantIdMerchantReferenceId {
merchant_id: &'a common_utils::id_type::MerchantId,
merchant_reference_id: &'a str,
},
MerchantIdPayoutId {
merchant_id: &'a common_utils::id_type::MerchantId,
payout_id: &'a common_utils::id_type::PayoutId,
},
MerchantIdPayoutAttemptId {
merchant_id: &'a common_utils::id_type::MerchantId,
payout_attempt_id: &'a str,
},
MerchantIdMandateId {
merchant_id: &'a common_utils::id_type::MerchantId,
mandate_id: &'a str,
},
#[cfg(feature = "v2")]
GlobalId {
id: &'a str,
},
#[cfg(feature = "v2")]
GlobalPaymentId {
id: &'a common_utils::id_type::GlobalPaymentId,
},
}
// PartitionKey::MerchantIdPaymentId {merchant_id, payment_id}
impl std::fmt::Display for PartitionKey<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match *self {
PartitionKey::MerchantIdPaymentId {
merchant_id,
payment_id,
} => f.write_str(&format!(
"mid_{}_pid_{}",
merchant_id.get_string_repr(),
payment_id.get_string_repr()
)),
PartitionKey::CombinationKey { combination } => f.write_str(combination),
PartitionKey::MerchantIdCustomerId {
merchant_id,
customer_id,
} => f.write_str(&format!(
"mid_{}_cust_{}",
merchant_id.get_string_repr(),
customer_id.get_string_repr()
)),
#[cfg(feature = "v2")]
PartitionKey::MerchantIdMerchantReferenceId {
merchant_id,
merchant_reference_id,
} => f.write_str(&format!(
"mid_{}_cust_{merchant_reference_id}",
merchant_id.get_string_repr()
)),
PartitionKey::MerchantIdPayoutId {
merchant_id,
payout_id,
} => f.write_str(&format!(
"mid_{}_po_{}",
merchant_id.get_string_repr(),
payout_id.get_string_repr()
)),
PartitionKey::MerchantIdPayoutAttemptId {
merchant_id,
payout_attempt_id,
} => f.write_str(&format!(
"mid_{}_poa_{payout_attempt_id}",
merchant_id.get_string_repr()
)),
PartitionKey::MerchantIdMandateId {
merchant_id,
mandate_id,
} => f.write_str(&format!(
"mid_{}_mandate_{mandate_id}",
merchant_id.get_string_repr()
)),
#[cfg(feature = "v2")]
PartitionKey::GlobalId { id } => f.write_str(&format!("global_cust_{id}")),
#[cfg(feature = "v2")]
PartitionKey::GlobalPaymentId { id } => {
f.write_str(&format!("global_payment_{}", id.get_string_repr()))
}
}
}
}
pub trait RedisConnInterface {
fn get_redis_conn(
&self,
) -> error_stack::Result<Arc<redis_interface::RedisConnectionPool>, RedisError>;
}
/// An enum to represent what operation to do on
pub enum KvOperation<'a, S: serde::Serialize + Debug> {
Hset((&'a str, String), TypedSql),
SetNx(&'a S, TypedSql),
HSetNx(&'a str, &'a S, TypedSql),
HGet(&'a str),
Get,
Scan(&'a str),
}
#[derive(TryGetEnumVariant)]
#[error(RedisError::UnknownResult)]
pub enum KvResult<T: de::DeserializeOwned> {
HGet(T),
Get(T),
Hset(()),
SetNx(redis_interface::SetnxReply),
HSetNx(redis_interface::HsetnxReply),
Scan(Vec<T>),
}
impl<T> std::fmt::Display for KvOperation<'_, T>
where
T: serde::Serialize + Debug,
{
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
KvOperation::Hset(_, _) => f.write_str("Hset"),
KvOperation::SetNx(_, _) => f.write_str("Setnx"),
KvOperation::HSetNx(_, _, _) => f.write_str("HSetNx"),
KvOperation::HGet(_) => f.write_str("Hget"),
KvOperation::Get => f.write_str("Get"),
KvOperation::Scan(_) => f.write_str("Scan"),
}
}
}
pub async fn kv_wrapper<'a, T, D, S>(
store: &KVRouterStore<D>,
op: KvOperation<'a, S>,
partition_key: PartitionKey<'a>,
) -> CustomResult<KvResult<T>, RedisError>
where
T: de::DeserializeOwned,
D: crate::database::store::DatabaseStore,
S: serde::Serialize + Debug + KvStorePartition + UniqueConstraints + Sync,
{
let redis_conn = store.get_redis_conn()?;
let key = format!("{partition_key}");
let type_name = std::any::type_name::<T>();
let operation = op.to_string();
let ttl = store.ttl_for_kv;
let result = async {
match op {
KvOperation::Hset(value, sql) => {
logger::debug!(kv_operation= %operation, value = ?value);
redis_conn
.set_hash_fields(&key.into(), value, Some(ttl.into()))
.await?;
store
.push_to_drainer_stream::<S>(sql, partition_key)
.await?;
Ok(KvResult::Hset(()))
}
KvOperation::HGet(field) => {
let result = redis_conn
.get_hash_field_and_deserialize(&key.into(), field, type_name)
.await?;
Ok(KvResult::HGet(result))
}
KvOperation::Scan(pattern) => {
let result: Vec<T> = redis_conn
.hscan_and_deserialize(&key.into(), pattern, None)
.await
.and_then(|result| {
if result.is_empty() {
Err(report!(RedisError::NotFound))
} else {
Ok(result)
}
})?;
Ok(KvResult::Scan(result))
}
KvOperation::HSetNx(field, value, sql) => {
logger::debug!(kv_operation= %operation, value = ?value);
value.check_for_constraints(&redis_conn).await?;
let result = redis_conn
.serialize_and_set_hash_field_if_not_exist(&key.into(), field, value, Some(ttl))
.await?;
if matches!(result, redis_interface::HsetnxReply::KeySet) {
store
.push_to_drainer_stream::<S>(sql, partition_key)
.await?;
Ok(KvResult::HSetNx(result))
} else {
Err(report!(RedisError::SetNxFailed))
}
}
KvOperation::SetNx(value, sql) => {
logger::debug!(kv_operation= %operation, value = ?value);
let result = redis_conn
.serialize_and_set_key_if_not_exist(&key.into(), value, Some(ttl.into()))
.await?;
value.check_for_constraints(&redis_conn).await?;
if matches!(result, redis_interface::SetnxReply::KeySet) {
store
.push_to_drainer_stream::<S>(sql, partition_key)
.await?;
Ok(KvResult::SetNx(result))
} else {
Err(report!(RedisError::SetNxFailed))
}
}
KvOperation::Get => {
let result = redis_conn
.get_and_deserialize_key(&key.into(), type_name)
.await?;
Ok(KvResult::Get(result))
}
}
};
let attributes = router_env::metric_attributes!(("operation", operation.clone()));
result
.await
.inspect(|_| {
logger::debug!(kv_operation= %operation, status="success");
metrics::KV_OPERATION_SUCCESSFUL.add(1, attributes);
})
.inspect_err(|err| {
logger::error!(kv_operation = %operation, status="error", error = ?err);
metrics::KV_OPERATION_FAILED.add(1, attributes);
})
}
pub enum Op<'a> {
Insert,
Update(PartitionKey<'a>, &'a str, Option<&'a str>),
Find,
}
impl std::fmt::Display for Op<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Op::Insert => f.write_str("insert"),
Op::Find => f.write_str("find"),
Op::Update(p_key, _, updated_by) => {
f.write_str(&format!("update_{p_key} for updated_by_{updated_by:?}"))
}
}
}
}
pub async fn decide_storage_scheme<T, D>(
store: &KVRouterStore<T>,
storage_scheme: MerchantStorageScheme,
operation: Op<'_>,
) -> MerchantStorageScheme
where
D: de::DeserializeOwned
+ serde::Serialize
+ Debug
+ KvStorePartition
+ UniqueConstraints
+ Sync,
T: crate::database::store::DatabaseStore,
{
if store.soft_kill_mode {
let ops = operation.to_string();
let updated_scheme = match operation {
Op::Insert => MerchantStorageScheme::PostgresOnly,
Op::Find => MerchantStorageScheme::RedisKv,
Op::Update(_, _, Some("postgres_only")) => MerchantStorageScheme::PostgresOnly,
Op::Update(partition_key, field, Some(_updated_by)) => {
match Box::pin(kv_wrapper::<D, _, _>(
store,
KvOperation::<D>::HGet(field),
partition_key,
))
.await
{
Ok(_) => {
metrics::KV_SOFT_KILL_ACTIVE_UPDATE.add(1, &[]);
MerchantStorageScheme::RedisKv
}
Err(_) => MerchantStorageScheme::PostgresOnly,
}
}
Op::Update(_, _, None) => MerchantStorageScheme::PostgresOnly,
};
let type_name = std::any::type_name::<D>();
logger::info!(soft_kill_mode = "decide_storage_scheme", decided_scheme = %updated_scheme, configured_scheme = %storage_scheme,entity = %type_name, operation = %ops);
updated_scheme
} else {
storage_scheme
}
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/redis/kv_store.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2591
}
|
large_file_6699375452115000229
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/mock_db/payment_attempt.rs
</path>
<file>
use common_utils::errors::CustomResult;
#[cfg(feature = "v2")]
use common_utils::{id_type, types::keymanager::KeyManagerState};
use diesel_models::enums as storage_enums;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::merchant_key_store::MerchantKeyStore;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew;
use hyperswitch_domain_models::payments::payment_attempt::{
PaymentAttempt, PaymentAttemptInterface, PaymentAttemptUpdate,
};
use super::MockDb;
use crate::errors::StorageError;
#[cfg(feature = "v1")]
use crate::DataModelExt;
#[async_trait::async_trait]
impl PaymentAttemptInterface for MockDb {
type Error = StorageError;
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&self,
_payment_id: &common_utils::id_type::PaymentId,
_merchant_id: &common_utils::id_type::MerchantId,
_attempt_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_filters_for_payments(
&self,
_pi: &[hyperswitch_domain_models::payments::PaymentIntent],
_merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<
hyperswitch_domain_models::payments::payment_attempt::PaymentListFilters,
StorageError,
> {
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_total_count_of_filtered_payment_attempts(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_active_attempt_ids: &[String],
_connector: Option<Vec<api_models::enums::Connector>>,
_payment_method: Option<Vec<common_enums::PaymentMethod>>,
_payment_method_type: Option<Vec<common_enums::PaymentMethodType>>,
_authentication_type: Option<Vec<common_enums::AuthenticationType>>,
_merchanat_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>,
_card_network: Option<Vec<storage_enums::CardNetwork>>,
_card_discovery: Option<Vec<storage_enums::CardDiscovery>>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<i64, StorageError> {
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v2", feature = "olap"))]
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<common_enums::PaymentMethod>>,
_payment_method_subtype: Option<Vec<common_enums::PaymentMethodType>>,
_authentication_type: Option<Vec<common_enums::AuthenticationType>>,
_merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>,
_card_network: Option<Vec<storage_enums::CardNetwork>>,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<i64, StorageError> {
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_attempt_id_merchant_id(
&self,
_attempt_id: &str,
_merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[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, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v2")]
async fn find_payment_attempts_by_payment_intent_id(
&self,
_key_manager_state: &KeyManagerState,
_id: &id_type::GlobalPaymentId,
_merchant_key_store: &MerchantKeyStore,
_storage_scheme: common_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<PaymentAttempt>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_preprocessing_id_merchant_id(
&self,
_preprocessing_id: &str,
_merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_merchant_id_connector_txn_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_txn_id: &str,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[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, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn find_attempts_by_merchant_id_payment_id(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_payment_id: &common_utils::id_type::PaymentId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentAttempt>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
#[allow(clippy::panic)]
async fn insert_payment_attempt(
&self,
payment_attempt: PaymentAttemptNew,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
let mut payment_attempts = self.payment_attempts.lock().await;
let time = common_utils::date_time::now();
let payment_attempt = PaymentAttempt {
payment_id: payment_attempt.payment_id,
merchant_id: payment_attempt.merchant_id,
attempt_id: payment_attempt.attempt_id,
status: payment_attempt.status,
net_amount: payment_attempt.net_amount,
currency: payment_attempt.currency,
save_to_locker: payment_attempt.save_to_locker,
connector: payment_attempt.connector,
error_message: payment_attempt.error_message,
offer_amount: payment_attempt.offer_amount,
payment_method_id: payment_attempt.payment_method_id,
payment_method: payment_attempt.payment_method,
connector_transaction_id: None,
capture_method: payment_attempt.capture_method,
capture_on: payment_attempt.capture_on,
confirm: payment_attempt.confirm,
authentication_type: payment_attempt.authentication_type,
created_at: payment_attempt.created_at.unwrap_or(time),
modified_at: payment_attempt.modified_at.unwrap_or(time),
last_synced: payment_attempt.last_synced,
cancellation_reason: payment_attempt.cancellation_reason,
amount_to_capture: payment_attempt.amount_to_capture,
mandate_id: None,
browser_info: None,
payment_token: None,
error_code: payment_attempt.error_code,
connector_metadata: None,
charge_id: None,
payment_experience: payment_attempt.payment_experience,
payment_method_type: payment_attempt.payment_method_type,
payment_method_data: payment_attempt.payment_method_data,
business_sub_label: payment_attempt.business_sub_label,
straight_through_algorithm: payment_attempt.straight_through_algorithm,
mandate_details: payment_attempt.mandate_details,
preprocessing_step_id: payment_attempt.preprocessing_step_id,
error_reason: payment_attempt.error_reason,
multiple_capture_count: payment_attempt.multiple_capture_count,
connector_response_reference_id: None,
amount_capturable: payment_attempt.amount_capturable,
updated_by: storage_scheme.to_string(),
authentication_data: payment_attempt.authentication_data,
encoded_data: payment_attempt.encoded_data,
merchant_connector_id: payment_attempt.merchant_connector_id,
unified_code: payment_attempt.unified_code,
unified_message: payment_attempt.unified_message,
external_three_ds_authentication_attempted: payment_attempt
.external_three_ds_authentication_attempted,
authentication_connector: payment_attempt.authentication_connector,
authentication_id: payment_attempt.authentication_id,
mandate_data: payment_attempt.mandate_data,
payment_method_billing_address_id: payment_attempt.payment_method_billing_address_id,
fingerprint_id: payment_attempt.fingerprint_id,
client_source: payment_attempt.client_source,
client_version: payment_attempt.client_version,
customer_acceptance: payment_attempt.customer_acceptance,
organization_id: payment_attempt.organization_id,
profile_id: payment_attempt.profile_id,
connector_mandate_detail: payment_attempt.connector_mandate_detail,
request_extended_authorization: payment_attempt.request_extended_authorization,
extended_authorization_applied: payment_attempt.extended_authorization_applied,
capture_before: payment_attempt.capture_before,
card_discovery: payment_attempt.card_discovery,
charges: None,
issuer_error_code: None,
issuer_error_message: None,
processor_merchant_id: payment_attempt.processor_merchant_id,
created_by: payment_attempt.created_by,
setup_future_usage_applied: payment_attempt.setup_future_usage_applied,
routing_approach: payment_attempt.routing_approach,
connector_request_reference_id: payment_attempt.connector_request_reference_id,
debit_routing_savings: None,
network_transaction_id: payment_attempt.network_transaction_id,
is_overcapture_enabled: None,
network_details: payment_attempt.network_details,
is_stored_credential: payment_attempt.is_stored_credential,
authorized_amount: payment_attempt.authorized_amount,
};
payment_attempts.push(payment_attempt.clone());
Ok(payment_attempt)
}
#[cfg(feature = "v2")]
#[allow(clippy::panic)]
async fn insert_payment_attempt(
&self,
_key_manager_state: &KeyManagerState,
_merchant_key_store: &MerchantKeyStore,
_payment_attempt: PaymentAttempt,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
// safety: only used for testing
#[allow(clippy::unwrap_used)]
async fn update_payment_attempt_with_attempt_id(
&self,
this: PaymentAttempt,
payment_attempt: PaymentAttemptUpdate,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
let mut payment_attempts = self.payment_attempts.lock().await;
let item = payment_attempts
.iter_mut()
.find(|item| item.attempt_id == this.attempt_id)
.unwrap();
*item = PaymentAttempt::from_storage_model(
payment_attempt
.to_storage_model()
.apply_changeset(this.to_storage_model()),
);
Ok(item.clone())
}
#[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,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
async fn find_payment_attempt_by_connector_transaction_id_payment_id_merchant_id(
&self,
_connector_transaction_id: &common_utils::types::ConnectorTransactionId,
_payment_id: &common_utils::id_type::PaymentId,
_merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "v1")]
// safety: only used for testing
#[allow(clippy::unwrap_used)]
async fn find_payment_attempt_last_successful_attempt_by_payment_id_merchant_id(
&self,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
let payment_attempts = self.payment_attempts.lock().await;
Ok(payment_attempts
.iter()
.find(|payment_attempt| {
payment_attempt.payment_id == *payment_id
&& payment_attempt.merchant_id.eq(merchant_id)
})
.cloned()
.unwrap())
}
#[cfg(feature = "v1")]
#[allow(clippy::unwrap_used)]
async fn find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id_merchant_id(
&self,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentAttempt, StorageError> {
let payment_attempts = self.payment_attempts.lock().await;
Ok(payment_attempts
.iter()
.find(|payment_attempt| {
payment_attempt.payment_id == *payment_id
&& payment_attempt.merchant_id.eq(merchant_id)
&& (payment_attempt.status == storage_enums::AttemptStatus::PartialCharged
|| payment_attempt.status == storage_enums::AttemptStatus::Charged)
})
.cloned()
.unwrap())
}
#[cfg(feature = "v2")]
#[allow(clippy::unwrap_used)]
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,
) -> CustomResult<PaymentAttempt, StorageError> {
let payment_attempts = self.payment_attempts.lock().await;
Ok(payment_attempts
.iter()
.find(|payment_attempt| {
payment_attempt.payment_id == *payment_id
&& (payment_attempt.status == storage_enums::AttemptStatus::PartialCharged
|| payment_attempt.status == storage_enums::AttemptStatus::Charged)
})
.cloned()
.unwrap())
}
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/mock_db/payment_attempt.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3466
}
|
large_file_-5050199519478095459
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/mock_db/payment_intent.rs
</path>
<file>
use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState};
use diesel_models::enums as storage_enums;
#[cfg(feature = "v1")]
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::behaviour::Conversion;
use hyperswitch_domain_models::{
merchant_key_store::MerchantKeyStore,
payments::{
payment_intent::{PaymentIntentInterface, PaymentIntentUpdate},
PaymentIntent,
},
};
use super::MockDb;
use crate::errors::StorageError;
#[async_trait::async_trait]
impl PaymentIntentInterface for MockDb {
type Error = StorageError;
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_payment_intent_by_constraints(
&self,
_state: &KeyManagerState,
_merchant_id: &common_utils::id_type::MerchantId,
_filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v2", feature = "olap"))]
async fn get_filtered_payment_intents_attempt(
&self,
_state: &KeyManagerState,
_merchant_id: &common_utils::id_type::MerchantId,
_constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_merchant_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<
Vec<(
PaymentIntent,
Option<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>,
)>,
StorageError,
> {
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_payment_intents_by_time_range_constraints(
&self,
_state: &KeyManagerState,
_merchant_id: &common_utils::id_type::MerchantId,
_time_range: &common_utils::types::TimeRange,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "olap")]
async fn get_intent_status_with_count(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v2", feature = "olap"))]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<Option<String>>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_filtered_payment_intents_attempt(
&self,
_state: &KeyManagerState,
_merchant_id: &common_utils::id_type::MerchantId,
_constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<
Vec<(
PaymentIntent,
hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
)>,
StorageError,
> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[allow(clippy::panic)]
async fn insert_payment_intent(
&self,
_state: &KeyManagerState,
new: PaymentIntent,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, StorageError> {
let mut payment_intents = self.payment_intents.lock().await;
payment_intents.push(new.clone());
Ok(new)
}
#[cfg(feature = "v1")]
// safety: only used for testing
#[allow(clippy::unwrap_used)]
async fn update_payment_intent(
&self,
state: &KeyManagerState,
this: PaymentIntent,
update: PaymentIntentUpdate,
key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, StorageError> {
let mut payment_intents = self.payment_intents.lock().await;
let payment_intent = payment_intents
.iter_mut()
.find(|item| item.get_id() == this.get_id() && item.merchant_id == this.merchant_id)
.unwrap();
let diesel_payment_intent_update = diesel_models::PaymentIntentUpdate::from(update);
let diesel_payment_intent = payment_intent
.clone()
.convert()
.await
.change_context(StorageError::EncryptionError)?;
*payment_intent = PaymentIntent::convert_back(
state,
diesel_payment_intent_update.apply_changeset(diesel_payment_intent),
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?;
Ok(payment_intent.clone())
}
#[cfg(feature = "v2")]
// safety: only used for testing
#[allow(clippy::unwrap_used)]
async fn update_payment_intent(
&self,
_state: &KeyManagerState,
_this: PaymentIntent,
_update: PaymentIntentUpdate,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, StorageError> {
todo!()
}
#[cfg(feature = "v1")]
// safety: only used for testing
#[allow(clippy::unwrap_used)]
async fn find_payment_intent_by_payment_id_merchant_id(
&self,
_state: &KeyManagerState,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, StorageError> {
let payment_intents = self.payment_intents.lock().await;
Ok(payment_intents
.iter()
.find(|payment_intent| {
payment_intent.get_id() == payment_id && payment_intent.merchant_id.eq(merchant_id)
})
.cloned()
.unwrap())
}
#[cfg(feature = "v2")]
async fn find_payment_intent_by_id(
&self,
_state: &KeyManagerState,
id: &common_utils::id_type::GlobalPaymentId,
_merchant_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let payment_intents = self.payment_intents.lock().await;
let payment_intent = payment_intents
.iter()
.find(|payment_intent| payment_intent.get_id() == id)
.ok_or(StorageError::ValueNotFound(
"PaymentIntent not found".to_string(),
))?;
Ok(payment_intent.clone())
}
#[cfg(feature = "v2")]
async fn find_payment_intent_by_merchant_reference_id_profile_id(
&self,
_state: &KeyManagerState,
merchant_reference_id: &common_utils::id_type::PaymentReferenceId,
profile_id: &common_utils::id_type::ProfileId,
_merchant_key_store: &MerchantKeyStore,
_storage_scheme: &common_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let payment_intents = self.payment_intents.lock().await;
let payment_intent = payment_intents
.iter()
.find(|payment_intent| {
payment_intent.merchant_reference_id.as_ref() == Some(merchant_reference_id)
&& payment_intent.profile_id.eq(profile_id)
})
.ok_or(StorageError::ValueNotFound(
"PaymentIntent not found".to_string(),
))?;
Ok(payment_intent.clone())
}
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/mock_db/payment_intent.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2108
}
|
large_file_8841807986710983409
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/payouts/payouts.rs
</path>
<file>
#[cfg(feature = "olap")]
use api_models::enums::PayoutConnectors;
#[cfg(feature = "olap")]
use async_bb8_diesel::{AsyncConnection, AsyncRunQueryDsl};
use common_utils::ext_traits::Encode;
#[cfg(feature = "olap")]
use diesel::{associations::HasTable, ExpressionMethods, QueryDsl};
#[cfg(all(feature = "v1", feature = "olap"))]
use diesel::{JoinOnDsl, NullableExpressionMethods};
#[cfg(feature = "olap")]
use diesel_models::{
address::Address as DieselAddress, customers::Customer as DieselCustomer,
enums as storage_enums, query::generics::db_metrics, schema::payouts::dsl as po_dsl,
};
use diesel_models::{
enums::MerchantStorageScheme,
kv,
payouts::{
Payouts as DieselPayouts, PayoutsNew as DieselPayoutsNew,
PayoutsUpdate as DieselPayoutsUpdate,
},
};
#[cfg(all(feature = "olap", feature = "v1"))]
use diesel_models::{
payout_attempt::PayoutAttempt as DieselPayoutAttempt,
schema::{address::dsl as add_dsl, customers::dsl as cust_dsl, payout_attempt::dsl as poa_dsl},
};
use error_stack::ResultExt;
#[cfg(feature = "olap")]
use hyperswitch_domain_models::payouts::PayoutFetchConstraints;
use hyperswitch_domain_models::payouts::{
payout_attempt::PayoutAttempt,
payouts::{Payouts, PayoutsInterface, PayoutsNew, PayoutsUpdate},
};
use redis_interface::HsetnxReply;
#[cfg(feature = "olap")]
use router_env::logger;
use router_env::{instrument, tracing};
#[cfg(feature = "olap")]
use crate::connection;
#[cfg(all(feature = "olap", feature = "v1"))]
use crate::store::schema::{
address::all_columns as addr_all_columns, customers::all_columns as cust_all_columns,
payout_attempt::all_columns as poa_all_columns, payouts::all_columns as po_all_columns,
};
use crate::{
diesel_error_to_data_error,
errors::{RedisErrorExt, StorageError},
kv_router_store::KVRouterStore,
redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey},
utils::{self, pg_connection_read, pg_connection_write},
DataModelExt, DatabaseStore,
};
#[async_trait::async_trait]
impl<T: DatabaseStore> PayoutsInterface for KVRouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
async fn insert_payout(
&self,
new: PayoutsNew,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store.insert_payout(new, storage_scheme).await
}
MerchantStorageScheme::RedisKv => {
let merchant_id = new.merchant_id.clone();
let payout_id = new.payout_id.clone();
let key = PartitionKey::MerchantIdPayoutId {
merchant_id: &merchant_id,
payout_id: &payout_id,
};
let key_str = key.to_string();
let field = format!("po_{}", new.payout_id.get_string_repr());
let created_payout = Payouts {
payout_id: new.payout_id.clone(),
merchant_id: new.merchant_id.clone(),
customer_id: new.customer_id.clone(),
address_id: new.address_id.clone(),
payout_type: new.payout_type,
payout_method_id: new.payout_method_id.clone(),
amount: new.amount,
destination_currency: new.destination_currency,
source_currency: new.source_currency,
description: new.description.clone(),
recurring: new.recurring,
auto_fulfill: new.auto_fulfill,
return_url: new.return_url.clone(),
entity_type: new.entity_type,
metadata: new.metadata.clone(),
created_at: new.created_at,
last_modified_at: new.last_modified_at,
profile_id: new.profile_id.clone(),
status: new.status,
attempt_count: new.attempt_count,
confirm: new.confirm,
payout_link_id: new.payout_link_id.clone(),
client_secret: new.client_secret.clone(),
priority: new.priority,
};
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::Payouts(new.to_storage_model())),
},
};
match Box::pin(kv_wrapper::<DieselPayouts, _, _>(
self,
KvOperation::<DieselPayouts>::HSetNx(
&field,
&created_payout.clone().to_storage_model(),
redis_entry,
),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
{
Ok(HsetnxReply::KeyNotSet) => Err(StorageError::DuplicateValue {
entity: "payouts",
key: Some(key_str),
}
.into()),
Ok(HsetnxReply::KeySet) => Ok(created_payout),
Err(error) => Err(error.change_context(StorageError::KVError)),
}
}
}
}
#[instrument(skip_all)]
async fn update_payout(
&self,
this: &Payouts,
payout_update: PayoutsUpdate,
payout_attempt: &PayoutAttempt,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, StorageError> {
let key = PartitionKey::MerchantIdPayoutId {
merchant_id: &this.merchant_id,
payout_id: &this.payout_id,
};
let field = format!("po_{}", this.payout_id.get_string_repr());
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>(
self,
storage_scheme,
Op::Update(key.clone(), &field, None),
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.update_payout(this, payout_update, payout_attempt, storage_scheme)
.await
}
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let diesel_payout_update = payout_update.to_storage_model();
let origin_diesel_payout = this.clone().to_storage_model();
let diesel_payout = diesel_payout_update
.clone()
.apply_changeset(origin_diesel_payout.clone());
// Check for database presence as well Maybe use a read replica here ?
let redis_value = diesel_payout
.encode_to_string_of_json()
.change_context(StorageError::SerializationFailed)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
updatable: Box::new(kv::Updateable::PayoutsUpdate(kv::PayoutsUpdateMems {
orig: origin_diesel_payout,
update_data: diesel_payout_update,
})),
},
};
Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<DieselPayouts>::Hset((&field, redis_value), redis_entry),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hset()
.change_context(StorageError::KVError)?;
Ok(Payouts::from_storage_model(diesel_payout))
}
}
}
#[instrument(skip_all)]
async fn find_payout_by_merchant_id_payout_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &common_utils::id_type::PayoutId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, StorageError> {
let database_call = || async {
let conn = pg_connection_read(self).await?;
DieselPayouts::find_by_merchant_id_payout_id(&conn, merchant_id, payout_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => database_call().await,
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdPayoutId {
merchant_id,
payout_id,
};
let field = format!("po_{}", payout_id.get_string_repr());
Box::pin(utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper::<DieselPayouts, _, _>(
self,
KvOperation::<DieselPayouts>::HGet(&field),
key,
))
.await?
.try_into_hget()
},
database_call,
))
.await
}
}
.map(Payouts::from_storage_model)
}
#[instrument(skip_all)]
async fn find_optional_payout_by_merchant_id_payout_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &common_utils::id_type::PayoutId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Option<Payouts>, StorageError> {
let database_call = || async {
let conn = pg_connection_read(self).await?;
DieselPayouts::find_optional_by_merchant_id_payout_id(&conn, merchant_id, payout_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
};
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayouts>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
let maybe_payouts = database_call().await?;
Ok(maybe_payouts.filter(|payout| &payout.payout_id == payout_id))
}
MerchantStorageScheme::RedisKv => {
let key = PartitionKey::MerchantIdPayoutId {
merchant_id,
payout_id,
};
let field = format!("po_{}", payout_id.get_string_repr());
Box::pin(utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper::<DieselPayouts, _, _>(
self,
KvOperation::<DieselPayouts>::HGet(&field),
key,
))
.await?
.try_into_hget()
.map(Some)
},
database_call,
))
.await
}
}
.map(|payout| payout.map(Payouts::from_storage_model))
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn filter_payouts_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
filters: &PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
self.router_store
.filter_payouts_by_constraints(merchant_id, filters, storage_scheme)
.await
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn filter_payouts_and_attempts(
&self,
merchant_id: &common_utils::id_type::MerchantId,
filters: &PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<
Vec<(
Payouts,
PayoutAttempt,
Option<DieselCustomer>,
Option<DieselAddress>,
)>,
StorageError,
> {
self.router_store
.filter_payouts_and_attempts(merchant_id, filters, storage_scheme)
.await
}
#[cfg(feature = "olap")]
#[instrument[skip_all]]
async fn filter_payouts_by_time_range_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
time_range: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
self.router_store
.filter_payouts_by_time_range_constraints(merchant_id, time_range, storage_scheme)
.await
}
#[cfg(feature = "olap")]
async fn get_total_count_of_filtered_payouts(
&self,
merchant_id: &common_utils::id_type::MerchantId,
active_payout_ids: &[common_utils::id_type::PayoutId],
connector: Option<Vec<PayoutConnectors>>,
currency: Option<Vec<storage_enums::Currency>>,
status: Option<Vec<storage_enums::PayoutStatus>>,
payout_method: Option<Vec<storage_enums::PayoutType>>,
) -> error_stack::Result<i64, StorageError> {
self.router_store
.get_total_count_of_filtered_payouts(
merchant_id,
active_payout_ids,
connector,
currency,
status,
payout_method,
)
.await
}
#[cfg(feature = "olap")]
async fn filter_active_payout_ids_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PayoutFetchConstraints,
) -> error_stack::Result<Vec<common_utils::id_type::PayoutId>, StorageError> {
self.router_store
.filter_active_payout_ids_by_constraints(merchant_id, constraints)
.await
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> PayoutsInterface for crate::RouterStore<T> {
type Error = StorageError;
#[instrument(skip_all)]
async fn insert_payout(
&self,
new: PayoutsNew,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, StorageError> {
let conn = pg_connection_write(self).await?;
new.to_storage_model()
.insert(&conn)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(Payouts::from_storage_model)
}
#[instrument(skip_all)]
async fn update_payout(
&self,
this: &Payouts,
payout: PayoutsUpdate,
_payout_attempt: &PayoutAttempt,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, StorageError> {
let conn = pg_connection_write(self).await?;
this.clone()
.to_storage_model()
.update(&conn, payout.to_storage_model())
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(Payouts::from_storage_model)
}
#[instrument(skip_all)]
async fn find_payout_by_merchant_id_payout_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &common_utils::id_type::PayoutId,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Payouts, StorageError> {
let conn = pg_connection_read(self).await?;
DieselPayouts::find_by_merchant_id_payout_id(&conn, merchant_id, payout_id)
.await
.map(Payouts::from_storage_model)
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
#[instrument(skip_all)]
async fn find_optional_payout_by_merchant_id_payout_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payout_id: &common_utils::id_type::PayoutId,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Option<Payouts>, StorageError> {
let conn = pg_connection_read(self).await?;
DieselPayouts::find_optional_by_merchant_id_payout_id(&conn, merchant_id, payout_id)
.await
.map(|x| x.map(Payouts::from_storage_model))
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn filter_payouts_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
filters: &PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
//[#350]: Replace this with Boxable Expression and pass it into generic filter
// when https://github.com/rust-lang/rust/issues/52662 becomes stable
let mut query = <DieselPayouts as HasTable>::table()
.filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))
.order(po_dsl::created_at.desc())
.into_boxed();
match filters {
PayoutFetchConstraints::Single { payout_id } => {
query = query.filter(po_dsl::payout_id.eq(payout_id.to_owned()));
}
PayoutFetchConstraints::List(params) => {
if let Some(limit) = params.limit {
query = query.limit(limit.into());
}
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(po_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(po_dsl::profile_id.eq(profile_id.clone()));
}
query = match (params.starting_at, params.starting_after_id.as_ref()) {
(Some(starting_at), _) => query.filter(po_dsl::created_at.ge(starting_at)),
(None, Some(starting_after_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let starting_at = self
.find_payout_by_merchant_id_payout_id(
merchant_id,
starting_after_id,
storage_scheme,
)
.await?
.created_at;
query.filter(po_dsl::created_at.ge(starting_at))
}
(None, None) => query,
};
query = match (params.ending_at, params.ending_before_id.as_ref()) {
(Some(ending_at), _) => query.filter(po_dsl::created_at.le(ending_at)),
(None, Some(ending_before_id)) => {
// TODO: Fetch partial columns for this query since we only need some columns
let ending_at = self
.find_payout_by_merchant_id_payout_id(
merchant_id,
ending_before_id,
storage_scheme,
)
.await?
.created_at;
query.filter(po_dsl::created_at.le(ending_at))
}
(None, None) => query,
};
query = query.offset(params.offset.into());
if let Some(currency) = ¶ms.currency {
query = query.filter(po_dsl::destination_currency.eq_any(currency.clone()));
}
if let Some(status) = ¶ms.status {
query = query.filter(po_dsl::status.eq_any(status.clone()));
}
}
}
logger::debug!(query = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<DieselPayouts as HasTable>::Table, _, _>(
query.get_results_async::<DieselPayouts>(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.map(|payouts| {
payouts
.into_iter()
.map(Payouts::from_storage_model)
.collect::<Vec<Payouts>>()
})
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payout records"),
)
.into()
})
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn filter_payouts_and_attempts(
&self,
merchant_id: &common_utils::id_type::MerchantId,
filters: &PayoutFetchConstraints,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<
Vec<(
Payouts,
PayoutAttempt,
Option<DieselCustomer>,
Option<DieselAddress>,
)>,
StorageError,
> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPayouts::table()
.inner_join(
diesel_models::schema::payout_attempt::table
.on(poa_dsl::payout_id.eq(po_dsl::payout_id)),
)
.left_join(
diesel_models::schema::customers::table
.on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)),
)
.filter(cust_dsl::merchant_id.eq(merchant_id.to_owned()))
.left_outer_join(
diesel_models::schema::address::table
.on(add_dsl::address_id.nullable().eq(po_dsl::address_id)),
)
.filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))
.order(po_dsl::created_at.desc())
.into_boxed();
query = match filters {
PayoutFetchConstraints::Single { payout_id } => {
query.filter(po_dsl::payout_id.eq(payout_id.to_owned()))
}
PayoutFetchConstraints::List(params) => {
if let Some(limit) = params.limit {
query = query.limit(limit.into());
}
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(po_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(po_dsl::profile_id.eq(profile_id.clone()));
}
if let Some(merchant_order_reference_id_filter) =
¶ms.merchant_order_reference_id
{
query = query.filter(
poa_dsl::merchant_order_reference_id
.eq(merchant_order_reference_id_filter.clone()),
);
}
query = match (params.starting_at, params.starting_after_id.as_ref()) {
(Some(starting_at), _) => query.filter(po_dsl::created_at.ge(starting_at)),
(None, Some(starting_after_id)) => {
let starting_at = self
.find_payout_by_merchant_id_payout_id(
merchant_id,
starting_after_id,
storage_scheme,
)
.await?
.created_at;
query.filter(po_dsl::created_at.ge(starting_at))
}
(None, None) => query,
};
query = match (params.ending_at, params.ending_before_id.as_ref()) {
(Some(ending_at), _) => query.filter(po_dsl::created_at.le(ending_at)),
(None, Some(ending_before_id)) => {
let ending_at = self
.find_payout_by_merchant_id_payout_id(
merchant_id,
ending_before_id,
storage_scheme,
)
.await?
.created_at;
query.filter(po_dsl::created_at.le(ending_at))
}
(None, None) => query,
};
query = query.offset(params.offset.into());
if let Some(currency) = ¶ms.currency {
query = query.filter(po_dsl::destination_currency.eq_any(currency.clone()));
}
let connectors = params
.connector
.as_ref()
.map(|c| c.iter().map(|c| c.to_string()).collect::<Vec<String>>());
query = match connectors {
Some(conn_filters) if !conn_filters.is_empty() => {
query.filter(poa_dsl::connector.eq_any(conn_filters))
}
_ => query,
};
query = match ¶ms.status {
Some(status_filters) if !status_filters.is_empty() => {
query.filter(po_dsl::status.eq_any(status_filters.clone()))
}
_ => query,
};
query = match ¶ms.payout_method {
Some(payout_method) if !payout_method.is_empty() => {
query.filter(po_dsl::payout_type.eq_any(payout_method.clone()))
}
_ => query,
};
query
}
};
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
query
.select((
po_all_columns,
poa_all_columns,
cust_all_columns.nullable(),
addr_all_columns.nullable(),
))
.get_results_async::<(
DieselPayouts,
DieselPayoutAttempt,
Option<DieselCustomer>,
Option<DieselAddress>,
)>(conn)
.await
.map(|results| {
results
.into_iter()
.map(|(pi, pa, c, add)| {
(
Payouts::from_storage_model(pi),
PayoutAttempt::from_storage_model(pa),
c,
add,
)
})
.collect()
})
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payout records"),
)
.into()
})
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all)]
async fn filter_payouts_and_attempts(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_filters: &PayoutFetchConstraints,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<
Vec<(
Payouts,
PayoutAttempt,
Option<DieselCustomer>,
Option<DieselAddress>,
)>,
StorageError,
> {
todo!()
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn filter_payouts_by_time_range_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
time_range: &common_utils::types::TimeRange,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<Vec<Payouts>, StorageError> {
let payout_filters = (*time_range).into();
self.filter_payouts_by_constraints(merchant_id, &payout_filters, storage_scheme)
.await
}
#[cfg(feature = "olap")]
#[instrument(skip_all)]
async fn get_total_count_of_filtered_payouts(
&self,
merchant_id: &common_utils::id_type::MerchantId,
active_payout_ids: &[common_utils::id_type::PayoutId],
connector: Option<Vec<PayoutConnectors>>,
currency: Option<Vec<storage_enums::Currency>>,
status: Option<Vec<storage_enums::PayoutStatus>>,
payout_type: Option<Vec<storage_enums::PayoutType>>,
) -> error_stack::Result<i64, StorageError> {
let conn = self
.db_store
.get_replica_pool()
.get()
.await
.change_context(StorageError::DatabaseConnectionError)?;
let connector_strings = connector.as_ref().map(|connectors| {
connectors
.iter()
.map(|c| c.to_string())
.collect::<Vec<String>>()
});
DieselPayouts::get_total_count_of_payouts(
&conn,
merchant_id,
active_payout_ids,
connector_strings,
currency,
status,
payout_type,
)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
#[cfg(all(feature = "v1", feature = "olap"))]
#[instrument(skip_all)]
async fn filter_active_payout_ids_by_constraints(
&self,
merchant_id: &common_utils::id_type::MerchantId,
constraints: &PayoutFetchConstraints,
) -> error_stack::Result<Vec<common_utils::id_type::PayoutId>, StorageError> {
let conn = connection::pg_connection_read(self).await?;
let conn = async_bb8_diesel::Connection::as_async_conn(&conn);
let mut query = DieselPayouts::table()
.inner_join(
diesel_models::schema::payout_attempt::table
.on(poa_dsl::payout_id.eq(po_dsl::payout_id)),
)
.left_join(
diesel_models::schema::customers::table
.on(cust_dsl::customer_id.nullable().eq(po_dsl::customer_id)),
)
.select(po_dsl::payout_id)
.filter(cust_dsl::merchant_id.eq(merchant_id.to_owned()))
.filter(po_dsl::merchant_id.eq(merchant_id.to_owned()))
.order(po_dsl::created_at.desc())
.into_boxed();
query = match constraints {
PayoutFetchConstraints::Single { payout_id } => {
query.filter(po_dsl::payout_id.eq(payout_id.to_owned()))
}
PayoutFetchConstraints::List(params) => {
if let Some(customer_id) = ¶ms.customer_id {
query = query.filter(po_dsl::customer_id.eq(customer_id.clone()));
}
if let Some(profile_id) = ¶ms.profile_id {
query = query.filter(po_dsl::profile_id.eq(profile_id.clone()));
}
query = match params.starting_at {
Some(starting_at) => query.filter(po_dsl::created_at.ge(starting_at)),
None => query,
};
query = match params.ending_at {
Some(ending_at) => query.filter(po_dsl::created_at.le(ending_at)),
None => query,
};
query = match ¶ms.currency {
Some(currency) => {
query.filter(po_dsl::destination_currency.eq_any(currency.clone()))
}
None => query,
};
query = match ¶ms.status {
Some(status) => query.filter(po_dsl::status.eq_any(status.clone())),
None => query,
};
query
}
};
logger::debug!(filter = %diesel::debug_query::<diesel::pg::Pg,_>(&query).to_string());
db_metrics::track_database_call::<<DieselPayouts as HasTable>::Table, _, _>(
query.get_results_async::<String>(conn),
db_metrics::DatabaseOperation::Filter,
)
.await
.map_err(|er| {
StorageError::DatabaseError(
error_stack::report!(diesel_models::errors::DatabaseError::from(er))
.attach_printable("Error filtering payout records"),
)
})?
.into_iter()
.map(|s| {
common_utils::id_type::PayoutId::try_from(std::borrow::Cow::Owned(s))
.change_context(StorageError::DeserializationFailed)
.attach_printable("Failed to deserialize PayoutId from database string")
})
.collect::<error_stack::Result<Vec<_>, _>>()
}
#[cfg(all(feature = "olap", feature = "v2"))]
#[instrument(skip_all)]
async fn filter_active_payout_ids_by_constraints(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_constraints: &PayoutFetchConstraints,
) -> error_stack::Result<Vec<common_utils::id_type::PayoutId>, StorageError> {
todo!()
}
}
impl DataModelExt for Payouts {
type StorageModel = DieselPayouts;
fn to_storage_model(self) -> Self::StorageModel {
DieselPayouts {
payout_id: self.payout_id,
merchant_id: self.merchant_id,
customer_id: self.customer_id,
address_id: self.address_id,
payout_type: self.payout_type,
payout_method_id: self.payout_method_id,
amount: self.amount,
destination_currency: self.destination_currency,
source_currency: self.source_currency,
description: self.description,
recurring: self.recurring,
auto_fulfill: self.auto_fulfill,
return_url: self.return_url,
entity_type: self.entity_type,
metadata: self.metadata,
created_at: self.created_at,
last_modified_at: self.last_modified_at,
profile_id: self.profile_id,
status: self.status,
attempt_count: self.attempt_count,
confirm: self.confirm,
payout_link_id: self.payout_link_id,
client_secret: self.client_secret,
priority: self.priority,
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
Self {
payout_id: storage_model.payout_id,
merchant_id: storage_model.merchant_id,
customer_id: storage_model.customer_id,
address_id: storage_model.address_id,
payout_type: storage_model.payout_type,
payout_method_id: storage_model.payout_method_id,
amount: storage_model.amount,
destination_currency: storage_model.destination_currency,
source_currency: storage_model.source_currency,
description: storage_model.description,
recurring: storage_model.recurring,
auto_fulfill: storage_model.auto_fulfill,
return_url: storage_model.return_url,
entity_type: storage_model.entity_type,
metadata: storage_model.metadata,
created_at: storage_model.created_at,
last_modified_at: storage_model.last_modified_at,
profile_id: storage_model.profile_id,
status: storage_model.status,
attempt_count: storage_model.attempt_count,
confirm: storage_model.confirm,
payout_link_id: storage_model.payout_link_id,
client_secret: storage_model.client_secret,
priority: storage_model.priority,
}
}
}
impl DataModelExt for PayoutsNew {
type StorageModel = DieselPayoutsNew;
fn to_storage_model(self) -> Self::StorageModel {
DieselPayoutsNew {
payout_id: self.payout_id,
merchant_id: self.merchant_id,
customer_id: self.customer_id,
address_id: self.address_id,
payout_type: self.payout_type,
payout_method_id: self.payout_method_id,
amount: self.amount,
destination_currency: self.destination_currency,
source_currency: self.source_currency,
description: self.description,
recurring: self.recurring,
auto_fulfill: self.auto_fulfill,
return_url: self.return_url,
entity_type: self.entity_type,
metadata: self.metadata,
created_at: self.created_at,
last_modified_at: self.last_modified_at,
profile_id: self.profile_id,
status: self.status,
attempt_count: self.attempt_count,
confirm: self.confirm,
payout_link_id: self.payout_link_id,
client_secret: self.client_secret,
priority: self.priority,
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
Self {
payout_id: storage_model.payout_id,
merchant_id: storage_model.merchant_id,
customer_id: storage_model.customer_id,
address_id: storage_model.address_id,
payout_type: storage_model.payout_type,
payout_method_id: storage_model.payout_method_id,
amount: storage_model.amount,
destination_currency: storage_model.destination_currency,
source_currency: storage_model.source_currency,
description: storage_model.description,
recurring: storage_model.recurring,
auto_fulfill: storage_model.auto_fulfill,
return_url: storage_model.return_url,
entity_type: storage_model.entity_type,
metadata: storage_model.metadata,
created_at: storage_model.created_at,
last_modified_at: storage_model.last_modified_at,
profile_id: storage_model.profile_id,
status: storage_model.status,
attempt_count: storage_model.attempt_count,
confirm: storage_model.confirm,
payout_link_id: storage_model.payout_link_id,
client_secret: storage_model.client_secret,
priority: storage_model.priority,
}
}
}
impl DataModelExt for PayoutsUpdate {
type StorageModel = DieselPayoutsUpdate;
fn to_storage_model(self) -> Self::StorageModel {
match self {
Self::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,
} => DieselPayoutsUpdate::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::PayoutMethodIdUpdate { payout_method_id } => {
DieselPayoutsUpdate::PayoutMethodIdUpdate { payout_method_id }
}
Self::RecurringUpdate { recurring } => {
DieselPayoutsUpdate::RecurringUpdate { recurring }
}
Self::AttemptCountUpdate { attempt_count } => {
DieselPayoutsUpdate::AttemptCountUpdate { attempt_count }
}
Self::StatusUpdate { status } => DieselPayoutsUpdate::StatusUpdate { status },
}
}
#[allow(clippy::todo)]
fn from_storage_model(_storage_model: Self::StorageModel) -> Self {
todo!("Reverse map should no longer be needed")
}
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/payouts/payouts.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 8366
}
|
large_file_-6818407439050536976
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: storage_impl
File: crates/storage_impl/src/payouts/payout_attempt.rs
</path>
<file>
use std::str::FromStr;
use api_models::enums::PayoutConnectors;
use common_utils::{errors::CustomResult, ext_traits::Encode, fallback_reverse_lookup_not_found};
use diesel_models::{
enums::MerchantStorageScheme,
kv,
payout_attempt::{
PayoutAttempt as DieselPayoutAttempt, PayoutAttemptNew as DieselPayoutAttemptNew,
PayoutAttemptUpdate as DieselPayoutAttemptUpdate,
},
reverse_lookup::ReverseLookup,
ReverseLookupNew,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::payouts::{
payout_attempt::{
PayoutAttempt, PayoutAttemptInterface, PayoutAttemptNew, PayoutAttemptUpdate,
PayoutListFilters,
},
payouts::Payouts,
};
use redis_interface::HsetnxReply;
use router_env::{instrument, logger, tracing};
use crate::{
diesel_error_to_data_error, errors,
errors::RedisErrorExt,
kv_router_store::KVRouterStore,
lookup::ReverseLookupInterface,
redis::kv_store::{decide_storage_scheme, kv_wrapper, KvOperation, Op, PartitionKey},
utils::{self, pg_connection_read, pg_connection_write},
DataModelExt, DatabaseStore,
};
#[async_trait::async_trait]
impl<T: DatabaseStore> PayoutAttemptInterface for KVRouterStore<T> {
type Error = errors::StorageError;
#[instrument(skip_all)]
async fn insert_payout_attempt(
&self,
new_payout_attempt: PayoutAttemptNew,
payouts: &Payouts,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>(
self,
storage_scheme,
Op::Insert,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.insert_payout_attempt(new_payout_attempt, payouts, storage_scheme)
.await
}
MerchantStorageScheme::RedisKv => {
let merchant_id = new_payout_attempt.merchant_id.clone();
let payout_attempt_id = new_payout_attempt.payout_id.clone();
let key = PartitionKey::MerchantIdPayoutAttemptId {
merchant_id: &merchant_id,
payout_attempt_id: payout_attempt_id.get_string_repr(),
};
let key_str = key.to_string();
let created_attempt = PayoutAttempt {
payout_attempt_id: new_payout_attempt.payout_attempt_id.clone(),
payout_id: new_payout_attempt.payout_id.clone(),
additional_payout_method_data: new_payout_attempt
.additional_payout_method_data
.clone(),
customer_id: new_payout_attempt.customer_id.clone(),
merchant_id: new_payout_attempt.merchant_id.clone(),
address_id: new_payout_attempt.address_id.clone(),
connector: new_payout_attempt.connector.clone(),
connector_payout_id: new_payout_attempt.connector_payout_id.clone(),
payout_token: new_payout_attempt.payout_token.clone(),
status: new_payout_attempt.status,
is_eligible: new_payout_attempt.is_eligible,
error_message: new_payout_attempt.error_message.clone(),
error_code: new_payout_attempt.error_code.clone(),
business_country: new_payout_attempt.business_country,
business_label: new_payout_attempt.business_label.clone(),
created_at: new_payout_attempt.created_at,
last_modified_at: new_payout_attempt.last_modified_at,
profile_id: new_payout_attempt.profile_id.clone(),
merchant_connector_id: new_payout_attempt.merchant_connector_id.clone(),
routing_info: new_payout_attempt.routing_info.clone(),
unified_code: new_payout_attempt.unified_code.clone(),
unified_message: new_payout_attempt.unified_message.clone(),
merchant_order_reference_id: new_payout_attempt
.merchant_order_reference_id
.clone(),
payout_connector_metadata: new_payout_attempt.payout_connector_metadata.clone(),
};
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Insert {
insertable: Box::new(kv::Insertable::PayoutAttempt(
new_payout_attempt.to_storage_model(),
)),
},
};
// Reverse lookup for payout_attempt_id
let field = format!("poa_{}", created_attempt.payout_attempt_id);
let reverse_lookup = ReverseLookupNew {
lookup_id: format!(
"poa_{}_{}",
&created_attempt.merchant_id.get_string_repr(),
&created_attempt.payout_attempt_id,
),
pk_id: key_str.clone(),
sk_id: field.clone(),
source: "payout_attempt".to_string(),
updated_by: storage_scheme.to_string(),
};
self.insert_reverse_lookup(reverse_lookup, storage_scheme)
.await?;
match Box::pin(kv_wrapper::<DieselPayoutAttempt, _, _>(
self,
KvOperation::<DieselPayoutAttempt>::HSetNx(
&field,
&created_attempt.clone().to_storage_model(),
redis_entry,
),
key,
))
.await
.map_err(|err| err.to_redis_failed_response(&key_str))?
.try_into_hsetnx()
{
Ok(HsetnxReply::KeyNotSet) => Err(errors::StorageError::DuplicateValue {
entity: "payout attempt",
key: Some(key_str),
}
.into()),
Ok(HsetnxReply::KeySet) => Ok(created_attempt),
Err(error) => Err(error.change_context(errors::StorageError::KVError)),
}
}
}
}
#[instrument(skip_all)]
async fn update_payout_attempt(
&self,
this: &PayoutAttempt,
payout_update: PayoutAttemptUpdate,
payouts: &Payouts,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let key = PartitionKey::MerchantIdPayoutAttemptId {
merchant_id: &this.merchant_id,
payout_attempt_id: this.payout_id.get_string_repr(),
};
let field = format!("poa_{}", this.payout_attempt_id);
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>(
self,
storage_scheme,
Op::Update(key.clone(), &field, None),
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.update_payout_attempt(this, payout_update, payouts, storage_scheme)
.await
}
MerchantStorageScheme::RedisKv => {
let key_str = key.to_string();
let diesel_payout_update = payout_update.clone().to_storage_model();
let origin_diesel_payout = this.clone().to_storage_model();
let diesel_payout = diesel_payout_update
.clone()
.apply_changeset(origin_diesel_payout.clone());
// Check for database presence as well Maybe use a read replica here ?
let redis_value = diesel_payout
.encode_to_string_of_json()
.change_context(errors::StorageError::SerializationFailed)?;
let redis_entry = kv::TypedSql {
op: kv::DBOperation::Update {
updatable: Box::new(kv::Updateable::PayoutAttemptUpdate(
kv::PayoutAttemptUpdateMems {
orig: origin_diesel_payout,
update_data: diesel_payout_update,
},
)),
},
};
let updated_attempt = PayoutAttempt::from_storage_model(
payout_update
.to_storage_model()
.apply_changeset(this.clone().to_storage_model()),
);
let old_connector_payout_id = this.connector_payout_id.clone();
match (
old_connector_payout_id,
updated_attempt.connector_payout_id.clone(),
) {
(Some(old), Some(new)) if old != new => {
add_connector_payout_id_to_reverse_lookup(
self,
key_str.as_str(),
&this.merchant_id,
updated_attempt.payout_attempt_id.as_str(),
new.as_str(),
storage_scheme,
)
.await?;
}
(None, Some(new)) => {
add_connector_payout_id_to_reverse_lookup(
self,
key_str.as_str(),
&this.merchant_id,
updated_attempt.payout_attempt_id.as_str(),
new.as_str(),
storage_scheme,
)
.await?;
}
_ => {}
}
Box::pin(kv_wrapper::<(), _, _>(
self,
KvOperation::<DieselPayoutAttempt>::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(PayoutAttempt::from_storage_model(diesel_payout))
}
}
}
#[instrument(skip_all)]
async fn find_payout_attempt_by_merchant_id_payout_attempt_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payout_attempt_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let storage_scheme = Box::pin(decide_storage_scheme::<_, DieselPayoutAttempt>(
self,
storage_scheme,
Op::Find,
))
.await;
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_id,
payout_attempt_id,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let lookup_id =
format!("poa_{}_{payout_attempt_id}", merchant_id.get_string_repr());
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
self.router_store
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_id,
payout_attempt_id,
storage_scheme
)
.await
);
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
Box::pin(utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(
self,
KvOperation::<DieselPayoutAttempt>::HGet(&lookup.sk_id),
key,
))
.await?
.try_into_hget()
},
|| async {
self.router_store
.find_payout_attempt_by_merchant_id_payout_attempt_id(
merchant_id,
payout_attempt_id,
storage_scheme,
)
.await
},
))
.await
}
}
}
#[instrument(skip_all)]
async fn find_payout_attempt_by_merchant_id_connector_payout_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_payout_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
match storage_scheme {
MerchantStorageScheme::PostgresOnly => {
self.router_store
.find_payout_attempt_by_merchant_id_connector_payout_id(
merchant_id,
connector_payout_id,
storage_scheme,
)
.await
}
MerchantStorageScheme::RedisKv => {
let lookup_id = format!(
"po_conn_payout_{}_{connector_payout_id}",
merchant_id.get_string_repr()
);
let lookup = fallback_reverse_lookup_not_found!(
self.get_lookup_by_lookup_id(&lookup_id, storage_scheme)
.await,
self.router_store
.find_payout_attempt_by_merchant_id_connector_payout_id(
merchant_id,
connector_payout_id,
storage_scheme,
)
.await
);
let key = PartitionKey::CombinationKey {
combination: &lookup.pk_id,
};
Box::pin(utils::try_redis_get_else_try_database_get(
async {
Box::pin(kv_wrapper(
self,
KvOperation::<DieselPayoutAttempt>::HGet(&lookup.sk_id),
key,
))
.await?
.try_into_hget()
},
|| async {
self.router_store
.find_payout_attempt_by_merchant_id_connector_payout_id(
merchant_id,
connector_payout_id,
storage_scheme,
)
.await
},
))
.await
}
}
}
#[instrument(skip_all)]
async fn get_filters_for_payouts(
&self,
payouts: &[Payouts],
merchant_id: &common_utils::id_type::MerchantId,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutListFilters, errors::StorageError> {
self.router_store
.get_filters_for_payouts(payouts, merchant_id, storage_scheme)
.await
}
#[instrument(skip_all)]
async fn find_payout_attempt_by_merchant_id_merchant_order_reference_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
merchant_order_reference_id: &str,
storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
self.router_store
.find_payout_attempt_by_merchant_id_merchant_order_reference_id(
merchant_id,
merchant_order_reference_id,
storage_scheme,
)
.await
}
}
#[async_trait::async_trait]
impl<T: DatabaseStore> PayoutAttemptInterface for crate::RouterStore<T> {
type Error = errors::StorageError;
#[instrument(skip_all)]
async fn insert_payout_attempt(
&self,
new: PayoutAttemptNew,
_payouts: &Payouts,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let conn = pg_connection_write(self).await?;
new.to_storage_model()
.insert(&conn)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(PayoutAttempt::from_storage_model)
}
#[instrument(skip_all)]
async fn update_payout_attempt(
&self,
this: &PayoutAttempt,
payout: PayoutAttemptUpdate,
_payouts: &Payouts,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let conn = pg_connection_write(self).await?;
this.clone()
.to_storage_model()
.update_with_attempt_id(&conn, payout.to_storage_model())
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(PayoutAttempt::from_storage_model)
}
#[instrument(skip_all)]
async fn find_payout_attempt_by_merchant_id_payout_attempt_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
payout_attempt_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
DieselPayoutAttempt::find_by_merchant_id_payout_attempt_id(
&conn,
merchant_id,
payout_attempt_id,
)
.await
.map(PayoutAttempt::from_storage_model)
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
#[instrument(skip_all)]
async fn find_payout_attempt_by_merchant_id_connector_payout_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
connector_payout_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
DieselPayoutAttempt::find_by_merchant_id_connector_payout_id(
&conn,
merchant_id,
connector_payout_id,
)
.await
.map(PayoutAttempt::from_storage_model)
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
#[instrument(skip_all)]
async fn get_filters_for_payouts(
&self,
payouts: &[Payouts],
merchant_id: &common_utils::id_type::MerchantId,
_storage_scheme: MerchantStorageScheme,
) -> CustomResult<PayoutListFilters, errors::StorageError> {
let conn = pg_connection_read(self).await?;
let payouts = payouts
.iter()
.cloned()
.map(|payouts| payouts.to_storage_model())
.collect::<Vec<diesel_models::Payouts>>();
DieselPayoutAttempt::get_filters_for_payouts(&conn, payouts.as_slice(), merchant_id)
.await
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
.map(
|(connector, currency, status, payout_method)| PayoutListFilters {
connector: connector
.iter()
.filter_map(|c| {
PayoutConnectors::from_str(c)
.map_err(|e| {
logger::error!(
"Failed to parse payout connector '{}' - {}",
c,
e
);
})
.ok()
})
.collect(),
currency,
status,
payout_method,
},
)
}
#[instrument(skip_all)]
async fn find_payout_attempt_by_merchant_id_merchant_order_reference_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
merchant_order_reference_id: &str,
_storage_scheme: MerchantStorageScheme,
) -> error_stack::Result<PayoutAttempt, errors::StorageError> {
let conn = pg_connection_read(self).await?;
DieselPayoutAttempt::find_by_merchant_id_merchant_order_reference_id(
&conn,
merchant_id,
merchant_order_reference_id,
)
.await
.map(PayoutAttempt::from_storage_model)
.map_err(|er| {
let new_err = diesel_error_to_data_error(*er.current_context());
er.change_context(new_err)
})
}
}
impl DataModelExt for PayoutAttempt {
type StorageModel = DieselPayoutAttempt;
fn to_storage_model(self) -> Self::StorageModel {
DieselPayoutAttempt {
payout_attempt_id: self.payout_attempt_id,
payout_id: self.payout_id,
customer_id: self.customer_id,
merchant_id: self.merchant_id,
address_id: self.address_id,
connector: self.connector,
connector_payout_id: self.connector_payout_id,
payout_token: self.payout_token,
status: self.status,
is_eligible: self.is_eligible,
error_message: self.error_message,
error_code: self.error_code,
business_country: self.business_country,
business_label: self.business_label,
created_at: self.created_at,
last_modified_at: self.last_modified_at,
profile_id: self.profile_id,
merchant_connector_id: self.merchant_connector_id,
routing_info: self.routing_info,
unified_code: self.unified_code,
unified_message: self.unified_message,
additional_payout_method_data: self.additional_payout_method_data,
merchant_order_reference_id: self.merchant_order_reference_id,
payout_connector_metadata: self.payout_connector_metadata,
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
Self {
payout_attempt_id: storage_model.payout_attempt_id,
payout_id: storage_model.payout_id,
customer_id: storage_model.customer_id,
merchant_id: storage_model.merchant_id,
address_id: storage_model.address_id,
connector: storage_model.connector,
connector_payout_id: storage_model.connector_payout_id,
payout_token: storage_model.payout_token,
status: storage_model.status,
is_eligible: storage_model.is_eligible,
error_message: storage_model.error_message,
error_code: storage_model.error_code,
business_country: storage_model.business_country,
business_label: storage_model.business_label,
created_at: storage_model.created_at,
last_modified_at: storage_model.last_modified_at,
profile_id: storage_model.profile_id,
merchant_connector_id: storage_model.merchant_connector_id,
routing_info: storage_model.routing_info,
unified_code: storage_model.unified_code,
unified_message: storage_model.unified_message,
additional_payout_method_data: storage_model.additional_payout_method_data,
merchant_order_reference_id: storage_model.merchant_order_reference_id,
payout_connector_metadata: storage_model.payout_connector_metadata,
}
}
}
impl DataModelExt for PayoutAttemptNew {
type StorageModel = DieselPayoutAttemptNew;
fn to_storage_model(self) -> Self::StorageModel {
DieselPayoutAttemptNew {
payout_attempt_id: self.payout_attempt_id,
payout_id: self.payout_id,
customer_id: self.customer_id,
merchant_id: self.merchant_id,
address_id: self.address_id,
connector: self.connector,
connector_payout_id: self.connector_payout_id,
payout_token: self.payout_token,
status: self.status,
is_eligible: self.is_eligible,
error_message: self.error_message,
error_code: self.error_code,
business_country: self.business_country,
business_label: self.business_label,
created_at: self.created_at,
last_modified_at: self.last_modified_at,
profile_id: self.profile_id,
merchant_connector_id: self.merchant_connector_id,
routing_info: self.routing_info,
unified_code: self.unified_code,
unified_message: self.unified_message,
additional_payout_method_data: self.additional_payout_method_data,
merchant_order_reference_id: self.merchant_order_reference_id,
payout_connector_metadata: self.payout_connector_metadata,
}
}
fn from_storage_model(storage_model: Self::StorageModel) -> Self {
Self {
payout_attempt_id: storage_model.payout_attempt_id,
payout_id: storage_model.payout_id,
customer_id: storage_model.customer_id,
merchant_id: storage_model.merchant_id,
address_id: storage_model.address_id,
connector: storage_model.connector,
connector_payout_id: storage_model.connector_payout_id,
payout_token: storage_model.payout_token,
status: storage_model.status,
is_eligible: storage_model.is_eligible,
error_message: storage_model.error_message,
error_code: storage_model.error_code,
business_country: storage_model.business_country,
business_label: storage_model.business_label,
created_at: storage_model.created_at,
last_modified_at: storage_model.last_modified_at,
profile_id: storage_model.profile_id,
merchant_connector_id: storage_model.merchant_connector_id,
routing_info: storage_model.routing_info,
unified_code: storage_model.unified_code,
unified_message: storage_model.unified_message,
additional_payout_method_data: storage_model.additional_payout_method_data,
merchant_order_reference_id: storage_model.merchant_order_reference_id,
payout_connector_metadata: storage_model.payout_connector_metadata,
}
}
}
impl DataModelExt for PayoutAttemptUpdate {
type StorageModel = DieselPayoutAttemptUpdate;
fn to_storage_model(self) -> Self::StorageModel {
match self {
Self::StatusUpdate {
connector_payout_id,
status,
error_message,
error_code,
is_eligible,
unified_code,
unified_message,
payout_connector_metadata,
} => DieselPayoutAttemptUpdate::StatusUpdate {
connector_payout_id,
status,
error_message,
error_code,
is_eligible,
unified_code,
unified_message,
payout_connector_metadata,
},
Self::PayoutTokenUpdate { payout_token } => {
DieselPayoutAttemptUpdate::PayoutTokenUpdate { payout_token }
}
Self::BusinessUpdate {
business_country,
business_label,
address_id,
customer_id,
} => DieselPayoutAttemptUpdate::BusinessUpdate {
business_country,
business_label,
address_id,
customer_id,
},
Self::UpdateRouting {
connector,
routing_info,
merchant_connector_id,
} => DieselPayoutAttemptUpdate::UpdateRouting {
connector,
routing_info,
merchant_connector_id,
},
Self::AdditionalPayoutMethodDataUpdate {
additional_payout_method_data,
} => DieselPayoutAttemptUpdate::AdditionalPayoutMethodDataUpdate {
additional_payout_method_data,
},
}
}
#[allow(clippy::todo)]
fn from_storage_model(_storage_model: Self::StorageModel) -> Self {
todo!("Reverse map should no longer be needed")
}
}
#[inline]
#[instrument(skip_all)]
async fn add_connector_payout_id_to_reverse_lookup<T: DatabaseStore>(
store: &KVRouterStore<T>,
key: &str,
merchant_id: &common_utils::id_type::MerchantId,
updated_attempt_attempt_id: &str,
connector_payout_id: &str,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<ReverseLookup, errors::StorageError> {
let field = format!("poa_{updated_attempt_attempt_id}");
let reverse_lookup_new = ReverseLookupNew {
lookup_id: format!(
"po_conn_payout_{}_{}",
merchant_id.get_string_repr(),
connector_payout_id
),
pk_id: key.to_owned(),
sk_id: field.clone(),
source: "payout_attempt".to_string(),
updated_by: storage_scheme.to_string(),
};
store
.insert_reverse_lookup(reverse_lookup_new, storage_scheme)
.await
}
</file>
|
{
"crate": "storage_impl",
"file": "crates/storage_impl/src/payouts/payout_attempt.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5649
}
|
large_file_-8575037894542803730
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_utils
File: crates/common_utils/src/ext_traits.rs
</path>
<file>
//! This module holds traits for extending functionalities for existing datatypes
//! & inbuilt datatypes.
use error_stack::ResultExt;
use masking::{ExposeInterface, PeekInterface, Secret, Strategy};
use quick_xml::de;
#[cfg(all(feature = "logs", feature = "async_ext"))]
use router_env::logger;
use serde::{Deserialize, Serialize};
use crate::{
crypto,
errors::{self, CustomResult},
fp_utils::when,
};
/// Encode interface
/// An interface for performing type conversions and serialization
pub trait Encode<'e>
where
Self: 'e + std::fmt::Debug,
{
// If needed get type information/custom error implementation.
///
/// Converting `Self` into an intermediate representation `<P>`
/// and then performing encoding operation using the `Serialize` trait from `serde`
/// Specifically to convert into json, by using `serde_json`
fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize;
/// Converting `Self` into an intermediate representation `<P>`
/// and then performing encoding operation using the `Serialize` trait from `serde`
/// Specifically, to convert into urlencoded, by using `serde_urlencoded`
fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize;
/// Functionality, for specifically encoding `Self` into `String`
/// after serialization by using `serde::Serialize`
fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `String`
/// after serialization by using `serde::Serialize`
/// specifically, to convert into JSON `String`.
fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `String`
/// after serialization by using `serde::Serialize`
/// specifically, to convert into XML `String`.
fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `serde_json::Value`
/// after serialization by using `serde::Serialize`
fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError>
where
Self: Serialize;
/// Functionality, for specifically encoding `Self` into `Vec<u8>`
/// after serialization by using `serde::Serialize`
fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError>
where
Self: Serialize;
}
impl<'e, A> Encode<'e> for A
where
Self: 'e + std::fmt::Debug,
{
fn convert_and_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize,
{
serde_json::to_string(
&P::try_from(self).change_context(errors::ParsingError::UnknownError)?,
)
.change_context(errors::ParsingError::EncodeError("string"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn convert_and_url_encode<P>(&'e self) -> CustomResult<String, errors::ParsingError>
where
P: TryFrom<&'e Self> + Serialize,
Result<P, <P as TryFrom<&'e Self>>::Error>: ResultExt,
<Result<P, <P as TryFrom<&'e Self>>::Error> as ResultExt>::Ok: Serialize,
{
serde_urlencoded::to_string(
&P::try_from(self).change_context(errors::ParsingError::UnknownError)?,
)
.change_context(errors::ParsingError::EncodeError("url-encoded"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
// Check without two functions can we combine this
fn url_encode(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize,
{
serde_urlencoded::to_string(self)
.change_context(errors::ParsingError::EncodeError("url-encoded"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn encode_to_string_of_json(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize,
{
serde_json::to_string(self)
.change_context(errors::ParsingError::EncodeError("json"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn encode_to_string_of_xml(&'e self) -> CustomResult<String, errors::ParsingError>
where
Self: Serialize,
{
quick_xml::se::to_string(self)
.change_context(errors::ParsingError::EncodeError("xml"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a request"))
}
fn encode_to_value(&'e self) -> CustomResult<serde_json::Value, errors::ParsingError>
where
Self: Serialize,
{
serde_json::to_value(self)
.change_context(errors::ParsingError::EncodeError("json-value"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a value"))
}
fn encode_to_vec(&'e self) -> CustomResult<Vec<u8>, errors::ParsingError>
where
Self: Serialize,
{
serde_json::to_vec(self)
.change_context(errors::ParsingError::EncodeError("byte-vec"))
.attach_printable_lazy(|| format!("Unable to convert {self:?} to a value"))
}
}
/// Extending functionalities of `bytes::Bytes`
pub trait BytesExt {
/// Convert `bytes::Bytes` into type `<T>` using `serde::Deserialize`
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>;
}
impl BytesExt for bytes::Bytes {
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>,
{
use bytes::Buf;
serde_json::from_slice::<T>(self.chunk())
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| {
let variable_type = std::any::type_name::<T>();
let value = serde_json::from_slice::<serde_json::Value>(self)
.unwrap_or_else(|_| serde_json::Value::String(String::new()));
format!(
"Unable to parse {variable_type} from bytes {:?}",
Secret::<_, masking::JsonMaskStrategy>::new(value)
)
})
}
}
/// Extending functionalities of `[u8]` for performing parsing
pub trait ByteSliceExt {
/// Convert `[u8]` into type `<T>` by using `serde::Deserialize`
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>;
}
impl ByteSliceExt for [u8] {
#[track_caller]
fn parse_struct<'de, T>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>,
{
serde_json::from_slice(self)
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| {
let value = serde_json::from_slice::<serde_json::Value>(self)
.unwrap_or_else(|_| serde_json::Value::String(String::new()));
format!(
"Unable to parse {type_name} from &[u8] {:?}",
Secret::<_, masking::JsonMaskStrategy>::new(value)
)
})
}
}
/// Extending functionalities of `serde_json::Value` for performing parsing
pub trait ValueExt {
/// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize`
fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned;
}
impl ValueExt for serde_json::Value {
fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned,
{
serde_json::from_value::<T>(self.clone())
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| {
format!(
"Unable to parse {type_name} from serde_json::Value: {:?}",
// Required to prevent logging sensitive data in case of deserialization failure
Secret::<_, masking::JsonMaskStrategy>::new(self)
)
})
}
}
impl<MaskingStrategy> ValueExt for Secret<serde_json::Value, MaskingStrategy>
where
MaskingStrategy: Strategy<serde_json::Value>,
{
fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned,
{
self.expose().parse_value(type_name)
}
}
impl<E: ValueExt + Clone> ValueExt for crypto::Encryptable<E> {
fn parse_value<T>(self, type_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: serde::de::DeserializeOwned,
{
self.into_inner().parse_value(type_name)
}
}
/// Extending functionalities of `String` for performing parsing
pub trait StringExt<T> {
/// Convert `String` into type `<T>` (which being an `enum`)
fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: std::str::FromStr,
// Requirement for converting the `Err` variant of `FromStr` to `Report<Err>`
<T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static;
/// Convert `serde_json::Value` into type `<T>` by using `serde::Deserialize`
fn parse_struct<'de>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>;
}
impl<T> StringExt<T> for String {
fn parse_enum(self, enum_name: &'static str) -> CustomResult<T, errors::ParsingError>
where
T: std::str::FromStr,
<T as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
T::from_str(&self)
.change_context(errors::ParsingError::EnumParseFailure(enum_name))
.attach_printable_lazy(|| format!("Invalid enum variant {self:?} for enum {enum_name}"))
}
fn parse_struct<'de>(
&'de self,
type_name: &'static str,
) -> CustomResult<T, errors::ParsingError>
where
T: Deserialize<'de>,
{
serde_json::from_str::<T>(self)
.change_context(errors::ParsingError::StructParseFailure(type_name))
.attach_printable_lazy(|| {
format!(
"Unable to parse {type_name} from string {:?}",
Secret::<_, masking::JsonMaskStrategy>::new(serde_json::Value::String(
self.clone()
))
)
})
}
}
/// Extending functionalities of Wrapper types for idiomatic
#[cfg(feature = "async_ext")]
#[cfg_attr(feature = "async_ext", async_trait::async_trait)]
pub trait AsyncExt<A> {
/// Output type of the map function
type WrappedSelf<T>;
/// Extending map by allowing functions which are async
async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = B> + Send;
/// Extending the `and_then` by allowing functions which are async
async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send;
/// Extending `unwrap_or_else` to allow async fallback
async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = A> + Send;
/// Extending `or_else` to allow async fallback that returns Self::WrappedSelf<A>
async fn async_or_else<F, Fut>(self, func: F) -> Self::WrappedSelf<A>
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<A>> + Send;
}
#[cfg(feature = "async_ext")]
#[cfg_attr(feature = "async_ext", async_trait::async_trait)]
impl<A: Send, E: Send + std::fmt::Debug> AsyncExt<A> for Result<A, E> {
type WrappedSelf<T> = Result<T, E>;
async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send,
{
match self {
Ok(a) => func(a).await,
Err(err) => Err(err),
}
}
async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = B> + Send,
{
match self {
Ok(a) => Ok(func(a).await),
Err(err) => Err(err),
}
}
async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = A> + Send,
{
match self {
Ok(a) => a,
Err(_err) => {
#[cfg(feature = "logs")]
logger::error!("Error: {:?}", _err);
func().await
}
}
}
async fn async_or_else<F, Fut>(self, func: F) -> Self::WrappedSelf<A>
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<A>> + Send,
{
match self {
Ok(a) => Ok(a),
Err(_err) => {
#[cfg(feature = "logs")]
logger::error!("Error: {:?}", _err);
func().await
}
}
}
}
#[cfg(feature = "async_ext")]
#[cfg_attr(feature = "async_ext", async_trait::async_trait)]
impl<A: Send> AsyncExt<A> for Option<A> {
type WrappedSelf<T> = Option<T>;
async fn async_and_then<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<B>> + Send,
{
match self {
Some(a) => func(a).await,
None => None,
}
}
async fn async_map<F, B, Fut>(self, func: F) -> Self::WrappedSelf<B>
where
F: FnOnce(A) -> Fut + Send,
Fut: futures::Future<Output = B> + Send,
{
match self {
Some(a) => Some(func(a).await),
None => None,
}
}
async fn async_unwrap_or_else<F, Fut>(self, func: F) -> A
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = A> + Send,
{
match self {
Some(a) => a,
None => func().await,
}
}
async fn async_or_else<F, Fut>(self, func: F) -> Self::WrappedSelf<A>
where
F: FnOnce() -> Fut + Send,
Fut: futures::Future<Output = Self::WrappedSelf<A>> + Send,
{
match self {
Some(a) => Some(a),
None => func().await,
}
}
}
/// Extension trait for validating application configuration. This trait provides utilities to
/// check whether the value is either the default value or is empty.
pub trait ConfigExt {
/// Returns whether the value of `self` is the default value for `Self`.
fn is_default(&self) -> bool
where
Self: Default + PartialEq<Self>,
{
*self == Self::default()
}
/// Returns whether the value of `self` is empty after trimming whitespace on both left and
/// right ends.
fn is_empty_after_trim(&self) -> bool;
/// Returns whether the value of `self` is the default value for `Self` or empty after trimming
/// whitespace on both left and right ends.
fn is_default_or_empty(&self) -> bool
where
Self: Default + PartialEq<Self>,
{
self.is_default() || self.is_empty_after_trim()
}
}
impl ConfigExt for u32 {
fn is_empty_after_trim(&self) -> bool {
false
}
}
impl ConfigExt for String {
fn is_empty_after_trim(&self) -> bool {
self.trim().is_empty()
}
}
impl<T, U> ConfigExt for Secret<T, U>
where
T: ConfigExt + Default + PartialEq<T>,
U: Strategy<T>,
{
fn is_default(&self) -> bool
where
T: Default + PartialEq<T>,
{
*self.peek() == T::default()
}
fn is_empty_after_trim(&self) -> bool {
self.peek().is_empty_after_trim()
}
fn is_default_or_empty(&self) -> bool
where
T: Default + PartialEq<T>,
{
self.peek().is_default() || self.peek().is_empty_after_trim()
}
}
/// Extension trait for deserializing XML strings using `quick-xml` crate
pub trait XmlExt {
/// Deserialize an XML string into the specified type `<T>`.
fn parse_xml<T>(self) -> Result<T, de::DeError>
where
T: serde::de::DeserializeOwned;
}
impl XmlExt for &str {
fn parse_xml<T>(self) -> Result<T, de::DeError>
where
T: serde::de::DeserializeOwned,
{
de::from_str(self)
}
}
/// Extension trait for Option to validate missing fields
pub trait OptionExt<T> {
/// check if the current option is Some
fn check_value_present(
&self,
field_name: &'static str,
) -> CustomResult<(), errors::ValidationError>;
/// Throw missing required field error when the value is None
fn get_required_value(
self,
field_name: &'static str,
) -> CustomResult<T, errors::ValidationError>;
/// Try parsing the option as Enum
fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError>
where
T: AsRef<str>,
E: std::str::FromStr,
// Requirement for converting the `Err` variant of `FromStr` to `Report<Err>`
<E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static;
/// Try parsing the option as Type
fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError>
where
T: ValueExt,
U: serde::de::DeserializeOwned;
/// update option value
fn update_value(&mut self, value: Option<T>);
}
impl<T> OptionExt<T> for Option<T>
where
T: std::fmt::Debug,
{
#[track_caller]
fn check_value_present(
&self,
field_name: &'static str,
) -> CustomResult<(), errors::ValidationError> {
when(self.is_none(), || {
Err(errors::ValidationError::MissingRequiredField {
field_name: field_name.to_string(),
})
.attach_printable(format!("Missing required field {field_name} in {self:?}"))
})
}
// This will allow the error message that was generated in this function to point to the call site
#[track_caller]
fn get_required_value(
self,
field_name: &'static str,
) -> CustomResult<T, errors::ValidationError> {
match self {
Some(v) => Ok(v),
None => Err(errors::ValidationError::MissingRequiredField {
field_name: field_name.to_string(),
})
.attach_printable(format!("Missing required field {field_name} in {self:?}")),
}
}
#[track_caller]
fn parse_enum<E>(self, enum_name: &'static str) -> CustomResult<E, errors::ParsingError>
where
T: AsRef<str>,
E: std::str::FromStr,
<E as std::str::FromStr>::Err: std::error::Error + Send + Sync + 'static,
{
let value = self
.get_required_value(enum_name)
.change_context(errors::ParsingError::UnknownError)?;
E::from_str(value.as_ref())
.change_context(errors::ParsingError::UnknownError)
.attach_printable_lazy(|| format!("Invalid {{ {enum_name}: {value:?} }} "))
}
#[track_caller]
fn parse_value<U>(self, type_name: &'static str) -> CustomResult<U, errors::ParsingError>
where
T: ValueExt,
U: serde::de::DeserializeOwned,
{
let value = self
.get_required_value(type_name)
.change_context(errors::ParsingError::UnknownError)?;
value.parse_value(type_name)
}
fn update_value(&mut self, value: Self) {
if let Some(a) = value {
*self = Some(a)
}
}
}
</file>
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/ext_traits.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5151
}
|
large_file_-1486438238714084076
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_utils
File: crates/common_utils/src/consts.rs
</path>
<file>
//! Commonly used constants
/// Number of characters in a generated ID
pub const ID_LENGTH: usize = 20;
/// Characters to use for generating NanoID
pub(crate) const ALPHABETS: [char; 62] = [
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i',
'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B',
'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U',
'V', 'W', 'X', 'Y', 'Z',
];
/// TTL for token
pub const TOKEN_TTL: i64 = 900;
///an example of the frm_configs json
pub static FRM_CONFIGS_EG: &str = r#"
[{"gateway":"stripe","payment_methods":[{"payment_method":"card","payment_method_types":[{"payment_method_type":"credit","card_networks":["Visa"],"flow":"pre","action":"cancel_txn"},{"payment_method_type":"debit","card_networks":["Visa"],"flow":"pre"}]}]}]
"#;
/// Maximum limit for payments list get api
pub const PAYMENTS_LIST_MAX_LIMIT_V1: u32 = 100;
/// Maximum limit for payments list post api with filters
pub const PAYMENTS_LIST_MAX_LIMIT_V2: u32 = 50;
/// Default limit for payments list API
pub fn default_payments_list_limit() -> u32 {
10
}
/// Average delay (in seconds) between account onboarding's API response and the changes to actually reflect at Stripe's end
pub const STRIPE_ACCOUNT_ONBOARDING_DELAY_IN_SECONDS: i64 = 15;
/// Maximum limit for payment link list get api
pub const PAYMENTS_LINK_LIST_LIMIT: u32 = 100;
/// Maximum limit for payouts list get api
pub const PAYOUTS_LIST_MAX_LIMIT_GET: u32 = 100;
/// Maximum limit for payouts list post api
pub const PAYOUTS_LIST_MAX_LIMIT_POST: u32 = 20;
/// Default limit for payouts list API
pub fn default_payouts_list_limit() -> u32 {
10
}
/// surcharge percentage maximum precision length
pub const SURCHARGE_PERCENTAGE_PRECISION_LENGTH: u8 = 2;
/// Header Key for application overhead of a request
pub const X_HS_LATENCY: &str = "x-hs-latency";
/// Redirect url for Prophetpay
pub const PROPHETPAY_REDIRECT_URL: &str = "https://ccm-thirdparty.cps.golf/hp/tokenize/";
/// Variable which store the card token for Prophetpay
pub const PROPHETPAY_TOKEN: &str = "cctoken";
/// Payment intent default client secret expiry (in seconds)
pub const DEFAULT_SESSION_EXPIRY: i64 = 15 * 60;
/// Payment intent fulfillment time (in seconds)
pub const DEFAULT_INTENT_FULFILLMENT_TIME: i64 = 15 * 60;
/// Payment order fulfillment time (in seconds)
pub const DEFAULT_ORDER_FULFILLMENT_TIME: i64 = 15 * 60;
/// Default ttl for Extended card info in redis (in seconds)
pub const DEFAULT_TTL_FOR_EXTENDED_CARD_INFO: u16 = 15 * 60;
/// Max ttl for Extended card info in redis (in seconds)
pub const MAX_TTL_FOR_EXTENDED_CARD_INFO: u16 = 60 * 60 * 2;
/// Default tenant to be used when multitenancy is disabled
pub const DEFAULT_TENANT: &str = "public";
/// Default tenant to be used when multitenancy is disabled
pub const TENANT_HEADER: &str = "x-tenant-id";
/// Max Length for MerchantReferenceId
pub const MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 64;
/// Maximum length allowed for a global id
pub const MIN_GLOBAL_ID_LENGTH: u8 = 32;
/// Minimum length required for a global id
pub const MAX_GLOBAL_ID_LENGTH: u8 = 64;
/// Minimum allowed length for MerchantReferenceId
pub const MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH: u8 = 1;
/// Length of a cell identifier in a distributed system
pub const CELL_IDENTIFIER_LENGTH: u8 = 5;
/// General purpose base64 engine
pub const BASE64_ENGINE: base64::engine::GeneralPurpose = base64::engine::general_purpose::STANDARD;
/// URL Safe base64 engine
pub const BASE64_ENGINE_URL_SAFE: base64::engine::GeneralPurpose =
base64::engine::general_purpose::URL_SAFE;
/// URL Safe base64 engine without padding
pub const BASE64_ENGINE_URL_SAFE_NO_PAD: base64::engine::GeneralPurpose =
base64::engine::general_purpose::URL_SAFE_NO_PAD;
/// Regex for matching a domain
/// Eg -
/// http://www.example.com
/// https://www.example.com
/// www.example.com
/// example.io
pub const STRICT_DOMAIN_REGEX: &str = r"^(https?://)?(([A-Za-z0-9][-A-Za-z0-9]\.)*[A-Za-z0-9][-A-Za-z0-9]*|(\d{1,3}\.){3}\d{1,3})+(:[0-9]{2,4})?$";
/// Regex for matching a wildcard domain
/// Eg -
/// *.example.com
/// *.subdomain.domain.com
/// *://example.com
/// *example.com
pub const WILDCARD_DOMAIN_REGEX: &str = r"^((\*|https?)?://)?((\*\.|[A-Za-z0-9][-A-Za-z0-9]*\.)*[A-Za-z0-9][-A-Za-z0-9]*|((\d{1,3}|\*)\.){3}(\d{1,3}|\*)|\*)(:\*|:[0-9]{2,4})?(/\*)?$";
/// Maximum allowed length for MerchantName
pub const MAX_ALLOWED_MERCHANT_NAME_LENGTH: usize = 64;
/// Default locale
pub const DEFAULT_LOCALE: &str = "en";
/// Role ID for Tenant Admin
pub const ROLE_ID_TENANT_ADMIN: &str = "tenant_admin";
/// Role ID for Org Admin
pub const ROLE_ID_ORGANIZATION_ADMIN: &str = "org_admin";
/// Role ID for Internal View Only
pub const ROLE_ID_INTERNAL_VIEW_ONLY_USER: &str = "internal_view_only";
/// Role ID for Internal Admin
pub const ROLE_ID_INTERNAL_ADMIN: &str = "internal_admin";
/// Role ID for Internal Demo
pub const ROLE_ID_INTERNAL_DEMO: &str = "internal_demo";
/// Max length allowed for Description
pub const MAX_DESCRIPTION_LENGTH: u16 = 255;
/// Max length allowed for Statement Descriptor
pub const MAX_STATEMENT_DESCRIPTOR_LENGTH: u16 = 22;
/// Payout flow identifier used for performing GSM operations
pub const PAYOUT_FLOW_STR: &str = "payout_flow";
/// length of the publishable key
pub const PUBLISHABLE_KEY_LENGTH: u16 = 39;
/// The number of bytes allocated for the hashed connector transaction ID.
/// Total number of characters equals CONNECTOR_TRANSACTION_ID_HASH_BYTES times 2.
pub const CONNECTOR_TRANSACTION_ID_HASH_BYTES: usize = 25;
/// Apple Pay validation url
pub const APPLEPAY_VALIDATION_URL: &str =
"https://apple-pay-gateway-cert.apple.com/paymentservices/startSession";
/// Request ID
pub const X_REQUEST_ID: &str = "x-request-id";
/// Flow name
pub const X_FLOW_NAME: &str = "x-flow";
/// Connector name
pub const X_CONNECTOR_NAME: &str = "x-connector";
/// Unified Connector Service Mode
pub const X_UNIFIED_CONNECTOR_SERVICE_MODE: &str = "x-shadow-mode";
/// Chat Session ID
pub const X_CHAT_SESSION_ID: &str = "x-chat-session-id";
/// Merchant ID Header
pub const X_MERCHANT_ID: &str = "x-merchant-id";
/// Default Tenant ID for the `Global` tenant
pub const DEFAULT_GLOBAL_TENANT_ID: &str = "global";
/// Default status of Card IP Blocking
pub const DEFAULT_CARD_IP_BLOCKING_STATUS: bool = false;
/// Default Threshold for Card IP Blocking
pub const DEFAULT_CARD_IP_BLOCKING_THRESHOLD: i32 = 3;
/// Default status of Guest User Card Blocking
pub const DEFAULT_GUEST_USER_CARD_BLOCKING_STATUS: bool = false;
/// Default Threshold for Card Blocking for Guest Users
pub const DEFAULT_GUEST_USER_CARD_BLOCKING_THRESHOLD: i32 = 10;
/// Default status of Customer ID Blocking
pub const DEFAULT_CUSTOMER_ID_BLOCKING_STATUS: bool = false;
/// Default Threshold for Customer ID Blocking
pub const DEFAULT_CUSTOMER_ID_BLOCKING_THRESHOLD: i32 = 5;
/// Default Card Testing Guard Redis Expiry in seconds
pub const DEFAULT_CARD_TESTING_GUARD_EXPIRY_IN_SECS: i32 = 3600;
/// SOAP 1.1 Envelope Namespace
pub const SOAP_ENV_NAMESPACE: &str = "http://schemas.xmlsoap.org/soap/envelope/";
#[cfg(all(feature = "v2", feature = "tokenization_v2"))]
/// Length of generated tokens
pub const TOKEN_LENGTH: usize = 32;
/// The tag name used for identifying the host in metrics.
pub const METRICS_HOST_TAG_NAME: &str = "host";
/// API client request timeout (in seconds)
pub const REQUEST_TIME_OUT: u64 = 30;
/// API client request timeout for ai service (in seconds)
pub const REQUEST_TIME_OUT_FOR_AI_SERVICE: u64 = 120;
/// Default limit for list operations (can be used across different entities)
pub const DEFAULT_LIST_LIMIT: i64 = 100;
/// Default offset for list operations (can be used across different entities)
pub const DEFAULT_LIST_OFFSET: i64 = 0;
</file>
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/consts.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2268
}
|
large_file_4415067210030871193
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_utils
File: crates/common_utils/src/types.rs
</path>
<file>
//! 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;
}
</file>
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/types.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 11041
}
|
large_file_1453433217514567650
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_utils
File: crates/common_utils/src/lib.rs
</path>
<file>
#![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;
</file>
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/lib.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3264
}
|
large_file_2009598790665570821
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_utils
File: crates/common_utils/src/new_type.rs
</path>
<file>
//! 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());
}
}
</file>
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/new_type.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2798
}
|
large_file_8300712959674680810
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_utils
File: crates/common_utils/src/validation.rs
</path>
<file>
//! 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("abc@example.com");
assert!(result.is_ok());
let result = validate_email("abc+123@example.com");
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"));
}
}
</file>
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/validation.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2336
}
|
large_file_-1934856490260211716
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_utils
File: crates/common_utils/src/pii.rs
</path>
<file>
//! 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("example@test.com".to_string());
assert_eq!("*******@test.com", format!("{secret:?}"));
let secret: Secret<String, EmailStrategy> = Secret::new("username@gmail.com".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("example@abc.com");
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:?}"));
}
}
</file>
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/pii.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3610
}
|
large_file_6022578928813386767
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_utils
File: crates/common_utils/src/id_type.rs
</path>
<file>
//! 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)
))
);
}
}
</file>
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/id_type.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2791
}
|
large_file_1456356452553274755
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_utils
File: crates/common_utils/src/macros.rs
</path>
<file>
//! Utility macros
#[allow(missing_docs)]
#[macro_export]
macro_rules! newtype_impl {
($is_pub:vis, $name:ident, $ty_path:path) => {
impl core::ops::Deref for $name {
type Target = $ty_path;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl core::ops::DerefMut for $name {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl From<$ty_path> for $name {
fn from(ty: $ty_path) -> Self {
Self(ty)
}
}
impl $name {
pub fn into_inner(self) -> $ty_path {
self.0
}
}
};
}
#[allow(missing_docs)]
#[macro_export]
macro_rules! newtype {
($is_pub:vis $name:ident = $ty_path:path) => {
$is_pub struct $name(pub $ty_path);
$crate::newtype_impl!($is_pub, $name, $ty_path);
};
($is_pub:vis $name:ident = $ty_path:path, derives = ($($trt:path),*)) => {
#[derive($($trt),*)]
$is_pub struct $name(pub $ty_path);
$crate::newtype_impl!($is_pub, $name, $ty_path);
};
}
/// Use this to ensure that the corresponding
/// openapi route has been implemented in the openapi crate
#[macro_export]
macro_rules! openapi_route {
($route_name: ident) => {{
#[cfg(feature = "openapi")]
use openapi::routes::$route_name as _;
$route_name
}};
}
#[allow(missing_docs)]
#[macro_export]
macro_rules! fallback_reverse_lookup_not_found {
($a:expr,$b:expr) => {
match $a {
Ok(res) => res,
Err(err) => {
router_env::logger::error!(reverse_lookup_fallback = ?err);
match err.current_context() {
errors::StorageError::ValueNotFound(_) => return $b,
errors::StorageError::DatabaseError(data_err) => {
match data_err.current_context() {
diesel_models::errors::DatabaseError::NotFound => return $b,
_ => return Err(err)
}
}
_=> return Err(err)
}
}
};
};
}
/// Collects names of all optional fields that are `None`.
/// This is typically useful for constructing error messages including a list of all missing fields.
#[macro_export]
macro_rules! collect_missing_value_keys {
[$(($key:literal, $option:expr)),+] => {
{
let mut keys: Vec<&'static str> = Vec::new();
$(
if $option.is_none() {
keys.push($key);
}
)*
keys
}
};
}
/// Implements the `ToSql` and `FromSql` traits on a type to allow it to be serialized/deserialized
/// to/from JSON data in the database.
#[macro_export]
macro_rules! impl_to_sql_from_sql_json {
($type:ty, $diesel_type:ty) => {
#[allow(unused_qualifications)]
impl diesel::serialize::ToSql<$diesel_type, diesel::pg::Pg> for $type {
fn to_sql<'b>(
&'b self,
out: &mut diesel::serialize::Output<'b, '_, diesel::pg::Pg>,
) -> diesel::serialize::Result {
let value = serde_json::to_value(self)?;
// 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 diesel::serialize::ToSql<
$diesel_type,
diesel::pg::Pg,
>>::to_sql(&value, &mut out.reborrow())
}
}
#[allow(unused_qualifications)]
impl diesel::deserialize::FromSql<$diesel_type, diesel::pg::Pg> for $type {
fn from_sql(
bytes: <diesel::pg::Pg as diesel::backend::Backend>::RawValue<'_>,
) -> diesel::deserialize::Result<Self> {
let value = <serde_json::Value as diesel::deserialize::FromSql<
$diesel_type,
diesel::pg::Pg,
>>::from_sql(bytes)?;
Ok(serde_json::from_value(value)?)
}
}
};
($type: ty) => {
$crate::impl_to_sql_from_sql_json!($type, diesel::sql_types::Json);
$crate::impl_to_sql_from_sql_json!($type, diesel::sql_types::Jsonb);
};
}
mod id_type {
/// Defines an ID type.
#[macro_export]
macro_rules! id_type {
($type:ident, $doc:literal, $diesel_type:ty, $max_length:expr, $min_length:expr) => {
#[doc = $doc]
#[derive(
Clone,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
diesel::expression::AsExpression,
utoipa::ToSchema,
)]
#[diesel(sql_type = $diesel_type)]
#[schema(value_type = String)]
pub struct $type($crate::id_type::LengthId<$max_length, $min_length>);
};
($type:ident, $doc:literal) => {
$crate::id_type!(
$type,
$doc,
diesel::sql_types::Text,
{ $crate::consts::MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH },
{ $crate::consts::MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH }
);
};
}
/// Defines a Global Id type
#[cfg(feature = "v2")]
#[macro_export]
macro_rules! global_id_type {
($type:ident, $doc:literal) => {
#[doc = $doc]
#[derive(
Debug,
Clone,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
diesel::expression::AsExpression,
)]
#[diesel(sql_type = diesel::sql_types::Text)]
pub struct $type($crate::id_type::global_id::GlobalId);
};
}
/// Implements common methods on the specified ID type.
#[macro_export]
macro_rules! impl_id_type_methods {
($type:ty, $field_name:literal) => {
impl $type {
/// Get the string representation of the ID type.
pub fn get_string_repr(&self) -> &str {
&self.0 .0 .0
}
}
};
}
/// Implements the `Debug` trait on the specified ID type.
#[macro_export]
macro_rules! impl_debug_id_type {
($type:ty) => {
impl core::fmt::Debug for $type {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.debug_tuple(stringify!($type))
.field(&self.0 .0 .0)
.finish()
}
}
};
}
/// Implements the `TryFrom<Cow<'static, str>>` trait on the specified ID type.
#[macro_export]
macro_rules! impl_try_from_cow_str_id_type {
($type:ty, $field_name:literal) => {
impl TryFrom<std::borrow::Cow<'static, str>> for $type {
type Error = error_stack::Report<$crate::errors::ValidationError>;
fn try_from(value: std::borrow::Cow<'static, str>) -> Result<Self, Self::Error> {
use error_stack::ResultExt;
let merchant_ref_id = $crate::id_type::LengthId::from(value).change_context(
$crate::errors::ValidationError::IncorrectValueProvided {
field_name: $field_name,
},
)?;
Ok(Self(merchant_ref_id))
}
}
};
}
/// Implements the `Default` trait on the specified ID type.
#[macro_export]
macro_rules! impl_default_id_type {
($type:ty, $prefix:literal) => {
impl Default for $type {
fn default() -> Self {
Self($crate::generate_ref_id_with_default_length($prefix))
}
}
};
}
/// Implements the `GenerateId` trait on the specified ID type.
#[macro_export]
macro_rules! impl_generate_id_id_type {
($type:ty, $prefix:literal) => {
impl $crate::id_type::GenerateId for $type {
fn generate() -> Self {
Self($crate::generate_ref_id_with_default_length($prefix))
}
}
};
}
/// Implements the `SerializableSecret` trait on the specified ID type.
#[macro_export]
macro_rules! impl_serializable_secret_id_type {
($type:ty) => {
impl masking::SerializableSecret for $type {}
};
}
/// Implements the `ToSql` and `FromSql` traits on the specified ID type.
#[macro_export]
macro_rules! impl_to_sql_from_sql_id_type {
($type:ty, $diesel_type:ty, $max_length:expr, $min_length:expr) => {
impl<DB> diesel::serialize::ToSql<$diesel_type, DB> for $type
where
DB: diesel::backend::Backend,
$crate::id_type::LengthId<$max_length, $min_length>:
diesel::serialize::ToSql<$diesel_type, 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_type, DB> for $type
where
DB: diesel::backend::Backend,
$crate::id_type::LengthId<$max_length, $min_length>:
diesel::deserialize::FromSql<$diesel_type, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
$crate::id_type::LengthId::<$max_length, $min_length>::from_sql(value).map(Self)
}
}
};
($type:ty) => {
$crate::impl_to_sql_from_sql_id_type!(
$type,
diesel::sql_types::Text,
{ $crate::consts::MAX_ALLOWED_MERCHANT_REFERENCE_ID_LENGTH },
{ $crate::consts::MIN_REQUIRED_MERCHANT_REFERENCE_ID_LENGTH }
);
};
}
#[cfg(feature = "v2")]
/// Implements the `ToSql` and `FromSql` traits on the specified Global ID type.
#[macro_export]
macro_rules! impl_to_sql_from_sql_global_id_type {
($type:ty, $diesel_type:ty) => {
impl<DB> diesel::serialize::ToSql<$diesel_type, DB> for $type
where
DB: diesel::backend::Backend,
$crate::id_type::global_id::GlobalId: diesel::serialize::ToSql<$diesel_type, 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_type, DB> for $type
where
DB: diesel::backend::Backend,
$crate::id_type::global_id::GlobalId:
diesel::deserialize::FromSql<$diesel_type, DB>,
{
fn from_sql(value: DB::RawValue<'_>) -> diesel::deserialize::Result<Self> {
$crate::id_type::global_id::GlobalId::from_sql(value).map(Self)
}
}
};
($type:ty) => {
$crate::impl_to_sql_from_sql_global_id_type!($type, diesel::sql_types::Text);
};
}
/// Implements the `Queryable` trait on the specified ID type.
#[macro_export]
macro_rules! impl_queryable_id_type {
($type:ty, $diesel_type:ty) => {
impl<DB> diesel::Queryable<$diesel_type, DB> for $type
where
DB: diesel::backend::Backend,
Self: diesel::deserialize::FromSql<$diesel_type, DB>,
{
type Row = Self;
fn build(row: Self::Row) -> diesel::deserialize::Result<Self> {
Ok(row)
}
}
};
($type:ty) => {
$crate::impl_queryable_id_type!($type, diesel::sql_types::Text);
};
}
}
/// Create new generic list wrapper
#[macro_export]
macro_rules! create_list_wrapper {
(
$wrapper_name:ident,
$type_name: ty,
impl_functions: {
$($function_def: tt)*
}
) => {
#[derive(Clone, Debug)]
pub struct $wrapper_name(Vec<$type_name>);
impl $wrapper_name {
pub fn new(list: Vec<$type_name>) -> Self {
Self(list)
}
pub fn with_capacity(size: usize) -> Self {
Self(Vec::with_capacity(size))
}
$($function_def)*
}
impl std::ops::Deref for $wrapper_name {
type Target = Vec<$type_name>;
fn deref(&self) -> &<Self as std::ops::Deref>::Target {
&self.0
}
}
impl std::ops::DerefMut for $wrapper_name {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.0
}
}
impl IntoIterator for $wrapper_name {
type Item = $type_name;
type IntoIter = std::vec::IntoIter<$type_name>;
fn into_iter(self) -> Self::IntoIter {
self.0.into_iter()
}
}
impl<'a> IntoIterator for &'a $wrapper_name {
type Item = &'a $type_name;
type IntoIter = std::slice::Iter<'a, $type_name>;
fn into_iter(self) -> Self::IntoIter {
self.0.iter()
}
}
impl FromIterator<$type_name> for $wrapper_name {
fn from_iter<T: IntoIterator<Item = $type_name>>(iter: T) -> Self {
Self(iter.into_iter().collect())
}
}
};
}
/// Get the type name for a type
#[macro_export]
macro_rules! type_name {
($type:ty) => {
std::any::type_name::<$type>()
.rsplit("::")
.nth(1)
.unwrap_or_default();
};
}
/// **Note** Creates an enum wrapper that implements `FromStr`, `Display`, `Serialize`, and `Deserialize`
/// based on a specific string representation format: `"VariantName<delimiter>FieldValue"`.
/// It handles parsing errors by returning a dedicated `Invalid` variant.
/// *Note*: The macro adds `Invalid,` automatically.
///
/// # Use Case
///
/// This macro is designed for scenarios where you need an enum, with each variant
/// holding a single piece of associated data, to be easily convertible to and from
/// a simple string format. This is useful for cases where enum is serialized to key value pairs
///
/// It avoids more complex serialization structures (like JSON objects `{"VariantName": value}`)
/// in favor of a plain string representation.
///
/// # Input Enum Format and Constraints
///
/// To use this macro, the enum definition must adhere to the following structure:
///
/// 1. **Public Enum:** The enum must be declared as `pub enum EnumName { ... }`.
/// 2. **Struct Variants Only:** All variants must be struct variants (using `{}`).
/// 3. **Exactly One Field:** Each struct variant must contain *exactly one* named field.
/// * **Valid:** `VariantA { value: i32 }`
/// * **Invalid:** `VariantA(i32)` (tuple variant)
/// * **Invalid:** `VariantA` or `VariantA {}` (no field)
/// * **Invalid:** `VariantA { value: i32, other: bool }` (multiple fields)
/// 4. **Tag Delimiter:** The macro invocation must specify a `tag_delimiter` literal,
/// which is the character used to separate the variant name from the field data in
/// the string representation (e.g., `tag_delimiter = ":",`).
/// 5. **Field Type Requirements:** The type of the single field in each variant (`$field_ty`)
/// must implement:
/// * `core::str::FromStr`: To parse the field's data from the string part.
/// The `Err` type should ideally be convertible to a meaningful error, though the
/// macro currently uses a generic error message upon failure.
/// * `core::fmt::Display`: To convert the field's data into the string part.
/// * `serde::Serialize` and `serde::Deserialize<'de>`: Although the macro implements
/// custom `Serialize`/`Deserialize` for the *enum* using the string format, the field
/// type itself must satisfy these bounds if required elsewhere or by generic contexts.
/// The macro's implementations rely solely on `Display` and `FromStr` for the conversion.
/// 6. **Error Type:** This macro uses `core::convert::Infallible` as it never fails but gives
/// `Self::Invalid` variant.
///
/// # Serialization and Deserialization (`serde`)
///
/// When `serde` features are enabled and the necessary traits are derived or implemented,
/// this macro implements `Serialize` and `Deserialize` for the enum:
///
/// **Serialization:** An enum value like `MyEnum::VariantA { value: 123 }` (with `tag_delimiter = ":",`)
/// will be serialized into the string `"VariantA:123"`. If serializing to JSON, this results
/// in a JSON string: `"\"VariantA:123\""`.
/// **Deserialization:** The macro expects a string matching the format `"VariantName<delimiter>FieldValue"`.
/// It uses the enum's `FromStr` implementation internally. When deserializing from JSON, it
/// expects a JSON string containing the correctly formatted value (e.g., `"\"VariantA:123\""`).
///
/// # `Display` and `FromStr`
///
/// **`Display`:** Formats valid variants to `"VariantName<delimiter>FieldValue"` and catch-all cases to `"Invalid"`.
/// **`FromStr`:** Parses `"VariantName<delimiter>FieldValue"` to the variant, or returns `Self::Invalid`
/// if the input string is malformed or `"Invalid"`.
///
/// # Example
///
/// ```rust
/// use std::str::FromStr;
///
/// crate::impl_enum_str!(
/// tag_delimiter = ":",
/// #[derive(Debug, PartialEq, Clone)] // Add other derives as needed
/// pub enum Setting {
/// Timeout { duration_ms: u32 },
/// Username { name: String },
/// }
/// );
/// // Note: The macro adds `Invalid,` automatically.
///
/// fn main() {
/// // Display
/// let setting1 = Setting::Timeout { duration_ms: 5000 };
/// assert_eq!(setting1.to_string(), "Timeout:5000");
/// assert_eq!(Setting::Invalid.to_string(), "Invalid");
///
/// // FromStr (returns Self, not Result)
/// let parsed_setting: Setting = "Username:admin".parse().expect("Valid parse"); // parse() itself doesn't panic
/// assert_eq!(parsed_setting, Setting::Username { name: "admin".to_string() });
///
/// let invalid_format: Setting = "Timeout".parse().expect("Parse always returns Self");
/// assert_eq!(invalid_format, Setting::Invalid); // Malformed input yields Invalid
///
/// let bad_data: Setting = "Timeout:fast".parse().expect("Parse always returns Self");
/// assert_eq!(bad_data, Setting::Invalid); // Bad field data yields Invalid
///
/// let unknown_tag: Setting = "Unknown:abc".parse().expect("Parse always returns Self");
/// assert_eq!(unknown_tag, Setting::Invalid); // Unknown tag yields Invalid
///
/// let explicit_invalid: Setting = "Invalid".parse().expect("Parse always returns Self");
/// assert_eq!(explicit_invalid, Setting::Invalid); // "Invalid" string yields Invalid
///
/// // Serde (requires derive Serialize/Deserialize on Setting)
/// // let json_output = serde_json::to_string(&setting1).unwrap();
/// // assert_eq!(json_output, "\"Timeout:5000\"");
/// // let invalid_json_output = serde_json::to_string(&Setting::Invalid).unwrap();
/// // assert_eq!(invalid_json_output, "\"Invalid\"");
///
/// // let deserialized: Setting = serde_json::from_str("\"Username:guest\"").unwrap();
/// // assert_eq!(deserialized, Setting::Username { name: "guest".to_string() });
/// // let deserialized_invalid: Setting = serde_json::from_str("\"Invalid\"").unwrap();
/// // assert_eq!(deserialized_invalid, Setting::Invalid);
/// // let deserialized_malformed: Setting = serde_json::from_str("\"TimeoutFast\"").unwrap();
/// // assert_eq!(deserialized_malformed, Setting::Invalid); // Malformed -> Invalid
/// }
///
/// # // Mock macro definition for doctest purposes
/// # #[macro_export] macro_rules! impl_enum_str { ($($tt:tt)*) => { $($tt)* } }
/// ```
#[macro_export]
macro_rules! impl_enum_str {
(
tag_delimiter = $tag_delim:literal,
$(#[$enum_attr:meta])*
pub enum $enum_name:ident {
$(
$(#[$variant_attr:meta])*
$variant:ident {
$(#[$field_attr:meta])*
$field:ident : $field_ty:ty $(,)?
}
),* $(,)?
}
) => {
$(#[$enum_attr])*
pub enum $enum_name {
$(
$(#[$variant_attr])*
$variant {
$(#[$field_attr])*
$field : $field_ty
},
)*
/// Represents a parsing failure.
Invalid, // Automatically add the Invalid variant
}
// Implement FromStr - now returns Self, not Result
impl core::str::FromStr for $enum_name {
// No associated error type needed
type Err = core::convert::Infallible; // FromStr requires an Err type, use Infallible
fn from_str(s: &str) -> Result<Self, Self::Err> {
// Check for explicit "Invalid" string first
if s == "Invalid" {
return Ok(Self::Invalid);
}
let Some((tag, associated_data)) = s.split_once($tag_delim) else {
// Missing delimiter -> Invalid
return Ok(Self::Invalid);
};
let result = match tag {
$(
stringify!($variant) => {
// Try to parse the field data
match associated_data.parse::<$field_ty>() {
Ok(parsed_field) => {
// Success -> construct the variant
Self::$variant { $field: parsed_field }
},
Err(_) => {
// Field parse failure -> Invalid
Self::Invalid
}
}
}
),*
// Unknown tag -> Invalid
_ => Self::Invalid,
};
Ok(result) // Always Ok because failure modes return Self::Invalid
}
}
// Implement Serialize
impl ::serde::Serialize for $enum_name {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: ::serde::Serializer,
{
match self {
$(
Self::$variant { $field } => {
let s = format!("{}{}{}", stringify!($variant), $tag_delim, $field);
serializer.serialize_str(&s)
}
)*
// Handle Invalid variant
Self::Invalid => serializer.serialize_str("Invalid"),
}
}
}
// Implement Deserialize
impl<'de> ::serde::Deserialize<'de> for $enum_name {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: ::serde::Deserializer<'de>,
{
struct EnumVisitor;
impl<'de> ::serde::de::Visitor<'de> for EnumVisitor {
type Value = $enum_name;
fn expecting(&self, formatter: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
formatter.write_str(concat!("a string like VariantName", $tag_delim, "field_data or 'Invalid'"))
}
// Leverage the FromStr implementation which now returns Self::Invalid on failure
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E>
where
E: ::serde::de::Error,
{
// parse() now returns Result<Self, Infallible>
// We unwrap() the Ok because it's infallible.
Ok(value.parse::<$enum_name>().unwrap())
}
fn visit_string<E>(self, value: String) -> Result<Self::Value, E>
where
E: ::serde::de::Error,
{
Ok(value.parse::<$enum_name>().unwrap())
}
}
deserializer.deserialize_str(EnumVisitor)
}
}
// Implement Display
impl core::fmt::Display for $enum_name {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
$(
Self::$variant { $field } => {
write!(f, "{}{}{}", stringify!($variant), $tag_delim, $field)
}
)*
// Handle Invalid variant
Self::Invalid => write!(f, "Invalid"),
}
}
}
};
}
// --- Tests ---
#[cfg(test)]
mod tests {
#![allow(clippy::panic, clippy::expect_used)]
use serde_json::{json, Value as JsonValue};
use crate::impl_enum_str;
impl_enum_str!(
tag_delimiter = ":",
#[derive(Debug, PartialEq, Clone)]
pub enum TestEnum {
VariantA { value: i32 },
VariantB { text: String },
VariantC { id: u64 },
VariantJson { data: JsonValue },
} // Note: Invalid variant is added automatically by the macro
);
#[test]
fn test_enum_from_str_ok() {
// Success cases just parse directly
let parsed_a: TestEnum = "VariantA:42".parse().unwrap(); // Unwrapping Infallible is fine
assert_eq!(parsed_a, TestEnum::VariantA { value: 42 });
let parsed_b: TestEnum = "VariantB:hello world".parse().unwrap();
assert_eq!(
parsed_b,
TestEnum::VariantB {
text: "hello world".to_string()
}
);
let parsed_c: TestEnum = "VariantC:123456789012345".parse().unwrap();
assert_eq!(
parsed_c,
TestEnum::VariantC {
id: 123456789012345
}
);
let parsed_json: TestEnum = r#"VariantJson:{"ok":true}"#.parse().unwrap();
assert_eq!(
parsed_json,
TestEnum::VariantJson {
data: json!({"ok": true})
}
);
}
#[test]
fn test_enum_from_str_failures_yield_invalid() {
// Missing delimiter
let parsed: TestEnum = "VariantA".parse().unwrap();
assert_eq!(parsed, TestEnum::Invalid);
// Unknown tag
let parsed: TestEnum = "UnknownVariant:123".parse().unwrap();
assert_eq!(parsed, TestEnum::Invalid);
// Bad field data for i32
let parsed: TestEnum = "VariantA:not_a_number".parse().unwrap();
assert_eq!(parsed, TestEnum::Invalid);
// Bad field data for JsonValue
let parsed: TestEnum = r#"VariantJson:{"bad_json"#.parse().unwrap();
assert_eq!(parsed, TestEnum::Invalid);
// Empty field data for non-string (e.g., i32)
let parsed: TestEnum = "VariantA:".parse().unwrap();
assert_eq!(parsed, TestEnum::Invalid);
// Empty field data for string IS valid for String type
let parsed_str: TestEnum = "VariantB:".parse().unwrap();
assert_eq!(
parsed_str,
TestEnum::VariantB {
text: "".to_string()
}
);
// Parsing the literal "Invalid" string
let parsed_invalid_str: TestEnum = "Invalid".parse().unwrap();
assert_eq!(parsed_invalid_str, TestEnum::Invalid);
}
#[test]
fn test_enum_display_and_serialize() {
// Display valid
let value_a = TestEnum::VariantA { value: 99 };
assert_eq!(value_a.to_string(), "VariantA:99");
// Serialize valid
let json_a = serde_json::to_string(&value_a).expect("Serialize A failed");
assert_eq!(json_a, "\"VariantA:99\""); // Serializes to JSON string
// Display Invalid
let value_invalid = TestEnum::Invalid;
assert_eq!(value_invalid.to_string(), "Invalid");
// Serialize Invalid
let json_invalid = serde_json::to_string(&value_invalid).expect("Serialize Invalid failed");
assert_eq!(json_invalid, "\"Invalid\""); // Serializes to JSON string "Invalid"
}
#[test]
fn test_enum_deserialize() {
// Deserialize valid
let input_a = "\"VariantA:123\"";
let deserialized_a: TestEnum = serde_json::from_str(input_a).expect("Deserialize A failed");
assert_eq!(deserialized_a, TestEnum::VariantA { value: 123 });
// Deserialize explicit "Invalid"
let input_invalid = "\"Invalid\"";
let deserialized_invalid: TestEnum =
serde_json::from_str(input_invalid).expect("Deserialize Invalid failed");
assert_eq!(deserialized_invalid, TestEnum::Invalid);
// Deserialize malformed string (according to macro rules) -> Invalid
let input_malformed = "\"VariantA_no_delimiter\"";
let deserialized_malformed: TestEnum =
serde_json::from_str(input_malformed).expect("Deserialize malformed should succeed");
assert_eq!(deserialized_malformed, TestEnum::Invalid);
// Deserialize string with bad field data -> Invalid
let input_bad_data = "\"VariantA:not_a_number\"";
let deserialized_bad_data: TestEnum =
serde_json::from_str(input_bad_data).expect("Deserialize bad data should succeed");
assert_eq!(deserialized_bad_data, TestEnum::Invalid);
}
}
</file>
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/macros.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6911
}
|
large_file_-8715910267064204253
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_utils
File: crates/common_utils/src/payout_method_utils.rs
</path>
<file>
//! 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 = "john.doe@example.com")]
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 = "john.doe@example.com")]
pub email: Option<MaskedEmail>,
}
</file>
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/payout_method_utils.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2485
}
|
large_file_1033538781307573881
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_utils
File: crates/common_utils/src/link_utils.rs
</path>
<file>
//! 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}",
);
}
}
}
</file>
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/link_utils.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2896
}
|
large_file_-6592522915775595381
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_utils
File: crates/common_utils/src/crypto.rs
</path>
<file>
//! 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);
}
}
</file>
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/crypto.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 9391
}
|
large_file_-6834220937453983928
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_utils
File: crates/common_utils/src/custom_serde.rs
</path>
<file>
//! 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())
}
}
</file>
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/custom_serde.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2336
}
|
large_file_3911739533787865524
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_utils
File: crates/common_utils/src/types/keymanager.rs
</path>
<file>
#![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>;
}
</file>
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/types/keymanager.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3643
}
|
large_file_-390337418924628888
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: common_utils
File: crates/common_utils/src/id_type/global_id.rs
</path>
<file>
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);
}
}
</file>
|
{
"crate": "common_utils",
"file": "crates/common_utils/src/id_type/global_id.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2050
}
|
large_file_4438743729035496835
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/router_request_types.rs
</path>
<file>
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,
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_request_types.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 12021
}
|
large_file_241330586059685780
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/payment_methods.rs
</path>
<file>
#[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());
}
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/payment_methods.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 10893
}
|
large_file_462730681741214259
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/types.rs
</path>
<file>
pub use diesel_models::types::OrderDetailsWithAmount;
use crate::{
router_data::{AccessToken, AccessTokenAuthenticationResponse, RouterData},
router_data_v2::{self, RouterDataV2},
router_flow_types::{
mandate_revoke::MandateRevoke,
revenue_recovery::InvoiceRecordBack,
subscriptions::{
GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans,
SubscriptionCreate,
},
AccessTokenAuth, AccessTokenAuthentication, Authenticate, AuthenticationConfirmation,
Authorize, AuthorizeSessionToken, BillingConnectorInvoiceSync,
BillingConnectorPaymentsSync, CalculateTax, Capture, CompleteAuthorize,
CreateConnectorCustomer, CreateOrder, Execute, ExtendAuthorization, ExternalVaultProxy,
GiftCardBalanceCheck, IncrementalAuthorization, PSync, PaymentMethodToken,
PostAuthenticate, PostCaptureVoid, PostSessionTokens, PreAuthenticate, PreProcessing,
RSync, SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, VerifyWebhookSource, Void,
},
router_request_types::{
revenue_recovery::{
BillingConnectorInvoiceSyncRequest, BillingConnectorPaymentsSyncRequest,
InvoiceRecordBackRequest,
},
subscriptions::{
GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest,
GetSubscriptionPlansRequest, SubscriptionCreateRequest,
},
unified_authentication_service::{
UasAuthenticationRequestData, UasAuthenticationResponseData,
UasConfirmationRequestData, UasPostAuthenticationRequestData,
UasPreAuthenticationRequestData,
},
AccessTokenAuthenticationRequestData, AccessTokenRequestData, AuthorizeSessionTokenData,
CompleteAuthorizeData, ConnectorCustomerData, CreateOrderRequestData,
ExternalVaultProxyPaymentsData, GiftCardBalanceCheckRequestData, MandateRevokeRequestData,
PaymentMethodTokenizationData, PaymentsAuthenticateData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCancelPostCaptureData, PaymentsCaptureData,
PaymentsExtendAuthorizationData, PaymentsIncrementalAuthorizationData,
PaymentsPostAuthenticateData, PaymentsPostSessionTokensData, PaymentsPreAuthenticateData,
PaymentsPreProcessingData, PaymentsSessionData, PaymentsSyncData,
PaymentsTaxCalculationData, PaymentsUpdateMetadataData, RefundsData,
SdkPaymentsSessionUpdateData, SetupMandateRequestData, VaultRequestData,
VerifyWebhookSourceRequestData,
},
router_response_types::{
revenue_recovery::{
BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse,
InvoiceRecordBackResponse,
},
subscriptions::{
GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse,
GetSubscriptionPlansResponse, SubscriptionCreateResponse,
},
GiftCardBalanceCheckResponseData, MandateRevokeResponseData, PaymentsResponseData,
RefundsResponseData, TaxCalculationResponseData, VaultResponseData,
VerifyWebhookSourceResponseData,
},
};
#[cfg(feature = "payouts")]
pub use crate::{router_request_types::PayoutsData, router_response_types::PayoutsResponseData};
pub type PaymentsAuthorizeRouterData =
RouterData<Authorize, PaymentsAuthorizeData, PaymentsResponseData>;
pub type ExternalVaultProxyPaymentsRouterData =
RouterData<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>;
pub type PaymentsAuthorizeSessionTokenRouterData =
RouterData<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>;
pub type PaymentsPreProcessingRouterData =
RouterData<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>;
pub type PaymentsPreAuthenticateRouterData =
RouterData<PreAuthenticate, PaymentsPreAuthenticateData, PaymentsResponseData>;
pub type PaymentsAuthenticateRouterData =
RouterData<Authenticate, PaymentsAuthenticateData, PaymentsResponseData>;
pub type PaymentsPostAuthenticateRouterData =
RouterData<PostAuthenticate, PaymentsPostAuthenticateData, PaymentsResponseData>;
pub type PaymentsSyncRouterData = RouterData<PSync, PaymentsSyncData, PaymentsResponseData>;
pub type PaymentsCaptureRouterData = RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>;
pub type PaymentsCancelRouterData = RouterData<Void, PaymentsCancelData, PaymentsResponseData>;
pub type PaymentsCancelPostCaptureRouterData =
RouterData<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>;
pub type SetupMandateRouterData =
RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>;
pub type RefundsRouterData<F> = RouterData<F, RefundsData, RefundsResponseData>;
pub type RefundExecuteRouterData = RouterData<Execute, RefundsData, RefundsResponseData>;
pub type RefundSyncRouterData = RouterData<RSync, RefundsData, RefundsResponseData>;
pub type TokenizationRouterData =
RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>;
pub type ConnectorCustomerRouterData =
RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>;
pub type PaymentsCompleteAuthorizeRouterData =
RouterData<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>;
pub type PaymentsTaxCalculationRouterData =
RouterData<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>;
pub type AccessTokenAuthenticationRouterData = RouterData<
AccessTokenAuthentication,
AccessTokenAuthenticationRequestData,
AccessTokenAuthenticationResponse,
>;
pub type PaymentsGiftCardBalanceCheckRouterData = RouterData<
GiftCardBalanceCheck,
GiftCardBalanceCheckRequestData,
GiftCardBalanceCheckResponseData,
>;
pub type RefreshTokenRouterData = RouterData<AccessTokenAuth, AccessTokenRequestData, AccessToken>;
pub type PaymentsPostSessionTokensRouterData =
RouterData<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>;
pub type PaymentsSessionRouterData = RouterData<Session, PaymentsSessionData, PaymentsResponseData>;
pub type PaymentsUpdateMetadataRouterData =
RouterData<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>;
pub type CreateOrderRouterData =
RouterData<CreateOrder, CreateOrderRequestData, PaymentsResponseData>;
pub type UasPostAuthenticationRouterData =
RouterData<PostAuthenticate, UasPostAuthenticationRequestData, UasAuthenticationResponseData>;
pub type UasPreAuthenticationRouterData =
RouterData<PreAuthenticate, UasPreAuthenticationRequestData, UasAuthenticationResponseData>;
pub type UasAuthenticationConfirmationRouterData = RouterData<
AuthenticationConfirmation,
UasConfirmationRequestData,
UasAuthenticationResponseData,
>;
pub type MandateRevokeRouterData =
RouterData<MandateRevoke, MandateRevokeRequestData, MandateRevokeResponseData>;
pub type PaymentsIncrementalAuthorizationRouterData = RouterData<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>;
pub type PaymentsExtendAuthorizationRouterData =
RouterData<ExtendAuthorization, PaymentsExtendAuthorizationData, PaymentsResponseData>;
pub type SdkSessionUpdateRouterData =
RouterData<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>;
pub type VerifyWebhookSourceRouterData = RouterData<
VerifyWebhookSource,
VerifyWebhookSourceRequestData,
VerifyWebhookSourceResponseData,
>;
#[cfg(feature = "payouts")]
pub type PayoutsRouterData<F> = RouterData<F, PayoutsData, PayoutsResponseData>;
pub type InvoiceRecordBackRouterData =
RouterData<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse>;
pub type GetSubscriptionPlansRouterData =
RouterData<GetSubscriptionPlans, GetSubscriptionPlansRequest, GetSubscriptionPlansResponse>;
pub type GetSubscriptionEstimateRouterData = RouterData<
GetSubscriptionEstimate,
GetSubscriptionEstimateRequest,
GetSubscriptionEstimateResponse,
>;
pub type UasAuthenticationRouterData =
RouterData<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>;
pub type BillingConnectorPaymentsSyncRouterData = RouterData<
BillingConnectorPaymentsSync,
BillingConnectorPaymentsSyncRequest,
BillingConnectorPaymentsSyncResponse,
>;
pub type BillingConnectorInvoiceSyncRouterData = RouterData<
BillingConnectorInvoiceSync,
BillingConnectorInvoiceSyncRequest,
BillingConnectorInvoiceSyncResponse,
>;
pub type BillingConnectorInvoiceSyncRouterDataV2 = RouterDataV2<
BillingConnectorInvoiceSync,
router_data_v2::flow_common_types::BillingConnectorInvoiceSyncFlowData,
BillingConnectorInvoiceSyncRequest,
BillingConnectorInvoiceSyncResponse,
>;
pub type BillingConnectorPaymentsSyncRouterDataV2 = RouterDataV2<
BillingConnectorPaymentsSync,
router_data_v2::flow_common_types::BillingConnectorPaymentsSyncFlowData,
BillingConnectorPaymentsSyncRequest,
BillingConnectorPaymentsSyncResponse,
>;
pub type InvoiceRecordBackRouterDataV2 = RouterDataV2<
InvoiceRecordBack,
router_data_v2::flow_common_types::InvoiceRecordBackData,
InvoiceRecordBackRequest,
InvoiceRecordBackResponse,
>;
pub type GetSubscriptionPlanPricesRouterData = RouterData<
GetSubscriptionPlanPrices,
GetSubscriptionPlanPricesRequest,
GetSubscriptionPlanPricesResponse,
>;
pub type VaultRouterData<F> = RouterData<F, VaultRequestData, VaultResponseData>;
pub type VaultRouterDataV2<F> = RouterDataV2<
F,
router_data_v2::flow_common_types::VaultConnectorFlowData,
VaultRequestData,
VaultResponseData,
>;
pub type ExternalVaultProxyPaymentsRouterDataV2 = RouterDataV2<
ExternalVaultProxy,
router_data_v2::flow_common_types::ExternalVaultProxyFlowData,
ExternalVaultProxyPaymentsData,
PaymentsResponseData,
>;
pub type SubscriptionCreateRouterData =
RouterData<SubscriptionCreate, SubscriptionCreateRequest, SubscriptionCreateResponse>;
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/types.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2009
}
|
large_file_8352199373856755238
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/merchant_account.rs
</path>
<file>
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,
>;
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/merchant_account.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7393
}
|
large_file_3580461958184464950
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/merchant_connector_account.rs
</path>
<file>
#[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>;
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/merchant_connector_account.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 8484
}
|
large_file_7441902805601695073
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/payments.rs
</path>
<file>
#[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()),
}
}
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/payments.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 11129
}
|
large_file_-2690889537310184100
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/lib.rs
</path>
<file>
pub mod address;
pub mod api;
pub mod authentication;
pub mod behaviour;
pub mod bulk_tokenization;
pub mod business_profile;
pub mod callback_mapper;
pub mod card_testing_guard_data;
pub mod cards_info;
pub mod chat;
pub mod configs;
pub mod connector_endpoints;
pub mod consts;
pub mod customer;
pub mod disputes;
pub mod errors;
pub mod ext_traits;
pub mod gsm;
pub mod invoice;
pub mod mandates;
pub mod master_key;
pub mod merchant_account;
pub mod merchant_connector_account;
pub mod merchant_context;
pub mod merchant_key_store;
pub mod network_tokenization;
pub mod payment_address;
pub mod payment_method_data;
pub mod payment_methods;
pub mod payments;
#[cfg(feature = "payouts")]
pub mod payouts;
pub mod refunds;
pub mod relay;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
pub mod revenue_recovery;
pub mod router_data;
pub mod router_data_v2;
pub mod router_flow_types;
pub mod router_request_types;
pub mod router_response_types;
pub mod routing;
pub mod subscription;
#[cfg(feature = "tokenization_v2")]
pub mod tokenization;
pub mod transformers;
pub mod type_encryption;
pub mod types;
pub mod vault;
#[cfg(not(feature = "payouts"))]
pub trait PayoutAttemptInterface {}
#[cfg(not(feature = "payouts"))]
pub trait PayoutsInterface {}
use api_models::payments::{
ApplePayRecurringDetails as ApiApplePayRecurringDetails,
ApplePayRegularBillingDetails as ApiApplePayRegularBillingDetails,
FeatureMetadata as ApiFeatureMetadata, OrderDetailsWithAmount as ApiOrderDetailsWithAmount,
RecurringPaymentIntervalUnit as ApiRecurringPaymentIntervalUnit,
RedirectResponse as ApiRedirectResponse,
};
#[cfg(feature = "v2")]
use api_models::payments::{
BillingConnectorAdditionalCardInfo as ApiBillingConnectorAdditionalCardInfo,
BillingConnectorPaymentDetails as ApiBillingConnectorPaymentDetails,
BillingConnectorPaymentMethodDetails as ApiBillingConnectorPaymentMethodDetails,
PaymentRevenueRecoveryMetadata as ApiRevenueRecoveryMetadata,
};
use diesel_models::types::{
ApplePayRecurringDetails, ApplePayRegularBillingDetails, FeatureMetadata,
OrderDetailsWithAmount, RecurringPaymentIntervalUnit, RedirectResponse,
};
#[cfg(feature = "v2")]
use diesel_models::types::{
BillingConnectorAdditionalCardInfo, BillingConnectorPaymentDetails,
BillingConnectorPaymentMethodDetails, PaymentRevenueRecoveryMetadata,
};
#[derive(Clone, Debug, Eq, PartialEq, serde::Serialize)]
pub enum RemoteStorageObject<T: ForeignIDRef> {
ForeignID(String),
Object(T),
}
impl<T: ForeignIDRef> From<T> for RemoteStorageObject<T> {
fn from(value: T) -> Self {
Self::Object(value)
}
}
pub trait ForeignIDRef {
fn foreign_id(&self) -> String;
}
impl<T: ForeignIDRef> RemoteStorageObject<T> {
pub fn get_id(&self) -> String {
match self {
Self::ForeignID(id) => id.clone(),
Self::Object(i) => i.foreign_id(),
}
}
}
use std::fmt::Debug;
pub trait ApiModelToDieselModelConvertor<F> {
/// Convert from a foreign type to the current type
fn convert_from(from: F) -> Self;
fn convert_back(self) -> F;
}
#[cfg(feature = "v1")]
impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata {
fn convert_from(from: ApiFeatureMetadata) -> Self {
let ApiFeatureMetadata {
redirect_response,
search_tags,
apple_pay_recurring_details,
} = from;
Self {
redirect_response: redirect_response.map(RedirectResponse::convert_from),
search_tags,
apple_pay_recurring_details: apple_pay_recurring_details
.map(ApplePayRecurringDetails::convert_from),
gateway_system: None,
}
}
fn convert_back(self) -> ApiFeatureMetadata {
let Self {
redirect_response,
search_tags,
apple_pay_recurring_details,
..
} = self;
ApiFeatureMetadata {
redirect_response: redirect_response
.map(|redirect_response| redirect_response.convert_back()),
search_tags,
apple_pay_recurring_details: apple_pay_recurring_details
.map(|value| value.convert_back()),
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<ApiFeatureMetadata> for FeatureMetadata {
fn convert_from(from: ApiFeatureMetadata) -> Self {
let ApiFeatureMetadata {
redirect_response,
search_tags,
apple_pay_recurring_details,
revenue_recovery: payment_revenue_recovery_metadata,
} = from;
Self {
redirect_response: redirect_response.map(RedirectResponse::convert_from),
search_tags,
apple_pay_recurring_details: apple_pay_recurring_details
.map(ApplePayRecurringDetails::convert_from),
payment_revenue_recovery_metadata: payment_revenue_recovery_metadata
.map(PaymentRevenueRecoveryMetadata::convert_from),
}
}
fn convert_back(self) -> ApiFeatureMetadata {
let Self {
redirect_response,
search_tags,
apple_pay_recurring_details,
payment_revenue_recovery_metadata,
} = self;
ApiFeatureMetadata {
redirect_response: redirect_response
.map(|redirect_response| redirect_response.convert_back()),
search_tags,
apple_pay_recurring_details: apple_pay_recurring_details
.map(|value| value.convert_back()),
revenue_recovery: payment_revenue_recovery_metadata.map(|value| value.convert_back()),
}
}
}
impl ApiModelToDieselModelConvertor<ApiRedirectResponse> for RedirectResponse {
fn convert_from(from: ApiRedirectResponse) -> Self {
let ApiRedirectResponse {
param,
json_payload,
} = from;
Self {
param,
json_payload,
}
}
fn convert_back(self) -> ApiRedirectResponse {
let Self {
param,
json_payload,
} = self;
ApiRedirectResponse {
param,
json_payload,
}
}
}
impl ApiModelToDieselModelConvertor<ApiRecurringPaymentIntervalUnit>
for RecurringPaymentIntervalUnit
{
fn convert_from(from: ApiRecurringPaymentIntervalUnit) -> Self {
match from {
ApiRecurringPaymentIntervalUnit::Year => Self::Year,
ApiRecurringPaymentIntervalUnit::Month => Self::Month,
ApiRecurringPaymentIntervalUnit::Day => Self::Day,
ApiRecurringPaymentIntervalUnit::Hour => Self::Hour,
ApiRecurringPaymentIntervalUnit::Minute => Self::Minute,
}
}
fn convert_back(self) -> ApiRecurringPaymentIntervalUnit {
match self {
Self::Year => ApiRecurringPaymentIntervalUnit::Year,
Self::Month => ApiRecurringPaymentIntervalUnit::Month,
Self::Day => ApiRecurringPaymentIntervalUnit::Day,
Self::Hour => ApiRecurringPaymentIntervalUnit::Hour,
Self::Minute => ApiRecurringPaymentIntervalUnit::Minute,
}
}
}
impl ApiModelToDieselModelConvertor<ApiApplePayRegularBillingDetails>
for ApplePayRegularBillingDetails
{
fn convert_from(from: ApiApplePayRegularBillingDetails) -> Self {
Self {
label: from.label,
recurring_payment_start_date: from.recurring_payment_start_date,
recurring_payment_end_date: from.recurring_payment_end_date,
recurring_payment_interval_unit: from
.recurring_payment_interval_unit
.map(RecurringPaymentIntervalUnit::convert_from),
recurring_payment_interval_count: from.recurring_payment_interval_count,
}
}
fn convert_back(self) -> ApiApplePayRegularBillingDetails {
ApiApplePayRegularBillingDetails {
label: self.label,
recurring_payment_start_date: self.recurring_payment_start_date,
recurring_payment_end_date: self.recurring_payment_end_date,
recurring_payment_interval_unit: self
.recurring_payment_interval_unit
.map(|value| value.convert_back()),
recurring_payment_interval_count: self.recurring_payment_interval_count,
}
}
}
impl ApiModelToDieselModelConvertor<ApiApplePayRecurringDetails> for ApplePayRecurringDetails {
fn convert_from(from: ApiApplePayRecurringDetails) -> Self {
Self {
payment_description: from.payment_description,
regular_billing: ApplePayRegularBillingDetails::convert_from(from.regular_billing),
billing_agreement: from.billing_agreement,
management_url: from.management_url,
}
}
fn convert_back(self) -> ApiApplePayRecurringDetails {
ApiApplePayRecurringDetails {
payment_description: self.payment_description,
regular_billing: self.regular_billing.convert_back(),
billing_agreement: self.billing_agreement,
management_url: self.management_url,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<ApiBillingConnectorAdditionalCardInfo>
for BillingConnectorAdditionalCardInfo
{
fn convert_from(from: ApiBillingConnectorAdditionalCardInfo) -> Self {
Self {
card_issuer: from.card_issuer,
card_network: from.card_network,
}
}
fn convert_back(self) -> ApiBillingConnectorAdditionalCardInfo {
ApiBillingConnectorAdditionalCardInfo {
card_issuer: self.card_issuer,
card_network: self.card_network,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<ApiBillingConnectorPaymentMethodDetails>
for BillingConnectorPaymentMethodDetails
{
fn convert_from(from: ApiBillingConnectorPaymentMethodDetails) -> Self {
match from {
ApiBillingConnectorPaymentMethodDetails::Card(data) => {
Self::Card(BillingConnectorAdditionalCardInfo::convert_from(data))
}
}
}
fn convert_back(self) -> ApiBillingConnectorPaymentMethodDetails {
match self {
Self::Card(data) => ApiBillingConnectorPaymentMethodDetails::Card(data.convert_back()),
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<ApiRevenueRecoveryMetadata> for PaymentRevenueRecoveryMetadata {
fn convert_from(from: ApiRevenueRecoveryMetadata) -> Self {
Self {
total_retry_count: from.total_retry_count,
payment_connector_transmission: from.payment_connector_transmission.unwrap_or_default(),
billing_connector_id: from.billing_connector_id,
active_attempt_payment_connector_id: from.active_attempt_payment_connector_id,
billing_connector_payment_details: BillingConnectorPaymentDetails::convert_from(
from.billing_connector_payment_details,
),
payment_method_type: from.payment_method_type,
payment_method_subtype: from.payment_method_subtype,
connector: from.connector,
invoice_next_billing_time: from.invoice_next_billing_time,
billing_connector_payment_method_details: from
.billing_connector_payment_method_details
.map(BillingConnectorPaymentMethodDetails::convert_from),
first_payment_attempt_network_advice_code: from
.first_payment_attempt_network_advice_code,
first_payment_attempt_network_decline_code: from
.first_payment_attempt_network_decline_code,
first_payment_attempt_pg_error_code: from.first_payment_attempt_pg_error_code,
invoice_billing_started_at_time: from.invoice_billing_started_at_time,
}
}
fn convert_back(self) -> ApiRevenueRecoveryMetadata {
ApiRevenueRecoveryMetadata {
total_retry_count: self.total_retry_count,
payment_connector_transmission: Some(self.payment_connector_transmission),
billing_connector_id: self.billing_connector_id,
active_attempt_payment_connector_id: self.active_attempt_payment_connector_id,
billing_connector_payment_details: self
.billing_connector_payment_details
.convert_back(),
payment_method_type: self.payment_method_type,
payment_method_subtype: self.payment_method_subtype,
connector: self.connector,
invoice_next_billing_time: self.invoice_next_billing_time,
billing_connector_payment_method_details: self
.billing_connector_payment_method_details
.map(|data| data.convert_back()),
first_payment_attempt_network_advice_code: self
.first_payment_attempt_network_advice_code,
first_payment_attempt_network_decline_code: self
.first_payment_attempt_network_decline_code,
first_payment_attempt_pg_error_code: self.first_payment_attempt_pg_error_code,
invoice_billing_started_at_time: self.invoice_billing_started_at_time,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<ApiBillingConnectorPaymentDetails>
for BillingConnectorPaymentDetails
{
fn convert_from(from: ApiBillingConnectorPaymentDetails) -> Self {
Self {
payment_processor_token: from.payment_processor_token,
connector_customer_id: from.connector_customer_id,
}
}
fn convert_back(self) -> ApiBillingConnectorPaymentDetails {
ApiBillingConnectorPaymentDetails {
payment_processor_token: self.payment_processor_token,
connector_customer_id: self.connector_customer_id,
}
}
}
impl ApiModelToDieselModelConvertor<ApiOrderDetailsWithAmount> for OrderDetailsWithAmount {
fn convert_from(from: ApiOrderDetailsWithAmount) -> Self {
let ApiOrderDetailsWithAmount {
product_name,
quantity,
amount,
requires_shipping,
product_img_link,
product_id,
category,
sub_category,
brand,
product_type,
product_tax_code,
tax_rate,
total_tax_amount,
description,
sku,
upc,
commodity_code,
unit_of_measure,
total_amount,
unit_discount_amount,
} = from;
Self {
product_name,
quantity,
amount,
requires_shipping,
product_img_link,
product_id,
category,
sub_category,
brand,
product_type,
product_tax_code,
tax_rate,
total_tax_amount,
description,
sku,
upc,
commodity_code,
unit_of_measure,
total_amount,
unit_discount_amount,
}
}
fn convert_back(self) -> ApiOrderDetailsWithAmount {
let Self {
product_name,
quantity,
amount,
requires_shipping,
product_img_link,
product_id,
category,
sub_category,
brand,
product_type,
product_tax_code,
tax_rate,
total_tax_amount,
description,
sku,
upc,
commodity_code,
unit_of_measure,
total_amount,
unit_discount_amount,
} = self;
ApiOrderDetailsWithAmount {
product_name,
quantity,
amount,
requires_shipping,
product_img_link,
product_id,
category,
sub_category,
brand,
product_type,
product_tax_code,
tax_rate,
total_tax_amount,
description,
sku,
upc,
commodity_code,
unit_of_measure,
total_amount,
unit_discount_amount,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkConfigRequest>
for diesel_models::payment_intent::PaymentLinkConfigRequestForPayments
{
fn convert_from(item: api_models::admin::PaymentLinkConfigRequest) -> Self {
Self {
theme: item.theme,
logo: item.logo,
seller_name: item.seller_name,
sdk_layout: item.sdk_layout,
display_sdk_only: item.display_sdk_only,
enabled_saved_payment_method: item.enabled_saved_payment_method,
hide_card_nickname_field: item.hide_card_nickname_field,
show_card_form_by_default: item.show_card_form_by_default,
details_layout: item.details_layout,
transaction_details: item.transaction_details.map(|transaction_details| {
transaction_details
.into_iter()
.map(|transaction_detail| {
diesel_models::PaymentLinkTransactionDetails::convert_from(
transaction_detail,
)
})
.collect()
}),
background_image: item.background_image.map(|background_image| {
diesel_models::business_profile::PaymentLinkBackgroundImageConfig::convert_from(
background_image,
)
}),
payment_button_text: item.payment_button_text,
custom_message_for_card_terms: item.custom_message_for_card_terms,
payment_button_colour: item.payment_button_colour,
skip_status_screen: item.skip_status_screen,
background_colour: item.background_colour,
payment_button_text_colour: item.payment_button_text_colour,
sdk_ui_rules: item.sdk_ui_rules,
payment_link_ui_rules: item.payment_link_ui_rules,
enable_button_only_on_form_ready: item.enable_button_only_on_form_ready,
payment_form_header_text: item.payment_form_header_text,
payment_form_label_type: item.payment_form_label_type,
show_card_terms: item.show_card_terms,
is_setup_mandate_flow: item.is_setup_mandate_flow,
color_icon_card_cvc_error: item.color_icon_card_cvc_error,
}
}
fn convert_back(self) -> api_models::admin::PaymentLinkConfigRequest {
let Self {
theme,
logo,
seller_name,
sdk_layout,
display_sdk_only,
enabled_saved_payment_method,
hide_card_nickname_field,
show_card_form_by_default,
transaction_details,
background_image,
details_layout,
payment_button_text,
custom_message_for_card_terms,
payment_button_colour,
skip_status_screen,
background_colour,
payment_button_text_colour,
sdk_ui_rules,
payment_link_ui_rules,
enable_button_only_on_form_ready,
payment_form_header_text,
payment_form_label_type,
show_card_terms,
is_setup_mandate_flow,
color_icon_card_cvc_error,
} = self;
api_models::admin::PaymentLinkConfigRequest {
theme,
logo,
seller_name,
sdk_layout,
display_sdk_only,
enabled_saved_payment_method,
hide_card_nickname_field,
show_card_form_by_default,
details_layout,
transaction_details: transaction_details.map(|transaction_details| {
transaction_details
.into_iter()
.map(|transaction_detail| transaction_detail.convert_back())
.collect()
}),
background_image: background_image
.map(|background_image| background_image.convert_back()),
payment_button_text,
custom_message_for_card_terms,
payment_button_colour,
skip_status_screen,
background_colour,
payment_button_text_colour,
sdk_ui_rules,
payment_link_ui_rules,
enable_button_only_on_form_ready,
payment_form_header_text,
payment_form_label_type,
show_card_terms,
is_setup_mandate_flow,
color_icon_card_cvc_error,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkTransactionDetails>
for diesel_models::PaymentLinkTransactionDetails
{
fn convert_from(from: api_models::admin::PaymentLinkTransactionDetails) -> Self {
Self {
key: from.key,
value: from.value,
ui_configuration: from
.ui_configuration
.map(diesel_models::TransactionDetailsUiConfiguration::convert_from),
}
}
fn convert_back(self) -> api_models::admin::PaymentLinkTransactionDetails {
let Self {
key,
value,
ui_configuration,
} = self;
api_models::admin::PaymentLinkTransactionDetails {
key,
value,
ui_configuration: ui_configuration
.map(|ui_configuration| ui_configuration.convert_back()),
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<api_models::admin::PaymentLinkBackgroundImageConfig>
for diesel_models::business_profile::PaymentLinkBackgroundImageConfig
{
fn convert_from(from: api_models::admin::PaymentLinkBackgroundImageConfig) -> Self {
Self {
url: from.url,
position: from.position,
size: from.size,
}
}
fn convert_back(self) -> api_models::admin::PaymentLinkBackgroundImageConfig {
let Self {
url,
position,
size,
} = self;
api_models::admin::PaymentLinkBackgroundImageConfig {
url,
position,
size,
}
}
}
#[cfg(feature = "v2")]
impl ApiModelToDieselModelConvertor<api_models::admin::TransactionDetailsUiConfiguration>
for diesel_models::TransactionDetailsUiConfiguration
{
fn convert_from(from: api_models::admin::TransactionDetailsUiConfiguration) -> Self {
Self {
position: from.position,
is_key_bold: from.is_key_bold,
is_value_bold: from.is_value_bold,
}
}
fn convert_back(self) -> api_models::admin::TransactionDetailsUiConfiguration {
let Self {
position,
is_key_bold,
is_value_bold,
} = self;
api_models::admin::TransactionDetailsUiConfiguration {
position,
is_key_bold,
is_value_bold,
}
}
}
#[cfg(feature = "v2")]
impl From<api_models::payments::AmountDetails> for payments::AmountDetails {
fn from(amount_details: api_models::payments::AmountDetails) -> Self {
Self {
order_amount: amount_details.order_amount().into(),
currency: amount_details.currency(),
shipping_cost: amount_details.shipping_cost(),
tax_details: amount_details.order_tax_amount().map(|order_tax_amount| {
diesel_models::TaxDetails {
default: Some(diesel_models::DefaultTax { order_tax_amount }),
payment_method_type: None,
}
}),
skip_external_tax_calculation: amount_details.skip_external_tax_calculation(),
skip_surcharge_calculation: amount_details.skip_surcharge_calculation(),
surcharge_amount: amount_details.surcharge_amount(),
tax_on_surcharge: amount_details.tax_on_surcharge(),
// We will not receive this in the request. This will be populated after calling the connector / processor
amount_captured: None,
}
}
}
#[cfg(feature = "v2")]
impl From<payments::AmountDetails> for api_models::payments::AmountDetailsSetter {
fn from(amount_details: payments::AmountDetails) -> Self {
Self {
order_amount: amount_details.order_amount.into(),
currency: amount_details.currency,
shipping_cost: amount_details.shipping_cost,
order_tax_amount: amount_details
.tax_details
.and_then(|tax_detail| tax_detail.get_default_tax_amount()),
skip_external_tax_calculation: amount_details.skip_external_tax_calculation,
skip_surcharge_calculation: amount_details.skip_surcharge_calculation,
surcharge_amount: amount_details.surcharge_amount,
tax_on_surcharge: amount_details.tax_on_surcharge,
}
}
}
#[cfg(feature = "v2")]
impl From<&api_models::payments::PaymentAttemptAmountDetails>
for payments::payment_attempt::AttemptAmountDetailsSetter
{
fn from(amount: &api_models::payments::PaymentAttemptAmountDetails) -> Self {
Self {
net_amount: amount.net_amount,
amount_to_capture: amount.amount_to_capture,
surcharge_amount: amount.surcharge_amount,
tax_on_surcharge: amount.tax_on_surcharge,
amount_capturable: amount.amount_capturable,
shipping_cost: amount.shipping_cost,
order_tax_amount: amount.order_tax_amount,
}
}
}
#[cfg(feature = "v2")]
impl From<&payments::payment_attempt::AttemptAmountDetailsSetter>
for api_models::payments::PaymentAttemptAmountDetails
{
fn from(amount: &payments::payment_attempt::AttemptAmountDetailsSetter) -> Self {
Self {
net_amount: amount.net_amount,
amount_to_capture: amount.amount_to_capture,
surcharge_amount: amount.surcharge_amount,
tax_on_surcharge: amount.tax_on_surcharge,
amount_capturable: amount.amount_capturable,
shipping_cost: amount.shipping_cost,
order_tax_amount: amount.order_tax_amount,
}
}
}
#[cfg(feature = "v2")]
impl From<&api_models::payments::RecordAttemptErrorDetails>
for payments::payment_attempt::ErrorDetails
{
fn from(error: &api_models::payments::RecordAttemptErrorDetails) -> Self {
Self {
code: error.code.clone(),
message: error.message.clone(),
reason: Some(error.message.clone()),
unified_code: None,
unified_message: None,
network_advice_code: error.network_advice_code.clone(),
network_decline_code: error.network_decline_code.clone(),
network_error_message: error.network_error_message.clone(),
}
}
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/lib.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5206
}
|
large_file_5308016517361552047
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/connector_endpoints.rs
</path>
<file>
//! 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,
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/connector_endpoints.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2051
}
|
large_file_2587657695976315028
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/subscription.rs
</path>
<file>
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,
})
}
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/subscription.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2089
}
|
large_file_990038839705177326
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/bulk_tokenization.rs
</path>
<file>
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,
}
}
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/bulk_tokenization.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2513
}
|
large_file_-4638164728467029812
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/type_encryption.rs
</path>
<file>
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);
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/type_encryption.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 10778
}
|
large_file_4180716884921923730
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/invoice.rs
</path>
<file>
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,
}
}
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/invoice.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2584
}
|
large_file_-678664907701684127
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/customer.rs
</path>
<file>
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");
}
}
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/customer.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5597
}
|
large_file_8865758948911041844
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/router_response_types.rs
</path>
<file>
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(),
}
}
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/router_response_types.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4753
}
|
large_file_3565609844896918684
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/revenue_recovery.rs
</path>
<file>
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,
}
}
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/revenue_recovery.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2734
}
|
large_file_-3479064181088437155
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/mandates.rs
</path>
<file>
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,
}
}
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/mandates.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3883
}
|
large_file_3252140861922345239
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/relay.rs
</path>
<file>
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,
})
}
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/relay.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2125
}
|
large_file_9015603645596858257
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/errors/api_error_response.rs
</path>
<file>
use api_models::errors::types::Extra;
use common_utils::errors::ErrorSwitch;
use http::StatusCode;
use crate::router_data;
#[derive(Clone, Debug, serde::Serialize)]
#[serde(rename_all = "snake_case")]
pub enum ErrorType {
InvalidRequestError,
ObjectNotFound,
RouterError,
ProcessingError,
BadGateway,
ServerNotAvailable,
DuplicateRequest,
ValidationError,
ConnectorError,
LockTimeout,
}
// CE Connector Error Errors originating from connector's end
// HE Hyperswitch Error Errors originating from Hyperswitch's end
// IR Invalid Request Error Error caused due to invalid fields and values in API request
// WE Webhook Error Errors related to Webhooks
#[derive(Debug, Clone, router_derive::ApiError)]
#[error(error_type_enum = ErrorType)]
pub enum ApiErrorResponse {
#[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "{code}: {message}", ignore = "status_code")]
ExternalConnectorError {
code: String,
message: String,
connector: String,
status_code: u16,
reason: Option<String>,
},
#[error(error_type = ErrorType::ProcessingError, code = "CE_01", message = "Payment failed during authorization with connector. Retry payment")]
PaymentAuthorizationFailed { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::ProcessingError, code = "CE_02", message = "Payment failed during authentication with connector. Retry payment")]
PaymentAuthenticationFailed { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::ProcessingError, code = "CE_03", message = "Capture attempt failed while processing with connector")]
PaymentCaptureFailed { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::ProcessingError, code = "CE_04", message = "The card data is invalid")]
InvalidCardData { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::ProcessingError, code = "CE_05", message = "The card has expired")]
CardExpired { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::ProcessingError, code = "CE_06", message = "Refund failed while processing with connector. Retry refund")]
RefundFailed { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::ProcessingError, code = "CE_07", message = "Verification failed while processing with connector. Retry operation")]
VerificationFailed { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::ProcessingError, code = "CE_08", message = "Dispute operation failed while processing with connector. Retry operation")]
DisputeFailed { data: Option<serde_json::Value> },
#[error(error_type = ErrorType::LockTimeout, code = "HE_00", message = "Resource is busy. Please try again later.")]
ResourceBusy,
#[error(error_type = ErrorType::ServerNotAvailable, code = "HE_00", message = "Something went wrong")]
InternalServerError,
#[error(error_type = ErrorType::ServerNotAvailable, code= "HE_00", message = "{component} health check is failing with error: {message}")]
HealthCheckError {
component: &'static str,
message: String,
},
#[error(error_type = ErrorType::ValidationError, code = "HE_00", message = "Failed to convert currency to minor unit")]
CurrencyConversionFailed,
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate refund request. Refund already attempted with the refund ID")]
DuplicateRefundRequest,
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "Duplicate mandate request. Mandate already attempted with the Mandate ID")]
DuplicateMandate,
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant account with the specified details already exists in our records")]
DuplicateMerchantAccount,
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_label}' already exists in our records")]
DuplicateMerchantConnectorAccount {
profile_id: String,
connector_label: String,
},
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment method with the specified details already exists in our records")]
DuplicatePaymentMethod,
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payment with the specified payment_id already exists in our records")]
DuplicatePayment {
payment_id: common_utils::id_type::PaymentId,
},
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The payout with the specified payout_id '{payout_id:?}' already exists in our records")]
DuplicatePayout {
payout_id: common_utils::id_type::PayoutId,
},
#[error(error_type = ErrorType::DuplicateRequest, code = "HE_01", message = "The config with the specified key already exists in our records")]
DuplicateConfig,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Refund does not exist in our records")]
RefundNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment Link does not exist in our records")]
PaymentLinkNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Customer does not exist in our records")]
CustomerNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Config key does not exist in our records.")]
ConfigNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment does not exist in our records")]
PaymentNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payment method does not exist in our records")]
PaymentMethodNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant account does not exist in our records")]
MerchantAccountNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Merchant connector account does not exist in our records")]
MerchantConnectorAccountNotFound { id: String },
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Business profile with the given id '{id}' does not exist in our records")]
ProfileNotFound { id: String },
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Profile acquirer with id '{profile_acquirer_id}' not found for profile '{profile_id}'.")]
ProfileAcquirerNotFound {
profile_acquirer_id: String,
profile_id: String,
},
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Poll with the given id '{id}' does not exist in our records")]
PollNotFound { id: String },
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Resource ID does not exist in our records")]
ResourceIdNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Mandate does not exist in our records")]
MandateNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Authentication does not exist in our records")]
AuthenticationNotFound { id: String },
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Failed to update mandate")]
MandateUpdateFailed,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "API Key does not exist in our records")]
ApiKeyNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Payout does not exist in our records")]
PayoutNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Event does not exist in our records")]
EventNotFound,
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Invalid mandate id passed from connector")]
MandateSerializationFailed,
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Unable to parse the mandate identifier passed from connector")]
MandateDeserializationFailed,
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Return URL is not configured and not passed in payments request")]
ReturnUrlUnavailable,
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard")]
RefundNotPossible { connector: String },
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Mandate Validation Failed" )]
MandateValidationFailed { reason: String },
#[error(error_type= ErrorType::ValidationError, code = "HE_03", message = "The payment has not succeeded yet. Please pass a successful payment to initiate refund")]
PaymentNotSucceeded,
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "The specified merchant connector account is disabled")]
MerchantConnectorAccountDisabled,
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "{code}: {message}")]
PaymentBlockedError {
code: u16,
message: String,
status: String,
reason: String,
},
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "File validation failed")]
FileValidationFailed { reason: String },
#[error(error_type = ErrorType::ValidationError, code = "HE_03", message = "Dispute status validation failed")]
DisputeStatusValidationFailed { reason: String },
#[error(error_type= ErrorType::ObjectNotFound, code = "HE_04", message = "Successful payment not found for the given payment id")]
SuccessfulPaymentNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "The connector provided in the request is incorrect or not available")]
IncorrectConnectorNameGiven,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Address does not exist in our records")]
AddressNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "Dispute does not exist in our records")]
DisputeNotFound { dispute_id: String },
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File does not exist in our records")]
FileNotFound,
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_04", message = "File not available")]
FileNotAvailable,
#[error(error_type = ErrorType::ProcessingError, code = "HE_05", message = "Missing tenant id")]
MissingTenantId,
#[error(error_type = ErrorType::ProcessingError, code = "HE_05", message = "Invalid tenant id: {tenant_id}")]
InvalidTenant { tenant_id: String },
#[error(error_type = ErrorType::ValidationError, code = "HE_06", message = "Failed to convert amount to {amount_type} type")]
AmountConversionFailed { amount_type: &'static str },
#[error(error_type = ErrorType::ServerNotAvailable, code = "IR_00", message = "{message:?}")]
NotImplemented { message: NotImplementedMessage },
#[error(
error_type = ErrorType::InvalidRequestError, code = "IR_01",
message = "API key not provided or invalid API key used"
)]
Unauthorized,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_02", message = "Unrecognized request URL")]
InvalidRequestUrl,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_03", message = "The HTTP method is not applicable for this API")]
InvalidHttpMethod,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_04", message = "Missing required param: {field_name}")]
MissingRequiredField { field_name: &'static str },
#[error(
error_type = ErrorType::InvalidRequestError, code = "IR_05",
message = "{field_name} contains invalid data. Expected format is {expected_format}"
)]
InvalidDataFormat {
field_name: String,
expected_format: String,
},
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_06", message = "{message}")]
InvalidRequestData { message: String },
/// Typically used when a field has invalid value, or deserialization of the value contained in a field fails.
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_07", message = "Invalid value provided: {field_name}")]
InvalidDataValue { field_name: &'static str },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret was not provided")]
ClientSecretNotGiven,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_08", message = "Client secret has expired")]
ClientSecretExpired,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_09", message = "The client_secret provided does not match the client_secret associated with the Payment")]
ClientSecretInvalid,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_10", message = "Customer has active mandate/subsciption")]
MandateActive,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_11", message = "Customer has already been redacted")]
CustomerRedacted,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_12", message = "Reached maximum refund attempts")]
MaximumRefundCount,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_13", message = "The refund amount exceeds the amount captured")]
RefundAmountExceedsPaymentAmount,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_14", message = "This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}")]
PaymentUnexpectedState {
current_flow: String,
field_name: String,
current_value: String,
states: String,
},
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_15", message = "Invalid Ephemeral Key for the customer")]
InvalidEphemeralKey,
/// Typically used when information involving multiple fields or previously provided information doesn't satisfy a condition.
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_16", message = "{message}")]
PreconditionFailed { message: String },
#[error(
error_type = ErrorType::InvalidRequestError, code = "IR_17",
message = "Access forbidden, invalid JWT token was used"
)]
InvalidJwtToken,
#[error(
error_type = ErrorType::InvalidRequestError, code = "IR_18",
message = "{message}",
)]
GenericUnauthorized { message: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_19", message = "{message}")]
NotSupported { message: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_20", message = "{flow} flow not supported by the {connector} connector")]
FlowNotSupported { flow: String, connector: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_21", message = "Missing required params")]
MissingRequiredFields { field_names: Vec<&'static str> },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_22", message = "Access forbidden. Not authorized to access this resource {resource}")]
AccessForbidden { resource: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_23", message = "{message}")]
FileProviderNotSupported { message: String },
#[error(
error_type = ErrorType::ProcessingError, code = "IR_24",
message = "Invalid {wallet_name} wallet token"
)]
InvalidWalletToken { wallet_name: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_25", message = "Cannot delete the default payment method")]
PaymentMethodDeleteFailed,
#[error(
error_type = ErrorType::InvalidRequestError, code = "IR_26",
message = "Invalid Cookie"
)]
InvalidCookie,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_27", message = "Extended card info does not exist")]
ExtendedCardInfoNotFound,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_28", message = "{message}")]
CurrencyNotSupported { message: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_29", message = "{message}")]
UnprocessableEntity { message: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_30", message = "Merchant connector account is configured with invalid {config}")]
InvalidConnectorConfiguration { config: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_31", message = "Card with the provided iin does not exist")]
InvalidCardIin,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_32", message = "The provided card IIN length is invalid, please provide an iin with 6 or 8 digits")]
InvalidCardIinLength,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_33", message = "File not found / valid in the request")]
MissingFile,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_34", message = "Dispute id not found in the request")]
MissingDisputeId,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_35", message = "File purpose not found in the request or is invalid")]
MissingFilePurpose,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_36", message = "File content type not found / valid")]
MissingFileContentType,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_37", message = "{message}")]
GenericNotFoundError { message: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_38", message = "{message}")]
GenericDuplicateError { message: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_39", message = "required payment method is not configured or configured incorrectly for all configured connectors")]
IncorrectPaymentMethodConfiguration,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_40", message = "{message}")]
LinkConfigurationError { message: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_41", message = "Payout validation failed")]
PayoutFailed { data: Option<serde_json::Value> },
#[error(
error_type = ErrorType::InvalidRequestError, code = "IR_42",
message = "Cookies are not found in the request"
)]
CookieNotFound,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_43", message = "API does not support platform account operation")]
PlatformAccountAuthNotSupported,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_44", message = "Invalid platform account operation")]
InvalidPlatformOperation,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_45", message = "External vault failed during processing with connector")]
ExternalVaultFailed,
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_46", message = "Field {fields} doesn't match with the ones used during mandate creation")]
MandatePaymentDataMismatch { fields: String },
#[error(error_type = ErrorType::InvalidRequestError, code = "IR_47", message = "Connector '{connector}' rejected field '{field_name}': length {received_length} exceeds maximum of {max_length}")]
MaxFieldLengthViolated {
connector: String,
field_name: String,
max_length: usize,
received_length: usize,
},
#[error(error_type = ErrorType::InvalidRequestError, code = "WE_01", message = "Failed to authenticate the webhook")]
WebhookAuthenticationFailed,
#[error(error_type = ErrorType::InvalidRequestError, code = "WE_02", message = "Bad request received in webhook")]
WebhookBadRequest,
#[error(error_type = ErrorType::RouterError, code = "WE_03", message = "There was some issue processing the webhook")]
WebhookProcessingFailure,
#[error(error_type = ErrorType::ObjectNotFound, code = "WE_04", message = "Webhook resource not found")]
WebhookResourceNotFound,
#[error(error_type = ErrorType::InvalidRequestError, code = "WE_05", message = "Unable to process the webhook body")]
WebhookUnprocessableEntity,
#[error(error_type = ErrorType::InvalidRequestError, code = "WE_06", message = "Merchant Secret set my merchant for webhook source verification is invalid")]
WebhookInvalidMerchantSecret,
#[error(error_type = ErrorType::ServerNotAvailable, code = "IE", message = "{reason} as data mismatched for {field_names}")]
IntegrityCheckFailed {
reason: String,
field_names: String,
connector_transaction_id: Option<String>,
},
#[error(error_type = ErrorType::ObjectNotFound, code = "HE_02", message = "Tokenization record not found for the given token_id {id}")]
TokenizationRecordNotFound { id: String },
#[error(error_type = ErrorType::ConnectorError, code = "CE_00", message = "Subscription operation: {operation} failed with connector")]
SubscriptionError { operation: String },
}
#[derive(Clone)]
pub enum NotImplementedMessage {
Reason(String),
Default,
}
impl std::fmt::Debug for NotImplementedMessage {
fn fmt(&self, fmt: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Reason(message) => write!(fmt, "{message} is not implemented"),
Self::Default => {
write!(
fmt,
"This API is under development and will be made available soon."
)
}
}
}
}
impl ::core::fmt::Display for ApiErrorResponse {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(
f,
r#"{{"error":{}}}"#,
serde_json::to_string(self).unwrap_or_else(|_| "API error response".to_string())
)
}
}
impl ErrorSwitch<api_models::errors::types::ApiErrorResponse> for ApiErrorResponse {
fn switch(&self) -> api_models::errors::types::ApiErrorResponse {
use api_models::errors::types::{ApiError, ApiErrorResponse as AER};
match self {
Self::ExternalConnectorError {
code,
message,
connector,
reason,
status_code,
} => AER::ConnectorError(ApiError::new("CE", 0, format!("{code}: {message}"), Some(Extra {connector: Some(connector.clone()), reason: reason.to_owned(), ..Default::default()})), StatusCode::from_u16(*status_code).unwrap_or(StatusCode::INTERNAL_SERVER_ERROR)),
Self::PaymentAuthorizationFailed { data } => {
AER::BadRequest(ApiError::new("CE", 1, "Payment failed during authorization with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
}
Self::PaymentAuthenticationFailed { data } => {
AER::BadRequest(ApiError::new("CE", 2, "Payment failed during authentication with connector. Retry payment", Some(Extra { data: data.clone(), ..Default::default()})))
}
Self::PaymentCaptureFailed { data } => {
AER::BadRequest(ApiError::new("CE", 3, "Capture attempt failed while processing with connector", Some(Extra { data: data.clone(), ..Default::default()})))
}
Self::InvalidCardData { data } => AER::BadRequest(ApiError::new("CE", 4, "The card data is invalid", Some(Extra { data: data.clone(), ..Default::default()}))),
Self::CardExpired { data } => AER::BadRequest(ApiError::new("CE", 5, "The card has expired", Some(Extra { data: data.clone(), ..Default::default()}))),
Self::RefundFailed { data } => AER::BadRequest(ApiError::new("CE", 6, "Refund failed while processing with connector. Retry refund", Some(Extra { data: data.clone(), ..Default::default()}))),
Self::VerificationFailed { data } => {
AER::BadRequest(ApiError::new("CE", 7, "Verification failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
},
Self::DisputeFailed { data } => {
AER::BadRequest(ApiError::new("CE", 8, "Dispute operation failed while processing with connector. Retry operation", Some(Extra { data: data.clone(), ..Default::default()})))
}
Self::ResourceBusy => {
AER::Unprocessable(ApiError::new("HE", 0, "There was an issue processing the webhook body", None))
}
Self::CurrencyConversionFailed => {
AER::Unprocessable(ApiError::new("HE", 0, "Failed to convert currency to minor unit", None))
}
Self::InternalServerError => {
AER::InternalServerError(ApiError::new("HE", 0, "Something went wrong", None))
},
Self::HealthCheckError { message,component } => {
AER::InternalServerError(ApiError::new("HE",0,format!("{component} health check failed with error: {message}"),None))
},
Self::DuplicateRefundRequest => AER::BadRequest(ApiError::new("HE", 1, "Duplicate refund request. Refund already attempted with the refund ID", None)),
Self::DuplicateMandate => AER::BadRequest(ApiError::new("HE", 1, "Duplicate mandate request. Mandate already attempted with the Mandate ID", None)),
Self::DuplicateMerchantAccount => AER::BadRequest(ApiError::new("HE", 1, "The merchant account with the specified details already exists in our records", None)),
Self::DuplicateMerchantConnectorAccount { profile_id, connector_label: connector_name } => {
AER::BadRequest(ApiError::new("HE", 1, format!("The merchant connector account with the specified profile_id '{profile_id}' and connector_label '{connector_name}' already exists in our records"), None))
}
Self::DuplicatePaymentMethod => AER::BadRequest(ApiError::new("HE", 1, "The payment method with the specified details already exists in our records", None)),
Self::DuplicatePayment { payment_id } => {
AER::BadRequest(ApiError::new("HE", 1, "The payment with the specified payment_id already exists in our records", Some(Extra {reason: Some(format!("{payment_id:?} already exists")), ..Default::default()})))
}
Self::DuplicatePayout { payout_id } => {
AER::BadRequest(ApiError::new("HE", 1, format!("The payout with the specified payout_id '{payout_id:?}' already exists in our records"), None))
}
Self::DuplicateConfig => {
AER::BadRequest(ApiError::new("HE", 1, "The config with the specified key already exists in our records", None))
}
Self::RefundNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Refund does not exist in our records.", None))
}
Self::PaymentLinkNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Payment Link does not exist in our records", None))
}
Self::CustomerNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Customer does not exist in our records", None))
}
Self::ConfigNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Config key does not exist in our records.", None))
},
Self::PaymentNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Payment does not exist in our records", None))
}
Self::PaymentMethodNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Payment method does not exist in our records", None))
}
Self::MerchantAccountNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Merchant account does not exist in our records", None))
}
Self::MerchantConnectorAccountNotFound {id } => {
AER::NotFound(ApiError::new("HE", 2, "Merchant connector account does not exist in our records", Some(Extra {reason: Some(format!("{id} does not exist")), ..Default::default()})))
}
Self::ProfileNotFound { id } => {
AER::NotFound(ApiError::new("HE", 2, format!("Business profile with the given id {id} does not exist"), None))
}
Self::ProfileAcquirerNotFound { profile_acquirer_id, profile_id } => {
AER::NotFound(ApiError::new("HE", 2, format!("Profile acquirer with id '{profile_acquirer_id}' not found for profile '{profile_id}'."), None))
}
Self::PollNotFound { .. } => {
AER::NotFound(ApiError::new("HE", 2, "Poll does not exist in our records", None))
},
Self::ResourceIdNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Resource ID does not exist in our records", None))
}
Self::MandateNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Mandate does not exist in our records", None))
}
Self::AuthenticationNotFound { .. } => {
AER::NotFound(ApiError::new("HE", 2, "Authentication does not exist in our records", None))
},
Self::MandateUpdateFailed => {
AER::InternalServerError(ApiError::new("HE", 2, "Mandate update failed", None))
},
Self::ApiKeyNotFound => {
AER::NotFound(ApiError::new("HE", 2, "API Key does not exist in our records", None))
}
Self::PayoutNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Payout does not exist in our records", None))
}
Self::EventNotFound => {
AER::NotFound(ApiError::new("HE", 2, "Event does not exist in our records", None))
}
Self::MandateSerializationFailed | Self::MandateDeserializationFailed => {
AER::InternalServerError(ApiError::new("HE", 3, "Something went wrong", None))
},
Self::ReturnUrlUnavailable => AER::NotFound(ApiError::new("HE", 3, "Return URL is not configured and not passed in payments request", None)),
Self::RefundNotPossible { connector } => {
AER::BadRequest(ApiError::new("HE", 3, format!("This refund is not possible through Hyperswitch. Please raise the refund through {connector} dashboard"), None))
}
Self::MandateValidationFailed { reason } => {
AER::BadRequest(ApiError::new("HE", 3, "Mandate Validation Failed", Some(Extra { reason: Some(reason.to_owned()), ..Default::default() })))
}
Self::PaymentNotSucceeded => AER::BadRequest(ApiError::new("HE", 3, "The payment has not succeeded yet. Please pass a successful payment to initiate refund", None)),
Self::MerchantConnectorAccountDisabled => {
AER::BadRequest(ApiError::new("HE", 3, "The selected merchant connector account is disabled", None))
}
Self::PaymentBlockedError {
message,
reason,
..
} => AER::DomainError(ApiError::new("HE", 3, message, Some(Extra { reason: Some(reason.clone()), ..Default::default() }))),
Self::FileValidationFailed { reason } => {
AER::BadRequest(ApiError::new("HE", 3, format!("File validation failed {reason}"), None))
}
Self::DisputeStatusValidationFailed { .. } => {
AER::BadRequest(ApiError::new("HE", 3, "Dispute status validation failed", None))
}
Self::SuccessfulPaymentNotFound => {
AER::NotFound(ApiError::new("HE", 4, "Successful payment not found for the given payment id", None))
}
Self::IncorrectConnectorNameGiven => {
AER::NotFound(ApiError::new("HE", 4, "The connector provided in the request is incorrect or not available", None))
}
Self::AddressNotFound => {
AER::NotFound(ApiError::new("HE", 4, "Address does not exist in our records", None))
},
Self::DisputeNotFound { .. } => {
AER::NotFound(ApiError::new("HE", 4, "Dispute does not exist in our records", None))
},
Self::FileNotFound => {
AER::NotFound(ApiError::new("HE", 4, "File does not exist in our records", None))
}
Self::FileNotAvailable => {
AER::NotFound(ApiError::new("HE", 4, "File not available", None))
}
Self::MissingTenantId => {
AER::InternalServerError(ApiError::new("HE", 5, "Missing Tenant ID in the request".to_string(), None))
}
Self::InvalidTenant { tenant_id } => {
AER::InternalServerError(ApiError::new("HE", 5, format!("Invalid Tenant {tenant_id}"), None))
}
Self::AmountConversionFailed { amount_type } => {
AER::InternalServerError(ApiError::new("HE", 6, format!("Failed to convert amount to {amount_type} type"), None))
}
Self::NotImplemented { message } => {
AER::NotImplemented(ApiError::new("IR", 0, format!("{message:?}"), None))
}
Self::Unauthorized => AER::Unauthorized(ApiError::new(
"IR",
1,
"API key not provided or invalid API key used", None
)),
Self::InvalidRequestUrl => {
AER::NotFound(ApiError::new("IR", 2, "Unrecognized request URL", None))
}
Self::InvalidHttpMethod => AER::MethodNotAllowed(ApiError::new(
"IR",
3,
"The HTTP method is not applicable for this API", None
)),
Self::MissingRequiredField { field_name } => AER::BadRequest(
ApiError::new("IR", 4, format!("Missing required param: {field_name}"), None),
),
Self::InvalidDataFormat {
field_name,
expected_format,
} => AER::Unprocessable(ApiError::new(
"IR",
5,
format!(
"{field_name} contains invalid data. Expected format is {expected_format}"
), None
)),
Self::InvalidRequestData { message } => {
AER::Unprocessable(ApiError::new("IR", 6, message.to_string(), None))
}
Self::InvalidDataValue { field_name } => AER::BadRequest(ApiError::new(
"IR",
7,
format!("Invalid value provided: {field_name}"), None
)),
Self::ClientSecretNotGiven => AER::BadRequest(ApiError::new(
"IR",
8,
"client_secret was not provided", None
)),
Self::ClientSecretExpired => AER::BadRequest(ApiError::new(
"IR",
8,
"The provided client_secret has expired", None
)),
Self::ClientSecretInvalid => {
AER::BadRequest(ApiError::new("IR", 9, "The client_secret provided does not match the client_secret associated with the Payment", None))
}
Self::MandateActive => {
AER::BadRequest(ApiError::new("IR", 10, "Customer has active mandate/subsciption", None))
}
Self::CustomerRedacted => {
AER::BadRequest(ApiError::new("IR", 11, "Customer has already been redacted", None))
}
Self::MaximumRefundCount => AER::BadRequest(ApiError::new("IR", 12, "Reached maximum refund attempts", None)),
Self::RefundAmountExceedsPaymentAmount => {
AER::BadRequest(ApiError::new("IR", 13, "The refund amount exceeds the amount captured", None))
}
Self::PaymentUnexpectedState {
current_flow,
field_name,
current_value,
states,
} => AER::BadRequest(ApiError::new("IR", 14, format!("This Payment could not be {current_flow} because it has a {field_name} of {current_value}. The expected state is {states}"), None)),
Self::InvalidEphemeralKey => AER::Unauthorized(ApiError::new("IR", 15, "Invalid Ephemeral Key for the customer", None)),
Self::PreconditionFailed { message } => {
AER::BadRequest(ApiError::new("IR", 16, message.to_string(), None))
}
Self::InvalidJwtToken => AER::Unauthorized(ApiError::new("IR", 17, "Access forbidden, invalid JWT token was used", None)),
Self::GenericUnauthorized { message } => {
AER::Unauthorized(ApiError::new("IR", 18, message.to_string(), None))
},
Self::NotSupported { message } => {
AER::BadRequest(ApiError::new("IR", 19, "Payment method type not supported", Some(Extra {reason: Some(message.to_owned()), ..Default::default()})))
},
Self::FlowNotSupported { flow, connector } => {
AER::BadRequest(ApiError::new("IR", 20, format!("{flow} flow not supported"), Some(Extra {connector: Some(connector.to_owned()), ..Default::default()}))) //FIXME: error message
}
Self::MissingRequiredFields { field_names } => AER::BadRequest(
ApiError::new("IR", 21, "Missing required params".to_string(), Some(Extra {data: Some(serde_json::json!(field_names)), ..Default::default() })),
),
Self::AccessForbidden {resource} => {
AER::ForbiddenCommonResource(ApiError::new("IR", 22, format!("Access forbidden. Not authorized to access this resource {resource}"), None))
},
Self::FileProviderNotSupported { message } => {
AER::BadRequest(ApiError::new("IR", 23, message.to_string(), None))
},
Self::InvalidWalletToken { wallet_name} => AER::Unprocessable(ApiError::new(
"IR",
24,
format!("Invalid {wallet_name} wallet token"), None
)),
Self::PaymentMethodDeleteFailed => {
AER::BadRequest(ApiError::new("IR", 25, "Cannot delete the default payment method", None))
}
Self::InvalidCookie => {
AER::BadRequest(ApiError::new("IR", 26, "Invalid Cookie", None))
}
Self::ExtendedCardInfoNotFound => {
AER::NotFound(ApiError::new("IR", 27, "Extended card info does not exist", None))
}
Self::CurrencyNotSupported { message } => {
AER::BadRequest(ApiError::new("IR", 28, message, None))
}
Self::UnprocessableEntity {message} => AER::Unprocessable(ApiError::new("IR", 29, message.to_string(), None)),
Self::InvalidConnectorConfiguration {config} => {
AER::BadRequest(ApiError::new("IR", 30, format!("Merchant connector account is configured with invalid {config}"), None))
}
Self::InvalidCardIin => AER::BadRequest(ApiError::new("IR", 31, "The provided card IIN does not exist", None)),
Self::InvalidCardIinLength => AER::BadRequest(ApiError::new("IR", 32, "The provided card IIN length is invalid, please provide an IIN with 6 digits", None)),
Self::MissingFile => {
AER::BadRequest(ApiError::new("IR", 33, "File not found in the request", None))
}
Self::MissingDisputeId => {
AER::BadRequest(ApiError::new("IR", 34, "Dispute id not found in the request", None))
}
Self::MissingFilePurpose => {
AER::BadRequest(ApiError::new("IR", 35, "File purpose not found in the request or is invalid", None))
}
Self::MissingFileContentType => {
AER::BadRequest(ApiError::new("IR", 36, "File content type not found", None))
}
Self::GenericNotFoundError { message } => {
AER::NotFound(ApiError::new("IR", 37, message, None))
},
Self::GenericDuplicateError { message } => {
AER::BadRequest(ApiError::new("IR", 38, message, None))
}
Self::IncorrectPaymentMethodConfiguration => {
AER::BadRequest(ApiError::new("IR", 39, "No eligible connector was found for the current payment method configuration", None))
}
Self::LinkConfigurationError { message } => {
AER::BadRequest(ApiError::new("IR", 40, message, None))
},
Self::PayoutFailed { data } => {
AER::BadRequest(ApiError::new("IR", 41, "Payout failed while processing with connector.", Some(Extra { data: data.clone(), ..Default::default()})))
},
Self::CookieNotFound => {
AER::Unauthorized(ApiError::new("IR", 42, "Cookies are not found in the request", None))
},
Self::ExternalVaultFailed => {
AER::BadRequest(ApiError::new("IR", 45, "External Vault failed while processing with connector.", None))
},
Self::MandatePaymentDataMismatch { fields} => {
AER::BadRequest(ApiError::new("IR", 46, format!("Field {fields} doesn't match with the ones used during mandate creation"), Some(Extra {fields: Some(fields.to_owned()), ..Default::default()}))) //FIXME: error message
}
Self::MaxFieldLengthViolated { connector, field_name, max_length, received_length} => {
AER::BadRequest(ApiError::new("IR", 47, format!("Connector '{connector}' rejected field '{field_name}': length {received_length} exceeds maximum of {max_length}"), Some(Extra {connector: Some(connector.to_string()), ..Default::default()})))
}
Self::WebhookAuthenticationFailed => {
AER::Unauthorized(ApiError::new("WE", 1, "Webhook authentication failed", None))
}
Self::WebhookBadRequest => {
AER::BadRequest(ApiError::new("WE", 2, "Bad request body received", None))
}
Self::WebhookProcessingFailure => {
AER::InternalServerError(ApiError::new("WE", 3, "There was an issue processing the webhook", None))
},
Self::WebhookResourceNotFound => {
AER::NotFound(ApiError::new("WE", 4, "Webhook resource was not found", None))
}
Self::WebhookUnprocessableEntity => {
AER::Unprocessable(ApiError::new("WE", 5, "There was an issue processing the webhook body", None))
},
Self::WebhookInvalidMerchantSecret => {
AER::BadRequest(ApiError::new("WE", 6, "Merchant Secret set for webhook source verification is invalid", None))
}
Self::IntegrityCheckFailed {
reason,
field_names,
connector_transaction_id
} => AER::InternalServerError(ApiError::new(
"IE",
0,
format!("{reason} as data mismatched for {field_names}"),
Some(Extra {
connector_transaction_id: connector_transaction_id.to_owned(),
..Default::default()
})
)),
Self::PlatformAccountAuthNotSupported => {
AER::BadRequest(ApiError::new("IR", 43, "API does not support platform operation", None))
}
Self::InvalidPlatformOperation => {
AER::Unauthorized(ApiError::new("IR", 44, "Invalid platform account operation", None))
}
Self::TokenizationRecordNotFound{ id } => {
AER::NotFound(ApiError::new("HE", 2, format!("Tokenization record not found for the given token_id '{id}' "), None))
}
Self::SubscriptionError { operation } => {
AER::BadRequest(ApiError::new("CE", 9, format!("Subscription operation: {operation} failed with connector"), None))
}
}
}
}
impl actix_web::ResponseError for ApiErrorResponse {
fn status_code(&self) -> StatusCode {
ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(self).status_code()
}
fn error_response(&self) -> actix_web::HttpResponse {
ErrorSwitch::<api_models::errors::types::ApiErrorResponse>::switch(self).error_response()
}
}
impl From<ApiErrorResponse> for router_data::ErrorResponse {
fn from(error: ApiErrorResponse) -> Self {
Self {
code: error.error_code(),
message: error.error_message(),
reason: None,
status_code: match error {
ApiErrorResponse::ExternalConnectorError { status_code, .. } => status_code,
_ => 500,
},
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}
}
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/errors/api_error_response.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 10461
}
|
large_file_-5538440330325265345
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_domain_models
File: crates/hyperswitch_domain_models/src/payouts/payouts.rs
</path>
<file>
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()
},
}
}
}
</file>
|
{
"crate": "hyperswitch_domain_models",
"file": "crates/hyperswitch_domain_models/src/payouts/payouts.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 2047
}
|
large_file_-6507471728499729065
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/nexinets.rs
</path>
<file>
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)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/nexinets.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6908
}
|
large_file_-7040189083114107576
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs
</path>
<file>
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
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3676
}
|
large_file_7571277928645933066
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/wellsfargo.rs
</path>
<file>
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)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/wellsfargo.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 10950
}
|
large_file_-851554693125112144
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/zsl.rs
</path>
<file>
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)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/zsl.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3746
}
|
large_file_-1115835265662819098
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/braintree.rs
</path>
<file>
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,
]
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/braintree.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 11265
}
|
large_file_-8913277469565209646
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/noon.rs
</path>
<file>
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)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/noon.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7802
}
|
large_file_-349379935154137141
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/breadpay.rs
</path>
<file>
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)
}
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/breadpay.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6246
}
|
large_file_-80150907867388433
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
</path>
<file>
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()
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 13252
}
|
large_file_509568609642082562
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/thunes.rs
</path>
<file>
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
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/thunes.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4479
}
|
large_file_-1752528987760531048
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/paysafe.rs
</path>
<file>
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
)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/paysafe.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 9348
}
|
large_file_9025847405865885314
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/nordea.rs
</path>
<file>
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
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/nordea.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 8455
}
|
large_file_3757485872993419098
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/adyenplatform.rs
</path>
<file>
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
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/adyenplatform.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3841
}
|
large_file_7103604159595091653
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/amazonpay.rs
</path>
<file>
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)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/amazonpay.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5919
}
|
large_file_-8070941852879125713
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/signifyd.rs
</path>
<file>
pub mod transformers;
use std::fmt::Debug;
#[cfg(feature = "frm")]
use api_models::webhooks::IncomingWebhookEvent;
#[cfg(feature = "frm")]
use base64::Engine;
#[cfg(feature = "frm")]
use common_utils::{
consts,
request::{Method, RequestBuilder},
};
#[cfg(feature = "frm")]
use common_utils::{crypto, ext_traits::ByteSliceExt, request::RequestContent};
use common_utils::{errors::CustomResult, request::Request};
#[cfg(feature = "frm")]
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{AccessToken, RouterData},
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 = "frm")]
use hyperswitch_domain_models::{
router_data::{ConnectorAuthType, ErrorResponse},
router_flow_types::{Checkout, Fulfillment, RecordReturn, Sale, Transaction},
router_request_types::fraud_check::{
FraudCheckCheckoutData, FraudCheckFulfillmentData, FraudCheckRecordReturnData,
FraudCheckSaleData, FraudCheckTransactionData,
},
router_response_types::fraud_check::FraudCheckResponseData,
};
use hyperswitch_interfaces::{
api::{
ConnectorAccessToken, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration,
ConnectorSpecifications, ConnectorValidation, MandateSetup, Payment, PaymentAuthorize,
PaymentCapture, PaymentSession, PaymentSync, PaymentToken, PaymentVoid, Refund,
RefundExecute, RefundSync,
},
configs::Connectors,
errors::ConnectorError,
};
#[cfg(feature = "frm")]
use hyperswitch_interfaces::{
api::{
FraudCheck, FraudCheckCheckout, FraudCheckFulfillment, FraudCheckRecordReturn,
FraudCheckSale, FraudCheckTransaction,
},
consts::NO_ERROR_CODE,
events::connector_api_logs::ConnectorEvent,
types::Response,
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
#[cfg(feature = "frm")]
use masking::Mask;
use masking::Maskable;
#[cfg(feature = "frm")]
use masking::{PeekInterface, Secret};
#[cfg(feature = "frm")]
use ring::hmac;
#[cfg(feature = "frm")]
use transformers as signifyd;
use crate::constants::headers;
#[cfg(feature = "frm")]
use crate::{
types::{
FrmCheckoutRouterData, FrmCheckoutType, FrmFulfillmentRouterData, FrmFulfillmentType,
FrmRecordReturnRouterData, FrmRecordReturnType, FrmSaleRouterData, FrmSaleType,
FrmTransactionRouterData, FrmTransactionType, ResponseRouterData,
},
utils::get_header_key_value,
};
#[derive(Debug, Clone)]
pub struct Signifyd;
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Signifyd
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, 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 Signifyd {
fn id(&self) -> &'static str {
"signifyd"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.signifyd.base_url.as_ref()
}
#[cfg(feature = "frm")]
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let auth = signifyd::SignifydAuthType::try_from(auth_type)
.change_context(ConnectorError::FailedToObtainAuthType)?;
let auth_api_key = format!(
"Basic {}",
consts::BASE64_ENGINE.encode(auth.api_key.peek())
);
Ok(vec![(
headers::AUTHORIZATION.to_string(),
Mask::into_masked(auth_api_key),
)])
}
#[cfg(feature = "frm")]
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
let response: signifyd::SignifydErrorResponse = res
.response
.parse_struct("SignifydErrorResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_string(),
message: response.messages.join(" &"),
reason: Some(response.errors.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 Payment for Signifyd {}
impl PaymentAuthorize for Signifyd {}
impl PaymentSync for Signifyd {}
impl PaymentVoid for Signifyd {}
impl PaymentCapture for Signifyd {}
impl MandateSetup for Signifyd {}
impl ConnectorAccessToken for Signifyd {}
impl PaymentToken for Signifyd {}
impl Refund for Signifyd {}
impl RefundExecute for Signifyd {}
impl RefundSync for Signifyd {}
impl ConnectorValidation for Signifyd {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Signifyd
{
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Signifyd {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Signifyd
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Err(ConnectorError::NotImplemented("Setup Mandate flow for Signifyd".to_string()).into())
}
}
impl PaymentSession for Signifyd {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Signifyd {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Signifyd {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Signifyd {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Signifyd {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Signifyd {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Signifyd {}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Signifyd {}
#[cfg(feature = "frm")]
impl FraudCheck for Signifyd {}
#[cfg(feature = "frm")]
impl FraudCheckSale for Signifyd {}
#[cfg(feature = "frm")]
impl FraudCheckCheckout for Signifyd {}
#[cfg(feature = "frm")]
impl FraudCheckTransaction for Signifyd {}
#[cfg(feature = "frm")]
impl FraudCheckFulfillment for Signifyd {}
#[cfg(feature = "frm")]
impl FraudCheckRecordReturn for Signifyd {}
#[cfg(feature = "frm")]
impl ConnectorIntegration<Sale, FraudCheckSaleData, FraudCheckResponseData> for Signifyd {
fn get_headers(
&self,
req: &FrmSaleRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &FrmSaleRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"v3/orders/events/sales"
))
}
fn get_request_body(
&self,
req: &FrmSaleRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let req_obj = signifyd::SignifydPaymentsSaleRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &FrmSaleRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&FrmSaleType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(FrmSaleType::get_headers(self, req, connectors)?)
.set_body(FrmSaleType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &FrmSaleRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<FrmSaleRouterData, ConnectorError> {
let response: signifyd::SignifydPaymentsResponse = res
.response
.parse_struct("SignifydPaymentsResponse Sale")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
<FrmSaleRouterData>::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)
}
}
#[cfg(feature = "frm")]
impl ConnectorIntegration<Checkout, FraudCheckCheckoutData, FraudCheckResponseData> for Signifyd {
fn get_headers(
&self,
req: &FrmCheckoutRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &FrmCheckoutRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"v3/orders/events/checkouts"
))
}
fn get_request_body(
&self,
req: &FrmCheckoutRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let req_obj = signifyd::SignifydPaymentsCheckoutRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &FrmCheckoutRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&FrmCheckoutType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(FrmCheckoutType::get_headers(self, req, connectors)?)
.set_body(FrmCheckoutType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &FrmCheckoutRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<FrmCheckoutRouterData, ConnectorError> {
let response: signifyd::SignifydPaymentsResponse = res
.response
.parse_struct("SignifydPaymentsResponse Checkout")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
<FrmCheckoutRouterData>::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)
}
}
#[cfg(feature = "frm")]
impl ConnectorIntegration<Transaction, FraudCheckTransactionData, FraudCheckResponseData>
for Signifyd
{
fn get_headers(
&self,
req: &FrmTransactionRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &FrmTransactionRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"v3/orders/events/transactions"
))
}
fn get_request_body(
&self,
req: &FrmTransactionRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let req_obj = signifyd::SignifydPaymentsTransactionRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &FrmTransactionRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&FrmTransactionType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(FrmTransactionType::get_headers(self, req, connectors)?)
.set_body(FrmTransactionType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &FrmTransactionRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<FrmTransactionRouterData, ConnectorError> {
let response: signifyd::SignifydPaymentsResponse = res
.response
.parse_struct("SignifydPaymentsResponse Transaction")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
<FrmTransactionRouterData>::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)
}
}
#[cfg(feature = "frm")]
impl ConnectorIntegration<Fulfillment, FraudCheckFulfillmentData, FraudCheckResponseData>
for Signifyd
{
fn get_headers(
&self,
req: &FrmFulfillmentRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &FrmFulfillmentRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"v3/orders/events/fulfillments"
))
}
fn get_request_body(
&self,
req: &FrmFulfillmentRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let req_obj = signifyd::FrmFulfillmentSignifydRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj.clone())))
}
fn build_request(
&self,
req: &FrmFulfillmentRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&FrmFulfillmentType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(FrmFulfillmentType::get_headers(self, req, connectors)?)
.set_body(FrmFulfillmentType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &FrmFulfillmentRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<FrmFulfillmentRouterData, ConnectorError> {
let response: signifyd::FrmFulfillmentSignifydApiResponse = res
.response
.parse_struct("FrmFulfillmentSignifydApiResponse Sale")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
FrmFulfillmentRouterData::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)
}
}
#[cfg(feature = "frm")]
impl ConnectorIntegration<RecordReturn, FraudCheckRecordReturnData, FraudCheckResponseData>
for Signifyd
{
fn get_headers(
&self,
req: &FrmRecordReturnRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &FrmRecordReturnRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!(
"{}{}",
self.base_url(connectors),
"v3/orders/events/returns/records"
))
}
fn get_request_body(
&self,
req: &FrmRecordReturnRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let req_obj = signifyd::SignifydPaymentsRecordReturnRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &FrmRecordReturnRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&FrmRecordReturnType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(FrmRecordReturnType::get_headers(self, req, connectors)?)
.set_body(FrmRecordReturnType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &FrmRecordReturnRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<FrmRecordReturnRouterData, ConnectorError> {
let response: signifyd::SignifydPaymentsRecordReturnResponse = res
.response
.parse_struct("SignifydPaymentsResponse Transaction")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
<FrmRecordReturnRouterData>::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)
}
}
#[cfg(feature = "frm")]
#[async_trait::async_trait]
impl IncomingWebhook for Signifyd {
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, ConnectorError> {
let header_value = get_header_key_value("x-signifyd-sec-hmac-sha256", request.headers)?;
Ok(header_value.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>, ConnectorError> {
Ok(request.body.to_vec())
}
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> {
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 signing_key = hmac::Key::new(hmac::HMAC_SHA256, &connector_webhook_secrets.secret);
let signed_message = hmac::sign(&signing_key, &message);
let payload_sign = consts::BASE64_ENGINE.encode(signed_message.as_ref());
Ok(payload_sign.as_bytes().eq(&signature))
}
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, ConnectorError> {
let resource: signifyd::SignifydWebhookBody = request
.body
.parse_struct("SignifydWebhookBody")
.change_context(ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::PaymentAttemptId(resource.order_id),
))
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, ConnectorError> {
let resource: signifyd::SignifydWebhookBody = request
.body
.parse_struct("SignifydWebhookBody")
.change_context(ConnectorError::WebhookEventTypeNotFound)?;
Ok(IncomingWebhookEvent::from(resource.review_disposition))
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> {
let resource: signifyd::SignifydWebhookBody = request
.body
.parse_struct("SignifydWebhookBody")
.change_context(ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(resource))
}
}
static SYGNIFYD_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Signifyd",
description: "Signifyd fraud and risk management provider with AI-driven commerce protection platform for maximizing conversions and eliminating fraud risk with guaranteed fraud liability coverage",
connector_type: common_enums::HyperswitchConnectorCategory::FraudAndRiskManagementProvider,
integration_status: common_enums::ConnectorIntegrationStatus::Sandbox,
};
impl ConnectorSpecifications for Signifyd {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&SYGNIFYD_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
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/signifyd.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5736
}
|
large_file_-3455957446615841420
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/coinbase.rs
</path>
<file>
pub mod transformers;
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::ResultExt;
use hyperswitch_domain_models::{
connector_endpoints::Connectors,
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, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
errors,
events::connector_api_logs::ConnectorEvent,
types::{PaymentsAuthorizeType, PaymentsSyncType, Response},
webhooks,
};
use lazy_static::lazy_static;
use masking::Mask;
use transformers as coinbase;
use self::coinbase::CoinbaseWebhookDetails;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, convert_amount},
};
#[derive(Clone)]
pub struct Coinbase {
amount_convertor: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Coinbase {
pub fn new() -> &'static Self {
&Self {
amount_convertor: &StringMajorUnitForConnector,
}
}
}
impl api::Payment for Coinbase {}
impl api::PaymentToken for Coinbase {}
impl api::PaymentSession for Coinbase {}
impl api::ConnectorAccessToken for Coinbase {}
impl api::MandateSetup for Coinbase {}
impl api::PaymentAuthorize for Coinbase {}
impl api::PaymentSync for Coinbase {}
impl api::PaymentCapture for Coinbase {}
impl api::PaymentVoid for Coinbase {}
impl api::Refund for Coinbase {}
impl api::RefundExecute for Coinbase {}
impl api::RefundSync for Coinbase {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Coinbase
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.common_get_content_type().to_string().into(),
),
(
headers::X_CC_VERSION.to_string(),
"2018-03-22".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 Coinbase {
fn id(&self) -> &'static str {
"coinbase"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.coinbase.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth: coinbase::CoinbaseAuthType = coinbase::CoinbaseAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::X_CC_API_KEY.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: coinbase::CoinbaseErrorResponse = res
.response
.parse_struct("CoinbaseErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.error_type,
message: response.error.message,
reason: response.error.code,
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 Coinbase {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Coinbase
{
// Not Implemented (R)
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Coinbase {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Coinbase {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Coinbase
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Coinbase".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Coinbase {
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!("{}/charges", self.base_url(_connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = coinbase::CoinbaseRouterData::from((amount, req));
let connector_req = coinbase::CoinbasePaymentsRequest::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)?)
.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: coinbase::CoinbasePaymentsResponse = res
.response
.parse_struct("Coinbase 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 Coinbase {
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_id = _req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/charges/{}",
self.base_url(_connectors),
connector_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)?)
.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: coinbase::CoinbasePaymentsResponse = res
.response
.parse_struct("coinbase 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,
})
.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<Capture, PaymentsCaptureData, PaymentsResponseData> for Coinbase {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Coinbase".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Coinbase {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Coinbase {
fn build_request(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refund".to_string(),
connector: "Coinbase".to_string(),
}
.into())
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Coinbase {
// default implementation of build_request method will be executed
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Coinbase {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature =
utils::get_header_key_value("X-CC-Webhook-Signature", request.headers)?;
hex::decode(base64_signature)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let message = std::str::from_utf8(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(message.to_string().into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
.parse_struct("CoinbaseWebhookDetails")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(notif.event.data.id),
))
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
.parse_struct("CoinbaseWebhookDetails")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match notif.event.event_type {
coinbase::WebhookEventType::Confirmed | coinbase::WebhookEventType::Resolved => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
coinbase::WebhookEventType::Failed => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
coinbase::WebhookEventType::Pending => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
}
coinbase::WebhookEventType::Unknown | coinbase::WebhookEventType::Created => {
Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
}
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: CoinbaseWebhookDetails = request
.body
.parse_struct("CoinbaseWebhookDetails")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Box::new(notif.event))
}
}
lazy_static! {
static ref COINBASE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Coinbase",
description:
"Coinbase is a place for people and businesses to buy, sell, and manage crypto.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Beta,
};
static ref COINBASE_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let mut coinbase_supported_payment_methods = SupportedPaymentMethods::new();
coinbase_supported_payment_methods.add(
enums::PaymentMethod::Crypto,
enums::PaymentMethodType::CryptoCurrency,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
coinbase_supported_payment_methods
};
static ref COINBASE_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> =
vec![enums::EventClass::Payments, enums::EventClass::Refunds,];
}
impl ConnectorSpecifications for Coinbase {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*COINBASE_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*COINBASE_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*COINBASE_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/coinbase.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3854
}
|
large_file_-6564876507612847484
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/payme.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use api_models::enums::AuthenticationType;
use common_enums::enums;
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{
AmountConvertor, MinorUnit, MinorUnitForConnector, StringMajorUnit,
StringMajorUnitForConnector, StringMinorUnit, StringMinorUnitForConnector,
},
};
use error_stack::{Report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
CompleteAuthorize, InitPayment, PreProcessing,
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData,
PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, RefundsRouterData,
TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation, PaymentsPreProcessing,
},
configs::Connectors,
disputes::DisputePayload,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType,
PaymentsPreProcessingType, PaymentsSyncType, PaymentsVoidType, RefundExecuteType,
RefundSyncType, Response, TokenizationType,
},
webhooks,
};
use masking::{ExposeInterface, Secret};
use transformers as payme;
use crate::{
types::ResponseRouterData,
utils::{self, ForeignTryFrom, PaymentsPreProcessingRequestData},
};
#[derive(Clone)]
pub struct Payme {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
apple_pay_google_pay_amount_converter:
&'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
amount_converter_webhooks: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Payme {
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
apple_pay_google_pay_amount_converter: &StringMajorUnitForConnector,
amount_converter_webhooks: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Payme {}
impl api::PaymentSession for Payme {}
impl api::PaymentsCompleteAuthorize for Payme {}
impl api::ConnectorAccessToken for Payme {}
impl api::MandateSetup for Payme {}
impl api::PaymentAuthorize for Payme {}
impl api::PaymentSync for Payme {}
impl api::PaymentCapture for Payme {}
impl api::PaymentVoid for Payme {}
impl api::Refund for Payme {}
impl api::RefundExecute for Payme {}
impl api::RefundSync for Payme {}
impl api::PaymentToken for Payme {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Payme
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![(
crate::constants::headers::CONTENT_TYPE.to_string(),
Self::get_content_type(self).to_string().into(),
)];
Ok(header)
}
}
impl ConnectorCommon for Payme {
fn id(&self) -> &'static str {
"payme"
}
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.payme.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<
payme::PaymeErrorResponse,
Report<common_utils::errors::ParsingError>,
> = res.response.parse_struct("PaymeErrorResponse");
match response {
Ok(response_data) => {
event_builder.map(|i| i.set_error_response_body(&response_data));
router_env::logger::info!(connector_response=?response_data);
let status_code = match res.status_code {
500..=511 => 200,
_ => res.status_code,
};
Ok(ErrorResponse {
status_code,
code: response_data.status_error_code.to_string(),
message: response_data.status_error_details.clone(),
reason: Some(format!(
"{}, additional info: {}",
response_data.status_error_details, response_data.status_additional_info
)),
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, "payme")
}
}
}
}
impl ConnectorValidation for Payme {
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(
utils::construct_not_supported_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([
utils::PaymentMethodDataType::Card,
utils::PaymentMethodDataType::ApplePayThirdPartySdk,
]);
utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Payme
{
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(format!(
"{}api/capture-buyer-token",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = payme::CaptureBuyerRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &TokenizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(match req.auth_type {
AuthenticationType::ThreeDs => 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(),
),
AuthenticationType::NoThreeDs => None,
})
}
fn handle_response(
&self,
data: &TokenizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<TokenizationRouterData, errors::ConnectorError>
where
PaymentsResponseData: Clone,
{
let response: payme::CaptureBuyerResponse = res
.response
.parse_struct("Payme CaptureBuyerResponse")
.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> {
// we are always getting 500 in error scenarios
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Payme {}
impl PaymentsPreProcessing for Payme {}
impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
for Payme
{
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> {
Ok(format!("{}api/generate-sale", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsPreProcessingRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let req_amount = req.request.get_minor_amount()?;
let req_currency = req.request.get_currency()?;
let amount = utils::convert_amount(self.amount_converter, req_amount, req_currency)?;
let connector_router_data = payme::PaymeRouterData::try_from((amount, req))?;
let connector_req = payme::GenerateSaleRequest::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> {
let req = Some(
RequestBuilder::new()
.method(Method::Post)
.attach_default_headers()
.headers(PaymentsPreProcessingType::get_headers(
self, req, connectors,
)?)
.url(&PaymentsPreProcessingType::get_url(self, req, connectors)?)
.set_body(PaymentsPreProcessingType::get_request_body(
self, req, connectors,
)?)
.build(),
);
Ok(req)
}
fn handle_response(
&self,
data: &PaymentsPreProcessingRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: payme::GenerateSaleResponse = res
.response
.parse_struct("Payme GenerateSaleResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let req_amount = data.request.get_minor_amount()?;
let req_currency = data.request.get_currency()?;
let apple_pay_amount = utils::convert_amount(
self.apple_pay_google_pay_amount_converter,
req_amount,
req_currency,
)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::foreign_try_from((
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
apple_pay_amount,
))
}
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> {
// we are always getting 500 in error scenarios
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Payme {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Payme {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Payme".to_string())
.into(),
)
}
}
impl ConnectorRedirectResponse for Payme {
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)
}
}
}
}
impl ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Payme
{
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!("{}api/pay-sale", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = payme::Pay3dsRequest::try_from(req)?;
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> {
let response: payme::PaymePaySaleResponse = res
.response
.parse_struct("Payme PaymePaySaleResponse")
.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> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<InitPayment, PaymentsAuthorizeData, PaymentsResponseData> for Payme {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Payme {
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> {
if req.request.mandate_id.is_some() {
// For recurring mandate payments
Ok(format!("{}api/generate-sale", self.base_url(connectors)))
} else {
// For Normal & first mandate payments
Ok(format!("{}api/pay-sale", 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 = payme::PaymeRouterData::try_from((amount, req))?;
let connector_req = payme::PaymePaymentRequest::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: payme::PaymePaySaleResponse = res
.response
.parse_struct("Payme 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)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
// we are always getting 500 in error scenarios
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Payme {
fn get_url(
&self,
_req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/get-sales", self.base_url(connectors)))
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_headers(
&self,
req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = payme::PaymeQuerySaleRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
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: &RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<PSync, PaymentsSyncData, PaymentsResponseData>,
errors::ConnectorError,
>
where
PSync: Clone,
PaymentsSyncData: Clone,
PaymentsResponseData: Clone,
{
let response: payme::PaymePaymentsResponse = res
.response
.parse_struct("PaymePaymentsResponse")
.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_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
// we are always getting 500 in error scenarios
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Payme {
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!("{}api/capture-sale", self.base_url(connectors)))
}
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 = payme::PaymeRouterData::try_from((amount, req))?;
let connector_req = payme::PaymentCaptureRequest::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: payme::PaymePaySaleResponse = res
.response
.parse_struct("Payme 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)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
// we are always getting 500 in error scenarios
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Payme {
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> {
// for void, same endpoint is used as refund for payme
Ok(format!("{}api/refund-sale", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let req_amount =
req.request
.minor_amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "amount",
})?;
let req_currency =
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "amount",
})?;
let amount = utils::convert_amount(self.amount_converter, req_amount, req_currency)?;
let connector_router_data = payme::PaymeRouterData::try_from((amount, req))?;
let connector_req = payme::PaymeVoidRequest::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> {
let request = 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();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: payme::PaymeVoidResponse = res
.response
.parse_struct("PaymeVoidResponse")
.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> {
// we are always getting 500 in error scenarios
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Payme {
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!("{}api/refund-sale", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = payme::PaymeRouterData::try_from((amount, req))?;
let connector_req = payme::PaymeRefundRequest::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: payme::PaymeRefundResponse = res
.response
.parse_struct("PaymeRefundResponse")
.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> {
// we are always getting 500 in error scenarios
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Payme {
fn get_url(
&self,
_req: &RouterData<RSync, RefundsData, RefundsResponseData>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}api/get-transactions", self.base_url(connectors)))
}
fn get_headers(
&self,
req: &RouterData<RSync, RefundsData, RefundsResponseData>,
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_request_body(
&self,
req: &RouterData<RSync, RefundsData, RefundsResponseData>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = payme::PaymeQueryTransactionRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RouterData<RSync, RefundsData, RefundsResponseData>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = 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();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RouterData<RSync, RefundsData, RefundsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RouterData<RSync, RefundsData, RefundsResponseData>, errors::ConnectorError>
where
RSync: Clone,
RefundsData: Clone,
RefundsResponseData: Clone,
{
let response: payme::PaymeQueryTransactionResponse = res
.response
.parse_struct("GetSalesResponse")
.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> {
// we are always getting 500 in error scenarios
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Payme {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::Md5))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let resource =
serde_urlencoded::from_bytes::<payme::WebhookEventDataResourceSignature>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(resource.payme_signature.expose().into_bytes())
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let resource =
serde_urlencoded::from_bytes::<payme::WebhookEventDataResource>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(format!(
"{}{}{}",
String::from_utf8_lossy(&connector_webhook_secrets.secret),
resource.payme_transaction_id,
resource.payme_sale_id
)
.as_bytes()
.to_vec())
}
async fn verify_webhook_source(
&self,
request: &webhooks::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 algorithm = self
.get_webhook_source_verification_algorithm(request)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
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::WebhookSourceVerificationFailed)?;
let mut message = self
.get_webhook_source_verification_message(
request,
merchant_id,
&connector_webhook_secrets,
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let mut message_to_verify = connector_webhook_secrets
.additional_secret
.ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Failed to get additional secrets")?
.expose()
.as_bytes()
.to_vec();
message_to_verify.append(&mut message);
let signature_to_verify = hex::decode(signature)
.change_context(errors::ConnectorError::WebhookResponseEncodingFailed)?;
algorithm
.verify_signature(
&connector_webhook_secrets.secret,
&signature_to_verify,
&message_to_verify,
)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let resource =
serde_urlencoded::from_bytes::<payme::WebhookEventDataResource>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let id = match resource.notify_type {
transformers::NotifyType::SaleComplete
| transformers::NotifyType::SaleAuthorized
| transformers::NotifyType::SaleFailure
| transformers::NotifyType::SaleChargeback
| transformers::NotifyType::SaleChargebackRefund => {
api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
resource.payme_sale_id,
),
)
}
transformers::NotifyType::Refund => api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(
resource.payme_transaction_id,
),
),
};
Ok(id)
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let resource =
serde_urlencoded::from_bytes::<payme::WebhookEventDataResourceEvent>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(api_models::webhooks::IncomingWebhookEvent::from(
resource.notify_type,
))
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let resource =
serde_urlencoded::from_bytes::<payme::WebhookEventDataResource>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
match resource.notify_type {
transformers::NotifyType::SaleComplete
| transformers::NotifyType::SaleAuthorized
| transformers::NotifyType::SaleFailure => {
Ok(Box::new(payme::PaymePaySaleResponse::from(resource)))
}
transformers::NotifyType::Refund => Ok(Box::new(
payme::PaymeQueryTransactionResponse::from(resource),
)),
transformers::NotifyType::SaleChargeback
| transformers::NotifyType::SaleChargebackRefund => Ok(Box::new(resource)),
}
}
fn get_dispute_details(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<DisputePayload, errors::ConnectorError> {
let webhook_object =
serde_urlencoded::from_bytes::<payme::WebhookEventDataResource>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(DisputePayload {
amount: utils::convert_amount(
self.amount_converter_webhooks,
webhook_object.price,
webhook_object.currency,
)?,
currency: webhook_object.currency,
dispute_stage: api_models::enums::DisputeStage::Dispute,
connector_dispute_id: webhook_object.payme_transaction_id,
connector_reason: None,
connector_reason_code: None,
challenge_required_by: None,
connector_status: webhook_object.sale_status.to_string(),
created_at: None,
updated_at: None,
})
}
}
static PAYME_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::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
];
let mut payme_supported_payment_methods = SupportedPaymentMethods::new();
payme_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(),
}
}),
),
},
);
payme_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(),
}
}),
),
},
);
payme_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,
},
);
payme_supported_payment_methods
});
static PAYME_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Payme",
description: "Payme is a payment gateway enabling secure online transactions",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static PAYME_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [
enums::EventClass::Payments,
enums::EventClass::Refunds,
enums::EventClass::Disputes,
];
impl ConnectorSpecifications for Payme {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&PAYME_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*PAYME_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&PAYME_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/payme.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 10490
}
|
large_file_-716775723090442839
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/xendit.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::IncomingWebhookEvent;
use base64::Engine;
use common_enums::{enums, CallConnectorAction, CaptureMethod, PaymentAction, PaymentMethodType};
use common_utils::{
consts::BASE64_ENGINE,
crypto,
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
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, PreProcessing, Session, SetupMandate,
Void,
},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData, SplitRefundsRequest,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundSyncRouterData,
RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, Response},
webhooks,
};
use image::EncodableLayout;
use masking::{Mask, PeekInterface};
use transformers::{self as xendit, XenditEventType, XenditWebhookEvent};
use crate::{
constants::headers,
types::ResponseRouterData,
utils as connector_utils,
utils::{self, PaymentMethodDataType, RefundsRequestData},
};
#[derive(Clone)]
pub struct Xendit {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Xendit {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Xendit {}
impl api::PaymentsPreProcessing for Xendit {}
impl api::PaymentSession for Xendit {}
impl api::ConnectorAccessToken for Xendit {}
impl api::MandateSetup for Xendit {}
impl api::PaymentAuthorize for Xendit {}
impl api::PaymentSync for Xendit {}
impl api::PaymentCapture for Xendit {}
impl api::PaymentVoid for Xendit {}
impl api::Refund for Xendit {}
impl api::RefundExecute for Xendit {}
impl api::RefundSync for Xendit {}
impl api::PaymentToken for Xendit {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Xendit
{
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Xendit
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 Xendit {
fn id(&self) -> &'static str {
"xendit"
}
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.xendit.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = xendit::XenditAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let encoded_api_key = BASE64_ENGINE.encode(format!("{}:", auth.api_key.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 error_response: xendit::XenditErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&error_response));
router_env::logger::info!(connector_response=?error_response);
Ok(ErrorResponse {
code: error_response.error_code.clone(),
message: error_response.message.clone(),
reason: Some(error_response.message.clone()),
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,
})
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Xendit {
fn build_request(
&self,
_req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "Cancel/Void flow".to_string(),
connector: "Xendit",
}
.into())
}
}
impl ConnectorValidation for Xendit {
fn validate_mandate_payment(
&self,
pm_type: Option<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<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Xendit {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Xendit {
//TODO: implement sessions flow
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Xendit {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Xendit {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = self.build_headers(req, connectors)?;
match &req.request.split_payments {
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
common_types::payments::XenditSplitRequest::MultipleSplits(_),
)) => {
if let Ok(PaymentsResponseData::TransactionResponse {
charges:
Some(common_types::payments::ConnectorChargeResponseData::XenditSplitPayment(
common_types::payments::XenditChargeResponseData::MultipleSplits(
xendit_response,
),
)),
..
}) = req.response.as_ref()
{
headers.push((
xendit::auth_headers::WITH_SPLIT_RULE.to_string(),
xendit_response.split_rule_id.clone().into(),
));
if let Some(for_user_id) = &xendit_response.for_user_id {
headers.push((
xendit::auth_headers::FOR_USER_ID.to_string(),
for_user_id.clone().into(),
))
};
};
}
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
common_types::payments::XenditSplitRequest::SingleSplit(single_split_data),
)) => {
headers.push((
xendit::auth_headers::FOR_USER_ID.to_string(),
single_split_data.for_user_id.clone().into(),
));
}
_ => (),
};
Ok(headers)
}
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_requests", 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 = xendit::XenditRouterData::from((amount, req));
let connector_req = xendit::XenditPaymentsRequest::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: xendit::XenditPaymentResponse = res
.response
.parse_struct("XenditPaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let response_integrity_object = connector_utils::get_authorise_integrity_object(
self.amount_converter,
response.amount,
response.currency.to_string().clone(),
)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let new_router_data = RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed);
new_router_data.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
}
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<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
for Xendit
{
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> {
Ok(format!("{}/split_rules", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsPreProcessingRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = xendit::XenditSplitRequestData::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let req = Some(
RequestBuilder::new()
.method(Method::Post)
.attach_default_headers()
.headers(types::PaymentsPreProcessingType::get_headers(
self, req, connectors,
)?)
.url(&types::PaymentsPreProcessingType::get_url(
self, req, connectors,
)?)
.set_body(types::PaymentsPreProcessingType::get_request_body(
self, req, connectors,
)?)
.build(),
);
Ok(req)
}
fn handle_response(
&self,
data: &PaymentsPreProcessingRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> {
let response: xendit::XenditSplitResponse = res
.response
.parse_struct("XenditSplitResponse")
.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 Xendit {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = self.build_headers(req, connectors)?;
match &req.request.split_payments {
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
common_types::payments::XenditSplitRequest::MultipleSplits(xendit_request),
)) => {
if let Some(for_user_id) = &xendit_request.for_user_id {
headers.push((
xendit::auth_headers::FOR_USER_ID.to_string(),
for_user_id.clone().into(),
))
};
}
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
common_types::payments::XenditSplitRequest::SingleSplit(single_split_data),
)) => {
headers.push((
xendit::auth_headers::FOR_USER_ID.to_string(),
single_split_data.for_user_id.clone().into(),
));
}
_ => (),
};
Ok(headers)
}
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
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/payment_requests/{connector_payment_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: xendit::XenditResponse = res
.response
.clone()
.parse_struct("xendit XenditResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let response_integrity_object = match response.clone() {
xendit::XenditResponse::Payment(p) => connector_utils::get_sync_integrity_object(
self.amount_converter,
p.amount,
p.currency.to_string().clone(),
),
xendit::XenditResponse::Webhook(p) => connector_utils::get_sync_integrity_object(
self.amount_converter,
p.data.amount,
p.data.currency.to_string().clone(),
),
};
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let new_router_data = RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
});
new_router_data.and_then(|mut router_data| {
let integrity_object = response_integrity_object?;
router_data.request.integrity_object = Some(integrity_object);
Ok(router_data)
})
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Xendit {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = self.build_headers(req, connectors)?;
match &req.request.split_payments {
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
common_types::payments::XenditSplitRequest::MultipleSplits(xendit_request),
)) => {
if let Some(for_user_id) = &xendit_request.for_user_id {
headers.push((
xendit::auth_headers::FOR_USER_ID.to_string(),
for_user_id.clone().into(),
))
};
}
Some(common_types::payments::SplitPaymentsRequest::XenditSplitPayment(
common_types::payments::XenditSplitRequest::SingleSplit(single_split_data),
)) => {
headers.push((
xendit::auth_headers::FOR_USER_ID.to_string(),
single_split_data.for_user_id.clone().into(),
));
}
_ => (),
};
Ok(headers)
}
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!(
"{}/payment_requests/{connector_payment_id}/captures",
self.base_url(connectors),
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_to_capture = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let authorized_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_payment_amount,
req.request.currency,
)?;
if amount_to_capture != authorized_amount {
Err(report!(errors::ConnectorError::NotSupported {
message: "Partial Capture".to_string(),
connector: "Xendit"
}))
} else {
let connector_router_data = xendit::XenditRouterData::from((amount_to_capture, req));
let connector_req =
xendit::XenditPaymentsCaptureRequest::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(self.get_request_body(req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: xendit::XenditCaptureResponse = res
.response
.parse_struct("Xendit 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,
})
.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 Xendit {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = self.build_headers(req, connectors)?;
if let Some(SplitRefundsRequest::XenditSplitRefund(sub_merchant_data)) =
&req.request.split_refunds
{
headers.push((
xendit::auth_headers::FOR_USER_ID.to_string(),
sub_merchant_data.for_user_id.clone().into(),
));
};
Ok(headers)
}
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 amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = xendit::XenditRouterData::from((amount, req));
let connector_req = xendit::XenditRefundRequest::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: xendit::RefundResponse =
res.response
.parse_struct("xendit RefundResponse")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let response_integrity_object = connector_utils::get_refund_integrity_object(
self.amount_converter,
response.amount,
response.currency.to_string().clone(),
)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let new_router_data = RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
});
new_router_data
.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
.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<RSync, RefundsData, RefundsResponseData> for Xendit {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut headers = self.build_headers(req, connectors)?;
if let Some(SplitRefundsRequest::XenditSplitRefund(sub_merchant_data)) =
&req.request.split_refunds
{
headers.push((
xendit::auth_headers::FOR_USER_ID.to_string(),
sub_merchant_data.for_user_id.clone().into(),
));
};
Ok(headers)
}
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!(
"{}/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)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: xendit::RefundResponse = res
.response
.clone()
.parse_struct("xendit RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let response_integrity_object = connector_utils::get_refund_integrity_object(
self.amount_converter,
response.amount,
response.currency.to_string().clone(),
)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let new_router_data = RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
});
new_router_data
.map(|mut router_data| {
router_data.request.integrity_object = Some(response_integrity_object);
router_data
})
.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 Xendit {
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let header_value = utils::get_header_key_value("X-CALLBACK-TOKEN", request.headers)?;
Ok(header_value.into())
}
async fn verify_webhook_source(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: crypto::Encryptable<masking::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::WebhookSourceVerificationFailed)?;
let secret_key = connector_webhook_secrets.secret;
Ok(secret_key.as_bytes() == (signature).as_bytes())
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(request.body.to_vec())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let details: XenditWebhookEvent = request
.body
.parse_struct("XenditWebhookEvent")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
match details.event {
XenditEventType::PaymentSucceeded
| XenditEventType::PaymentAwaitingCapture
| XenditEventType::PaymentFailed
| XenditEventType::CaptureSucceeded
| XenditEventType::CaptureFailed => {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
details
.data
.payment_request_id
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,
),
))
}
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let body: XenditWebhookEvent = request
.body
.parse_struct("XenditWebhookEvent")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
match body.event {
XenditEventType::PaymentSucceeded => Ok(IncomingWebhookEvent::PaymentIntentSuccess),
XenditEventType::CaptureSucceeded => {
Ok(IncomingWebhookEvent::PaymentIntentCaptureSuccess)
}
XenditEventType::PaymentAwaitingCapture => {
Ok(IncomingWebhookEvent::PaymentIntentAuthorizationSuccess)
}
XenditEventType::PaymentFailed | XenditEventType::CaptureFailed => {
Ok(IncomingWebhookEvent::PaymentIntentFailure)
}
}
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let body: XenditWebhookEvent = request
.body
.parse_struct("XenditWebhookEvent")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(Box::new(body))
}
}
static XENDIT_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![CaptureMethod::Automatic, CaptureMethod::Manual];
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 xendit_supported_payment_methods = SupportedPaymentMethods::new();
xendit_supported_payment_methods.add(
enums::PaymentMethod::Card,
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(),
}
}),
),
},
);
xendit_supported_payment_methods.add(
enums::PaymentMethod::Card,
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(),
}
}),
),
},
);
xendit_supported_payment_methods
});
static XENDIT_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Xendit",
description: "Xendit is a financial technology company that provides payment solutions and simplifies the payment process for businesses in Indonesia, the Philippines and Southeast Asia, from SMEs and e-commerce startups to large enterprises.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static XENDIT_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
impl ConnectorSpecifications for Xendit {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&XENDIT_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*XENDIT_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&XENDIT_SUPPORTED_WEBHOOK_FLOWS)
}
}
impl ConnectorRedirectResponse for Xendit {
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::PaymentAuthenticateCompleteAuthorize
| PaymentAction::CompleteAuthorize => Ok(CallConnectorAction::Trigger),
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/xendit.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 8090
}
|
large_file_3715736886231654683
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/worldpayxml.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_utils::{
errors::CustomResult,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
};
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, 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,
consts, errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask};
use transformers as worldpayxml;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Worldpayxml {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Worldpayxml {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Worldpayxml {}
impl api::PaymentSession for Worldpayxml {}
impl api::ConnectorAccessToken for Worldpayxml {}
impl api::MandateSetup for Worldpayxml {}
impl api::PaymentAuthorize for Worldpayxml {}
impl api::PaymentSync for Worldpayxml {}
impl api::PaymentCapture for Worldpayxml {}
impl api::PaymentVoid for Worldpayxml {}
impl api::Refund for Worldpayxml {}
impl api::RefundExecute for Worldpayxml {}
impl api::RefundSync for Worldpayxml {}
impl api::PaymentToken for Worldpayxml {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Worldpayxml
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Worldpayxml
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.common_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 Worldpayxml {
fn id(&self) -> &'static str {
"worldpayxml"
}
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.worldpayxml.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = worldpayxml::WorldpayxmlAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let basic_auth_value = format!(
"Basic {}",
common_utils::consts::BASE64_ENGINE.encode(format!(
"{}:{}",
auth.api_username.expose(),
auth.api_password.expose()
))
);
Ok(vec![(
headers::AUTHORIZATION.to_string(),
Mask::into_masked(basic_auth_value),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: Result<worldpayxml::PaymentService, _> =
utils::deserialize_xml_to_struct(&res.response);
match response {
Ok(response_data) => {
event_builder.map(|i| i.set_error_response_body(&response_data));
router_env::logger::info!(connector_response=?response_data);
let (error_code, error_msg) = response_data
.reply
.as_ref()
.and_then(|reply| {
reply
.error
.as_ref()
.map(|error| (Some(error.code.clone()), Some(error.message.clone())))
})
.unwrap_or((None, None));
Ok(ErrorResponse {
status_code: res.status_code,
code: error_code.unwrap_or(consts::NO_ERROR_CODE.to_string()),
message: error_msg
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: error_msg.clone(),
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, "worldpayxml")
}
}
}
}
impl ConnectorValidation for Worldpayxml {
fn validate_mandate_payment(
&self,
_pm_type: Option<common_enums::PaymentMethodType>,
_pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
Err(errors::ConnectorError::NotSupported {
message: "mandate payment".to_string(),
connector: "worldpayxml",
}
.into())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Worldpayxml {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Worldpayxml {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Worldpayxml
{
// 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 Worldpayxml".to_string(),
)
.into())
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Worldpayxml {
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 = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = worldpayxml::WorldpayxmlRouterData::from((amount, req));
let connector_req_object = worldpayxml::PaymentService::try_from(&connector_router_data)?;
let connector_req = utils::XmlSerializer::serialize_to_xml_bytes(
&connector_req_object,
worldpayxml::worldpayxml_constants::XML_VERSION,
Some(worldpayxml::worldpayxml_constants::XML_ENCODING),
None,
Some(worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE),
)?;
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> {
let response: worldpayxml::PaymentService =
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 Worldpayxml {
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_owned())
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req_object = worldpayxml::PaymentService::try_from(req)?;
let connector_req = utils::XmlSerializer::serialize_to_xml_bytes(
&connector_req_object,
worldpayxml::worldpayxml_constants::XML_VERSION,
Some(worldpayxml::worldpayxml_constants::XML_ENCODING),
None,
Some(worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE),
)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(types::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: worldpayxml::PaymentService =
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<Capture, PaymentsCaptureData, PaymentsResponseData> for Worldpayxml {
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 = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = worldpayxml::WorldpayxmlRouterData::from((amount, req));
let connector_req_object = worldpayxml::PaymentService::try_from(&connector_router_data)?;
let connector_req = utils::XmlSerializer::serialize_to_xml_bytes(
&connector_req_object,
worldpayxml::worldpayxml_constants::XML_VERSION,
Some(worldpayxml::worldpayxml_constants::XML_ENCODING),
None,
Some(worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE),
)?;
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: worldpayxml::PaymentService =
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 Worldpayxml {
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> {
Ok(self.base_url(connectors).to_owned())
}
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 connector_req_object = worldpayxml::PaymentService::try_from(req)?;
let connector_req = utils::XmlSerializer::serialize_to_xml_bytes(
&connector_req_object,
worldpayxml::worldpayxml_constants::XML_VERSION,
Some(worldpayxml::worldpayxml_constants::XML_ENCODING),
None,
Some(worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE),
)?;
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(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: worldpayxml::PaymentService =
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 Worldpayxml {
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 = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = worldpayxml::WorldpayxmlRouterData::from((refund_amount, req));
let connector_req_object = worldpayxml::PaymentService::try_from(&connector_router_data)?;
let connector_req = utils::XmlSerializer::serialize_to_xml_bytes(
&connector_req_object,
worldpayxml::worldpayxml_constants::XML_VERSION,
Some(worldpayxml::worldpayxml_constants::XML_ENCODING),
None,
Some(worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE),
)?;
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: worldpayxml::PaymentService =
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 Worldpayxml {
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_owned())
}
fn get_request_body(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req_object = worldpayxml::PaymentService::try_from(req)?;
let connector_req = utils::XmlSerializer::serialize_to_xml_bytes(
&connector_req_object,
worldpayxml::worldpayxml_constants::XML_VERSION,
Some(worldpayxml::worldpayxml_constants::XML_ENCODING),
None,
Some(worldpayxml::worldpayxml_constants::WORLDPAYXML_DOC_TYPE),
)?;
Ok(RequestContent::RawBytes(connector_req))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.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: worldpayxml::PaymentService =
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)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Worldpayxml {
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 WORLDPAYXML_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::CartesBancaires,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Maestro,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
];
let mut worldpayxml_supported_payment_methods = SupportedPaymentMethods::new();
worldpayxml_supported_payment_methods.add(
common_enums::PaymentMethod::Card,
common_enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
worldpayxml_supported_payment_methods.add(
common_enums::PaymentMethod::Card,
common_enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
worldpayxml_supported_payment_methods
});
static WORLDPAYXML_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Worldpay XML",
description: "Worldpay is a payment gateway and PSP enabling secure online transactions",
connector_type: common_enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: common_enums::ConnectorIntegrationStatus::Sandbox,
};
static WORLDPAYXML_SUPPORTED_WEBHOOK_FLOWS: [common_enums::EventClass; 0] = [];
impl ConnectorSpecifications for Worldpayxml {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&WORLDPAYXML_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*WORLDPAYXML_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::EventClass]> {
Some(&WORLDPAYXML_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/worldpayxml.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6420
}
|
large_file_-6190506594805585848
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/boku.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::{BytesExt, OptionExt, XmlExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::{
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, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts::NO_ERROR_CODE,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::{ExposeInterface, Mask, PeekInterface, Secret, WithType};
use ring::hmac;
use router_env::logger;
use time::OffsetDateTime;
use transformers as boku;
use crate::{
constants::{headers, UNSUPPORTED_ERROR_MESSAGE},
metrics,
types::ResponseRouterData,
utils::convert_amount,
};
#[derive(Clone)]
pub struct Boku {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Boku {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Boku {}
impl api::PaymentSession for Boku {}
impl api::ConnectorAccessToken for Boku {}
impl api::MandateSetup for Boku {}
impl api::PaymentAuthorize for Boku {}
impl api::PaymentSync for Boku {}
impl api::PaymentCapture for Boku {}
impl api::PaymentVoid for Boku {}
impl api::Refund for Boku {}
impl api::RefundExecute for Boku {}
impl api::RefundSync for Boku {}
impl api::PaymentToken for Boku {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Boku
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Boku
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 connector_auth = boku::BokuAuthType::try_from(&req.connector_auth_type)?;
let boku_url = Self::get_url(self, req, connectors)?;
let content_type = Self::common_get_content_type(self);
let connector_method = Self::get_http_method(self);
let timestamp = OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
let secret_key = boku::BokuAuthType::try_from(&req.connector_auth_type)?
.key_id
.expose();
let to_sign = format!(
"{} {}\nContent-Type: {}\n{}",
connector_method, boku_url, &content_type, timestamp
);
let key = hmac::Key::new(hmac::HMAC_SHA256, secret_key.as_bytes());
let tag = hmac::sign(&key, to_sign.as_bytes());
let signature = hex::encode(tag);
let auth_val = format!("2/HMAC_SHA256(H+SHA256(E)) timestamp={timestamp}, signature={signature} signed-headers=Content-Type, key-id={}", connector_auth.key_id.peek());
let header = vec![
(headers::CONTENT_TYPE.to_string(), content_type.into()),
(headers::AUTHORIZATION.to_string(), auth_val.into_masked()),
];
Ok(header)
}
}
impl ConnectorCommon for Boku {
fn id(&self) -> &'static str {
"boku"
}
fn common_get_content_type(&self) -> &'static str {
"text/xml;charset=utf-8"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.boku.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response_data: Result<boku::BokuErrorResponse, Report<errors::ConnectorError>> = res
.response
.parse_struct("boku::BokuErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed);
match response_data {
Ok(response) => {
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,
})
}
Err(_) => get_xml_deserialized(res, event_builder),
}
}
}
impl ConnectorValidation for Boku {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Boku {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Boku {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Boku {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Boku".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Boku {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_http_method(&self) -> Method {
Method::Post
}
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 boku_url = get_country_url(
req.connector_meta_data.clone(),
self.base_url(connectors).to_string(),
)?;
Ok(format!("{boku_url}/billing/3.0/begin-single-charge"))
}
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 = boku::BokuRouterData::from((amount, req));
let connector_req = boku::BokuPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Xml(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_data = String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let response = response_data
.parse_xml::<boku::BokuResponse>()
.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 Boku {
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 boku_url = get_country_url(
req.connector_meta_data.clone(),
self.base_url(connectors).to_string(),
)?;
Ok(format!("{boku_url}/billing/3.0/query-charge"))
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = boku::BokuPsyncRequest::try_from(req)?;
Ok(RequestContent::Xml(Box::new(connector_req)))
}
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)?)
.set_body(types::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_data = String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let response = response_data
.parse_xml::<boku::BokuResponse>()
.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 Boku {
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_data = String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let response = response_data
.parse_xml::<boku::BokuResponse>()
.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 Boku {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Boku {
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 boku_url = get_country_url(
req.connector_meta_data.clone(),
self.base_url(connectors).to_string(),
)?;
Ok(format!("{boku_url}/billing/3.0/refund-charge"))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = boku::BokuRouterData::from((refund_amount, req));
let connector_req = boku::BokuRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Xml(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: boku::RefundResponse = res
.response
.parse_struct("boku RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_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 Boku {
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 boku_url = get_country_url(
req.connector_meta_data.clone(),
self.base_url(connectors).to_string(),
)?;
Ok(format!("{boku_url}/billing/3.0/query-refund"))
}
fn get_request_body(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = boku::BokuRsyncRequest::try_from(req)?;
Ok(RequestContent::Xml(Box::new(connector_req)))
}
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: boku::BokuRsyncResponse = res
.response
.parse_struct("boku BokuRsyncResponse")
.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 Boku {
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> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
fn get_country_url(
meta_data: Option<Secret<serde_json::Value, WithType>>,
base_url: String,
) -> Result<String, Report<errors::ConnectorError>> {
let conn_meta_data: boku::BokuMetaData = meta_data
.parse_value("Object")
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(base_url.replace('$', &conn_meta_data.country.to_lowercase()))
}
// validate xml format for the error
fn get_xml_deserialized(
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
metrics::CONNECTOR_RESPONSE_DESERIALIZATION_FAILURE
.add(1, router_env::metric_attributes!(("connector", "boku")));
let response_data = String::from_utf8(res.response.to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response_data));
router_env::logger::info!(connector_response=?response_data);
// check for whether the response is in xml format
match roxmltree::Document::parse(&response_data) {
// in case of unexpected response but in xml format
Ok(_) => Err(errors::ConnectorError::ResponseDeserializationFailed)?,
// in case of unexpected response but in html or string format
Err(_) => {
logger::error!("UNEXPECTED RESPONSE FROM CONNECTOR: {}", response_data);
Ok(ErrorResponse {
status_code: res.status_code,
code: 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,
})
}
}
}
static BOKU_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let mut boku_supported_payment_methods = SupportedPaymentMethods::new();
boku_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Dana,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
boku_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Gcash,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
boku_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GoPay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
boku_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::KakaoPay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
boku_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Momo,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
boku_supported_payment_methods
});
static BOKU_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Boku",
description: "Boku, Inc. is a mobile payments company that allows businesses to collect online payments through both carrier billing and mobile wallets.",
connector_type: enums::HyperswitchConnectorCategory::AlternativePaymentMethod,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static BOKU_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Boku {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&BOKU_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BOKU_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&BOKU_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/boku.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5914
}
|
large_file_3531990826409936829
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/paystack.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use common_enums::enums;
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::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, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
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 paystack;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Paystack {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Paystack {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Paystack {}
impl api::PaymentSession for Paystack {}
impl api::ConnectorAccessToken for Paystack {}
impl api::MandateSetup for Paystack {}
impl api::PaymentAuthorize for Paystack {}
impl api::PaymentSync for Paystack {}
impl api::PaymentCapture for Paystack {}
impl api::PaymentVoid for Paystack {}
impl api::Refund for Paystack {}
impl api::RefundExecute for Paystack {}
impl api::RefundSync for Paystack {}
impl api::PaymentToken for Paystack {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Paystack
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paystack
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 Paystack {
fn id(&self) -> &'static str {
"paystack"
}
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.paystack.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = paystack::PaystackAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", auth.api_key.expose()).into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: paystack::PaystackErrorResponse = res
.response
.parse_struct("PaystackErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_message = paystack::get_error_message(response.clone());
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
message: error_message,
reason: Some(response.message),
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 Paystack {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Paystack {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Paystack {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Paystack
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paystack {
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!("{}/charge", 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 = paystack::PaystackRouterData::from((amount, req));
let connector_req = paystack::PaystackPaymentsRequest::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: paystack::PaystackPaymentsResponse = res
.response
.parse_struct("Paystack 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 Paystack {
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
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"/transaction/verify/",
connector_payment_id,
))
}
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: paystack::PaystackPSyncResponse = res
.response
.parse_struct("paystack 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 Paystack {
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: paystack::PaystackPaymentsResponse = res
.response
.parse_struct("Paystack 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 Paystack {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paystack {
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!("{}/refund", 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 = paystack::PaystackRouterData::from((refund_amount, req));
let connector_req = paystack::PaystackRefundRequest::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: paystack::PaystackRefundsResponse = res
.response
.parse_struct("paystack 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 Paystack {
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
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"/refund/",
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: paystack::PaystackRefundsResponse = res
.response
.parse_struct("paystack 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 Paystack {
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: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let signature = utils::get_header_key_value("x-paystack-signature", request.headers)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
hex::decode(signature)
.change_context(errors::ConnectorError::WebhookVerificationSecretInvalid)
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let message = std::str::from_utf8(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(message.to_string().into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook_body = request
.body
.parse_struct::<paystack::PaystackWebhookData>("PaystackWebhookData")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
match webhook_body.data {
paystack::PaystackWebhookEventData::Payment(data) => {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(data.reference),
))
}
paystack::PaystackWebhookEventData::Refund(data) => {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(data.id),
))
}
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let webhook_body = request
.body
.parse_struct::<paystack::PaystackWebhookData>("PaystackWebhookData")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(api_models::webhooks::IncomingWebhookEvent::from(
webhook_body.data,
))
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook_body = request
.body
.parse_struct::<paystack::PaystackWebhookData>("PaystackWebhookData")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(match webhook_body.data {
paystack::PaystackWebhookEventData::Payment(payment_webhook_data) => {
Box::new(payment_webhook_data)
}
paystack::PaystackWebhookEventData::Refund(refund_webhook_data) => {
Box::new(refund_webhook_data)
}
})
}
}
static PAYSTACK_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::SequentialAutomatic,
];
let mut paystack_supported_payment_methods = SupportedPaymentMethods::new();
paystack_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Eft,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
paystack_supported_payment_methods
});
static PAYSTACK_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Paystack",
description: "Paystack is a Nigerian financial technology company that provides online and offline payment solutions to businesses across Africa.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static PAYSTACK_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] =
[enums::EventClass::Payments, enums::EventClass::Refunds];
impl ConnectorSpecifications for Paystack {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&PAYSTACK_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*PAYSTACK_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&PAYSTACK_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/paystack.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5304
}
|
large_file_2855684322348934504
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/nomupay.rs
</path>
<file>
pub mod transformers;
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
pii,
request::{Method, RequestContent},
};
#[cfg(feature = "payouts")]
use common_utils::{
request::{Request, RequestBuilder},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
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,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::payouts::{
PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient, PoRecipientAccount,
PoSync,
},
router_request_types::PayoutsData,
router_response_types::PayoutsResponseData,
types::PayoutsRouterData,
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::types;
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
events::connector_api_logs::ConnectorEvent,
types::Response,
webhooks,
};
use josekit::{
jws::{self, JwsHeader, ES256},
jwt::{self, JwtPayload},
Map, Value,
};
use masking::{ExposeInterface, Mask};
#[cfg(feature = "payouts")]
use router_env::{instrument, tracing};
use serde_json::json;
use transformers as nomupay;
use crate::{constants::headers, utils};
#[cfg(feature = "payouts")]
use crate::{types::ResponseRouterData, utils::RouterData as RouterDataTrait};
#[derive(Clone)]
pub struct Nomupay {
#[cfg(feature = "payouts")]
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Nomupay {
pub fn new() -> &'static Self {
&Self {
#[cfg(feature = "payouts")]
amount_converter: &FloatMajorUnitForConnector,
}
}
}
fn get_private_key(
metadata: &Option<pii::SecretSerdeValue>,
) -> Result<String, errors::ConnectorError> {
match nomupay::NomupayMetadata::try_from(metadata.as_ref()) {
Ok(nomupay_metadata) => Ok(nomupay_metadata.private_key.expose()),
Err(_e) => Err(errors::ConnectorError::NoConnectorMetaData),
}
}
fn box_to_jwt_payload(
body: Box<dyn masking::ErasedMaskSerialize + Send>,
) -> CustomResult<JwtPayload, errors::ConnectorError> {
let str_result = serde_json::to_string(&body)
.change_context(errors::ConnectorError::ProcessingStepFailed(None))?;
let parsed_json: Map<String, Value> = serde_json::from_str(&str_result)
.change_context(errors::ConnectorError::ProcessingStepFailed(None))?;
let jwt_payload = JwtPayload::from_map(parsed_json)
.change_context(errors::ConnectorError::ProcessingStepFailed(None))?;
Ok(jwt_payload)
}
fn get_signature(
metadata: &Option<pii::SecretSerdeValue>,
auth: nomupay::NomupayAuthType,
body: RequestContent,
method: &str,
path: String,
) -> CustomResult<String, errors::ConnectorError> {
match body {
RequestContent::Json(masked_json) => {
let expiration_time = SystemTime::now() + Duration::from_secs(4 * 60);
let expires_in = match expiration_time.duration_since(UNIX_EPOCH) {
Ok(duration) => duration.as_secs(),
Err(_e) => 0,
};
let mut option_map = Map::new();
option_map.insert("alg".to_string(), json!(format!("ES256")));
option_map.insert("aud".to_string(), json!(format!("{} {}", method, path)));
option_map.insert("exp".to_string(), json!(expires_in));
option_map.insert("kid".to_string(), json!(auth.kid));
let header = JwsHeader::from_map(option_map)
.change_context(errors::ConnectorError::ProcessingStepFailed(None))?;
let payload = match method {
"GET" => JwtPayload::new(),
_ => box_to_jwt_payload(masked_json)
.change_context(errors::ConnectorError::ProcessingStepFailed(None))?,
};
let private_key = get_private_key(metadata)?;
let signer = ES256
.signer_from_pem(&private_key)
.change_context(errors::ConnectorError::ProcessingStepFailed(None))?;
let nomupay_jwt = match method {
"GET" => jws::serialize_compact(b"", &header, &signer)
.change_context(errors::ConnectorError::ProcessingStepFailed(None))?,
_ => jwt::encode_with_signer(&payload, &header, &signer)
.change_context(errors::ConnectorError::ProcessingStepFailed(None))?,
};
let jws_blocks: Vec<&str> = nomupay_jwt.split('.').collect();
let jws_detached = jws_blocks
.first()
.zip(jws_blocks.get(2))
.map(|(first, third)| format!("{first}..{third}"))
.ok_or_else(|| errors::ConnectorError::MissingRequiredField {
field_name: "JWS blocks not sufficient for detached payload",
})?;
Ok(jws_detached)
}
_ => Err(errors::ConnectorError::ProcessingStepFailed(None).into()),
}
}
impl api::Payment for Nomupay {}
impl api::PaymentSession for Nomupay {}
impl api::ConnectorAccessToken for Nomupay {}
impl api::MandateSetup for Nomupay {}
impl api::PaymentAuthorize for Nomupay {}
impl api::PaymentSync for Nomupay {}
impl api::PaymentCapture for Nomupay {}
impl api::PaymentVoid for Nomupay {}
impl api::Refund for Nomupay {}
impl api::RefundExecute for Nomupay {}
impl api::RefundSync for Nomupay {}
impl api::PaymentToken for Nomupay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Nomupay
{
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nomupay
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 is_post_req = matches!(self.get_http_method(), Method::Post);
let body = self.get_request_body(req, connectors)?;
let auth = nomupay::NomupayAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let base_url = connectors.nomupay.base_url.as_str();
let path: String = self
.get_url(req, connectors)?
.chars()
.skip(base_url.len())
.collect();
let req_method = if is_post_req { "POST" } else { "GET" };
let sign = get_signature(&req.connector_meta_data, auth, body, req_method, path)?;
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
header.push((
headers::X_SIGNATURE.to_string(),
masking::Maskable::Normal(sign),
));
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl TryFrom<Option<&pii::SecretSerdeValue>> for nomupay::NomupayMetadata {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(meta_data: Option<&pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let metadata: Self = utils::to_connector_meta_from_secret::<Self>(meta_data.cloned())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata",
})?;
Ok(metadata)
}
}
impl ConnectorCommon for Nomupay {
fn id(&self) -> &'static str {
"nomupay"
}
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.nomupay.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = nomupay::NomupayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.kid.expose().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: nomupay::NomupayErrorResponse = res
.response
.parse_struct("NomupayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
match (
response.status,
response.code,
response.error,
response.status_code,
response.detail,
) {
(Some(status), Some(code), _, _, _) => Ok(ErrorResponse {
status_code: res.status_code,
code: code.to_string(),
message: status,
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
(None, None, Some(nomupay_inner_error), _, _) => {
match (
nomupay_inner_error.error_description,
nomupay_inner_error.validation_errors,
) {
(Some(error_description), _) => Ok(ErrorResponse {
status_code: res.status_code,
code: nomupay_inner_error.error_code,
message: error_description,
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
(_, Some(validation_errors)) => Ok(ErrorResponse {
status_code: res.status_code,
code: nomupay_inner_error.error_code,
message: validation_errors
.first()
.map(|m| m.message.clone())
.unwrap_or_default(),
reason: Some(
validation_errors
.first()
.map(|m| m.field.clone())
.unwrap_or_default(),
),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
(None, None) => Ok(ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
}
}
(None, None, None, Some(status_code), Some(detail)) => Ok(ErrorResponse {
status_code,
code: detail
.get(1)
.map(|d| d.error_type.clone())
.unwrap_or_default(),
message: status_code.to_string(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
_ => Ok(ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: None,
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 Nomupay {}
impl ConnectorRedirectResponse for Nomupay {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nomupay {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nomupay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Nomupay {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nomupay {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nomupay {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nomupay {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Nomupay {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Nomupay {}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Nomupay {}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> for Nomupay {}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> for Nomupay {}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> for Nomupay {}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData> for Nomupay {}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> for Nomupay {
fn get_url(
&self,
req: &PayoutsRouterData<PoSync>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let nomupay_payout_id = req
.request
.connector_payout_id
.clone()
.ok_or_else(utils::missing_field_err("connector_payout_id"))?;
Ok(format!(
"{}/v1alpha1/payments/{}",
self.base_url(connectors),
nomupay_payout_id
))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoSync>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn build_request(
&self,
req: &PayoutsRouterData<PoSync>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Get)
.url(&types::PayoutSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PayoutSyncType::get_headers(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoSync>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoSync>, errors::ConnectorError> {
let response: nomupay::NomupayPaymentResponse = res
.response
.parse_struct("NomupayPaymentResponse")
.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)
}
}
#[cfg(feature = "payouts")]
impl api::Payouts for Nomupay {}
#[cfg(feature = "payouts")]
impl api::PayoutCancel for Nomupay {}
#[cfg(feature = "payouts")]
impl api::PayoutCreate for Nomupay {}
#[cfg(feature = "payouts")]
impl api::PayoutEligibility for Nomupay {}
#[cfg(feature = "payouts")]
impl api::PayoutFulfill for Nomupay {}
#[cfg(feature = "payouts")]
impl api::PayoutQuote for Nomupay {}
#[cfg(feature = "payouts")]
impl api::PayoutRecipient for Nomupay {}
#[cfg(feature = "payouts")]
impl api::PayoutRecipientAccount for Nomupay {}
#[cfg(feature = "payouts")]
impl api::PayoutSync for Nomupay {}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData> for Nomupay {
fn get_url(
&self,
_req: &PayoutsRouterData<PoRecipient>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/v1alpha1/sub-account",
connectors.nomupay.base_url
))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoRecipient>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoRecipient>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nomupay::OnboardSubAccountRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoRecipient>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::PayoutRecipientType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PayoutRecipientType::get_headers(
self, req, connectors,
)?)
.set_body(types::PayoutRecipientType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PayoutsRouterData<PoRecipient>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoRecipient>, errors::ConnectorError> {
let response: nomupay::OnboardSubAccountResponse = res
.response
.parse_struct("OnboardSubAccountResponse")
.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)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoRecipientAccount, PayoutsData, PayoutsResponseData> for Nomupay {
fn get_url(
&self,
req: &PayoutsRouterData<PoRecipientAccount>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let sid = req.get_connector_customer_id()?;
Ok(format!(
"{}/v1alpha1/sub-account/{}/transfer-method",
connectors.nomupay.base_url, sid
))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoRecipientAccount>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoRecipientAccount>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nomupay::OnboardTransferMethodRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoRecipientAccount>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::PayoutRecipientAccountType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PayoutRecipientAccountType::get_headers(
self, req, connectors,
)?)
.set_body(types::PayoutRecipientAccountType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PayoutsRouterData<PoRecipientAccount>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoRecipientAccount>, errors::ConnectorError> {
let response: nomupay::OnboardTransferMethodResponse = res
.response
.parse_struct("OnboardTransferMethodResponse")
.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)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Nomupay {
fn get_url(
&self,
_req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/v1alpha1/payments", connectors.nomupay.base_url))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoFulfill>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.destination_currency,
)?;
let connector_req = nomupay::NomupayPaymentRequest::try_from((req, amount))?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PayoutFulfillType::get_headers(
self, req, connectors,
)?)
.set_body(types::PayoutFulfillType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PayoutsRouterData<PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoFulfill>, errors::ConnectorError> {
let response: nomupay::NomupayPaymentResponse = res
.response
.parse_struct("NomupayPaymentResponse")
.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 Nomupay {
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 NOMUPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Nomupay",
description: "Nomupay payouts connector for disbursements to recipients' bank accounts and alternative payment methods in Southeast Asia and the Pacific Islands",
connector_type: common_enums::HyperswitchConnectorCategory::PayoutProcessor,
integration_status: common_enums::ConnectorIntegrationStatus::Sandbox,
};
impl ConnectorSpecifications for Nomupay {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&NOMUPAY_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
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/nomupay.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6267
}
|
large_file_5975904626851594032
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/inespay.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
crypto,
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::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, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
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, Secret};
use ring::hmac;
use transformers as inespay;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Inespay {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Inespay {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Inespay {}
impl api::PaymentSession for Inespay {}
impl api::ConnectorAccessToken for Inespay {}
impl api::MandateSetup for Inespay {}
impl api::PaymentAuthorize for Inespay {}
impl api::PaymentSync for Inespay {}
impl api::PaymentCapture for Inespay {}
impl api::PaymentVoid for Inespay {}
impl api::Refund for Inespay {}
impl api::RefundExecute for Inespay {}
impl api::RefundSync for Inespay {}
impl api::PaymentToken for Inespay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Inespay
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Inespay
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 auth_headers = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut auth_headers);
Ok(header)
}
}
impl ConnectorCommon for Inespay {
fn id(&self) -> &'static str {
"inespay"
}
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.inespay.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = inespay::InespayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![
(
headers::AUTHORIZATION.to_string(),
auth.authorization.expose().into_masked(),
),
(
headers::X_API_KEY.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: inespay::InespayErrorResponse = res
.response
.parse_struct("InespayErrorResponse")
.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.status,
message: response.status_desc,
reason: None,
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 Inespay {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Inespay {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Inespay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Inespay {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Inespay {
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!("{}/payins/single/init", 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,
)?;
match req.request.currency {
common_enums::Currency::EUR => {
let connector_router_data = inespay::InespayRouterData::from((amount, req));
let connector_req =
inespay::InespayPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
_ => Err(errors::ConnectorError::CurrencyNotSupported {
message: req.request.currency.to_string(),
connector: "Inespay",
}
.into()),
}
}
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: inespay::InespayPaymentsResponse = res
.response
.parse_struct("Inespay 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 Inespay {
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
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"/payins/single/",
connector_payment_id,
))
}
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: inespay::InespayPSyncResponse = res
.response
.parse_struct("inespay 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 Inespay {
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: inespay::InespayPaymentsResponse = res
.response
.parse_struct("Inespay 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 Inespay {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Inespay {
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!("{}/refunds/init", 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 = inespay::InespayRouterData::from((refund_amount, req));
let connector_req = inespay::InespayRefundRequest::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: inespay::InespayRefundsResponse = res
.response
.parse_struct("inespay InespayRefundsResponse")
.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 Inespay {
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
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
Ok(format!(
"{}{}{}",
self.base_url(connectors),
"/refunds/",
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: inespay::InespayRSyncResponse = res
.response
.parse_struct("inespay 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)
}
}
fn get_webhook_body(
body: &[u8],
) -> CustomResult<inespay::InespayWebhookEventData, errors::ConnectorError> {
let notif_item: inespay::InespayWebhookEvent =
serde_urlencoded::from_bytes::<inespay::InespayWebhookEvent>(body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let encoded_data_return = notif_item.data_return;
let decoded_data_return = BASE64_ENGINE
.decode(encoded_data_return)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let data_return: inespay::InespayWebhookEventData = decoded_data_return
.parse_struct("inespay InespayWebhookEventData")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(data_return)
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Inespay {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let notif_item = serde_urlencoded::from_bytes::<inespay::InespayWebhookEvent>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(notif_item.signature_data_return.as_bytes().to_owned())
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let notif_item = serde_urlencoded::from_bytes::<inespay::InespayWebhookEvent>(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(notif_item.data_return.into_bytes())
}
async fn verify_webhook_source(
&self,
request: &webhooks::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?;
let signature =
self.get_webhook_source_verification_signature(request, &connector_webhook_secrets)?;
let message = self.get_webhook_source_verification_message(
request,
merchant_id,
&connector_webhook_secrets,
)?;
let secret = connector_webhook_secrets.secret;
let signing_key = hmac::Key::new(hmac::HMAC_SHA256, &secret);
let signed_message = hmac::sign(&signing_key, &message);
let computed_signature = hex::encode(signed_message.as_ref());
let payload_sign = BASE64_ENGINE.encode(computed_signature);
Ok(payload_sign.as_bytes().eq(&signature))
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let data_return = get_webhook_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
match data_return {
inespay::InespayWebhookEventData::Payment(data) => {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
data.single_payin_id,
),
))
}
inespay::InespayWebhookEventData::Refund(data) => {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(data.refund_id),
))
}
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let data_return = get_webhook_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(api_models::webhooks::IncomingWebhookEvent::from(
data_return,
))
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let data_return = get_webhook_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(match data_return {
inespay::InespayWebhookEventData::Payment(payment_webhook_data) => {
Box::new(payment_webhook_data)
}
inespay::InespayWebhookEventData::Refund(refund_webhook_data) => {
Box::new(refund_webhook_data)
}
})
}
}
static INESPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
let mut inespay_supported_payment_methods = SupportedPaymentMethods::new();
inespay_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
enums::PaymentMethodType::Sepa,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
inespay_supported_payment_methods
});
static INESPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Inespay",
description:
"INESPAY is a payment method system that allows online shops to receive money in their bank accounts through a SEPA bank transfer ",
connector_type: enums::HyperswitchConnectorCategory::BankAcquirer,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static INESPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] =
[enums::EventClass::Payments, enums::EventClass::Refunds];
impl ConnectorSpecifications for Inespay {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&INESPAY_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*INESPAY_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&INESPAY_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/inespay.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5903
}
|
large_file_-7653283577704016577
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/dwolla.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use base64::engine::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
crypto,
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ErrorResponse, PaymentMethodToken as PMT, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
CreateConnectorCustomer,
},
router_request_types::{
AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, ResponseId, SetupMandateRequestData,
},
router_response_types::{
ConnectorCustomerResponseData, ConnectorInfo, PaymentMethodDetails, PaymentsResponseData,
RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsSyncRouterData,
RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, RefreshTokenType, Response, TokenizationType},
webhooks,
};
use masking::{ExposeInterface, Mask, Secret};
use ring::hmac;
use transformers as dwolla;
use transformers::extract_token_from_body;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{convert_amount, get_http_header, RefundsRequestData, RouterData as RD},
};
#[derive(Clone)]
pub struct Dwolla {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Dwolla {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl api::ConnectorCustomer for Dwolla {}
impl api::Payment for Dwolla {}
impl api::PaymentSession for Dwolla {}
impl api::ConnectorAccessToken for Dwolla {}
impl api::MandateSetup for Dwolla {}
impl api::PaymentAuthorize for Dwolla {}
impl api::PaymentSync for Dwolla {}
impl api::PaymentCapture for Dwolla {}
impl api::PaymentVoid for Dwolla {}
impl api::Refund for Dwolla {}
impl api::RefundExecute for Dwolla {}
impl api::RefundSync for Dwolla {}
impl api::PaymentToken for Dwolla {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Dwolla
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 header = vec![
(
headers::CONTENT_TYPE.to_string(),
self.common_get_content_type().to_string().into(),
),
(
headers::ACCEPT.to_string(),
self.common_get_content_type().to_string().into(),
),
(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", access_token.token.expose()).into_masked(),
),
(
headers::IDEMPOTENCY_KEY.to_string(),
uuid::Uuid::new_v4().to_string().into(),
),
];
Ok(header)
}
}
impl ConnectorCommon for Dwolla {
fn id(&self) -> &'static str {
"dwolla"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/vnd.dwolla.v1.hal+json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.dwolla.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: dwolla::DwollaErrorResponse = res
.response
.parse_struct("DwollaErrorResponse")
.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
._embedded
.as_ref()
.and_then(|errors_vec| errors_vec.first())
.and_then(|details| details.errors.first())
.and_then(|err_detail| err_detail.message.clone()),
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 Dwolla {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Dwolla {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Dwolla {
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/token", self.base_url(connectors)))
}
fn get_headers(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = dwolla::DwollaAuthType::try_from(&req.connector_auth_type)?;
let mut headers = vec![(
headers::CONTENT_TYPE.to_string(),
"application/x-www-form-urlencoded".to_string().into(),
)];
let auth_str = format!(
"{}:{}",
auth.client_id.expose(),
auth.client_secret.expose()
);
let encoded = BASE64_ENGINE.encode(auth_str);
let auth_header_value = format!("Basic {encoded}");
headers.push((
headers::AUTHORIZATION.to_string(),
auth_header_value.into_masked(),
));
Ok(headers)
}
fn build_request(
&self,
req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let headers = self.get_headers(req, connectors)?;
let connector_req = dwolla::DwollaAccessTokenRequest {
grant_type: "client_credentials".to_string(),
};
let body = RequestContent::FormUrlEncoded(Box::new(connector_req));
let req = Some(
RequestBuilder::new()
.method(Method::Post)
.headers(headers)
.url(&RefreshTokenType::get_url(self, req, connectors)?)
.set_body(body)
.build(),
);
Ok(req)
}
fn handle_response(
&self,
data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: dwolla::DwollaAccessTokenResponse = res
.response
.parse_struct("Dwolla DwollaAccessTokenResponse")
.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 Dwolla
{
fn get_url(
&self,
_req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/customers", self.base_url(connectors)))
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_headers(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
req: &ConnectorCustomerRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = dwolla::DwollaCustomerRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = 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(),
);
Ok(request)
}
fn handle_response(
&self,
data: &ConnectorCustomerRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<ConnectorCustomerRouterData, errors::ConnectorError> {
let headers = res
.headers
.as_ref()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let location = get_http_header("Location", headers)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let connector_customer_id = location
.split('/')
.next_back()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?
.to_string();
let response = serde_json::json!({"connector_customer_id": connector_customer_id.clone()});
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(RouterData {
connector_customer: Some(connector_customer_id.clone()),
response: Ok(PaymentsResponseData::ConnectorCustomerResponse(
ConnectorCustomerResponseData::new_with_customer_id(connector_customer_id),
)),
..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<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Dwolla
{
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> {
let customer_id = req.get_connector_customer_id()?;
Ok(format!(
"{}/customers/{}/funding-sources",
self.base_url(connectors),
customer_id
))
}
fn get_request_body(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = dwolla::DwollaFundingSourceRequest::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> {
let token = res
.headers
.as_ref()
.and_then(|headers| get_http_header("Location", headers).ok())
.and_then(|location| location.rsplit('/').next().map(|s| s.to_string()))
.ok_or_else(|| report!(errors::ConnectorError::ResponseHandlingFailed))?;
let response = serde_json::json!({ "payment_token": token });
if let Some(builder) = event_builder {
builder.set_response_body(&response);
}
router_env::logger::info!(connector_response=?response);
Ok(RouterData {
payment_method_token: Some(PMT::Token(token.clone().into())),
response: Ok(PaymentsResponseData::TokenizationResponse { token }),
..data.clone()
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
if let Ok(body) = std::str::from_utf8(&res.response) {
if res.status_code == 400 && body.contains("Duplicate") {
let token = extract_token_from_body(&res.response);
let metadata = Some(Secret::new(
serde_json::json!({ "payment_method_token": token? }),
));
let response: dwolla::DwollaErrorResponse = res
.response
.parse_struct("DwollaErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
return Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
message: response.message,
reason: response
._embedded
.as_ref()
.and_then(|errors_vec| errors_vec.first())
.and_then(|details| details.errors.first())
.and_then(|err_detail| err_detail.message.clone()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: metadata,
});
}
}
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Dwolla {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Dwolla {
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!("{}/transfers", self.base_url(connectors)))
}
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 =
dwolla::DwollaRouterData::try_from((amount, req, self.base_url(connectors)))?;
let connector_req = dwolla::DwollaPaymentsRequest::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 headers = res
.headers
.as_ref()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let location = get_http_header("Location", headers)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let payment_id = location
.split('/')
.next_back()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?
.to_string();
let response = serde_json::json!({"payment_id : ": payment_id.clone()});
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let connector_metadata = data
.payment_method_token
.as_ref()
.and_then(|token| match token {
PMT::Token(t) => Some(serde_json::json!({ "payment_token": t.clone().expose() })),
_ => None,
});
Ok(RouterData {
payment_method_token: data.payment_method_token.clone(),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(payment_id.clone()),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: Some(payment_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
amount_captured: Some(data.request.amount),
..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<PSync, PaymentsSyncData, PaymentsResponseData> for Dwolla {
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
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/transfers/{}",
self.base_url(connectors),
connector_payment_id.clone()
))
}
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: dwolla::DwollaPSyncResponse = res
.response
.parse_struct("dwolla DwollaPSyncResponse")
.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 Dwolla {
//Not implemented for Dwolla
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Dwolla {
//Not implemented for Dwolla
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Dwolla {
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!("{}/transfers", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_in_minor_unit = MinorUnit::new(req.request.refund_amount);
let amount = convert_amount(
self.amount_converter,
amount_in_minor_unit,
req.request.currency,
)?;
let connector_router_data =
dwolla::DwollaRouterData::try_from((amount, req, self.base_url(connectors)))?;
let connector_req = dwolla::DwollaRefundsRequest::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> {
Ok(Some(
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(),
))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let headers = res
.headers
.as_ref()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?;
let location = get_http_header("Location", headers)
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let refund_id = location
.split('/')
.next_back()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?
.to_string();
let response = serde_json::json!({"refund_id : ": refund_id.clone()});
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(RouterData {
response: Ok(RefundsResponseData {
connector_refund_id: refund_id.clone(),
refund_status: enums::RefundStatus::Pending,
}),
..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<RSync, RefundsData, RefundsResponseData> for Dwolla {
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!(
"{}/transfers/{}",
self.base_url(connectors),
connector_refund_id.clone()
))
}
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: dwolla::DwollaRSyncResponse = res
.response
.parse_struct("dwolla DwollaRSyncResponse")
.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 Dwolla {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let sig = request
.headers
.get("X-Request-Signature-SHA-256")
.and_then(|hv| hv.to_str().ok())
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)?;
hex::decode(sig).map_err(|_| errors::ConnectorError::WebhookSignatureNotFound.into())
}
async fn verify_webhook_source(
&self,
request: &webhooks::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_name: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_webhook_secrets = self
.get_webhook_source_verification_merchant_secret(
merchant_id,
connector_name,
connector_webhook_details,
)
.await?;
let signature = self
.get_webhook_source_verification_signature(request, &connector_webhook_secrets)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
let secret_bytes = connector_webhook_secrets.secret.as_ref();
let key = hmac::Key::new(hmac::HMAC_SHA256, secret_bytes);
let verify = hmac::verify(&key, request.body, &signature)
.map(|_| true)
.map_err(|_| errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(verify)
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let details: dwolla::DwollaWebhookDetails = request
.body
.parse_struct("DwollaWebhookDetails")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
if let Some(correlation_id) = &details.correlation_id {
if correlation_id.starts_with("refund_") {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(
details.resource_id.clone(),
),
))
} else if correlation_id.starts_with("payment_") {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
details.resource_id.clone(),
),
))
} else {
Err(report!(errors::ConnectorError::WebhookReferenceIdNotFound))
}
} else {
Err(report!(errors::ConnectorError::WebhookReferenceIdNotFound))
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let details: dwolla::DwollaWebhookDetails = request
.body
.parse_struct("DwollaWebhookDetails")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
let incoming = api_models::webhooks::IncomingWebhookEvent::try_from(details)?;
Ok(incoming)
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let details: dwolla::DwollaWebhookDetails = request
.body
.parse_struct("DwollaWebhookDetails")
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(details))
}
}
static DWOLLA_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::SequentialAutomatic,
];
let mut dwolla_supported_payment_methods = SupportedPaymentMethods::new();
dwolla_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,
},
);
dwolla_supported_payment_methods
});
static DWOLLA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Dwolla",
description: "Dwolla is a multinational financial technology company offering financial services and software as a service (SaaS)",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Beta,
};
static DWOLLA_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] =
[enums::EventClass::Payments, enums::EventClass::Refunds];
impl ConnectorSpecifications for Dwolla {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&DWOLLA_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*DWOLLA_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&DWOLLA_SUPPORTED_WEBHOOK_FLOWS)
}
fn should_call_connector_customer(
&self,
_payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> bool {
true
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/dwolla.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7509
}
|
large_file_4060618980769851253
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/authipay.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
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, 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, PeekInterface};
use transformers as authipay;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Authipay {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Authipay {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
pub fn generate_authorization_signature(
&self,
auth: authipay::AuthipayAuthType,
request_id: &str,
payload: &str,
timestamp: i128,
) -> CustomResult<String, errors::ConnectorError> {
let authipay::AuthipayAuthType {
api_key,
api_secret,
} = auth;
let raw_signature = format!("{}{request_id}{timestamp}{payload}", api_key.peek());
let key = ring::hmac::Key::new(ring::hmac::HMAC_SHA256, api_secret.expose().as_bytes());
let signature_value = common_utils::consts::BASE64_ENGINE
.encode(ring::hmac::sign(&key, raw_signature.as_bytes()).as_ref());
Ok(signature_value)
}
}
impl api::Payment for Authipay {}
impl api::PaymentSession for Authipay {}
impl api::ConnectorAccessToken for Authipay {}
impl api::MandateSetup for Authipay {}
impl api::PaymentAuthorize for Authipay {}
impl api::PaymentSync for Authipay {}
impl api::PaymentCapture for Authipay {}
impl api::PaymentVoid for Authipay {}
impl api::Refund for Authipay {}
impl api::RefundExecute for Authipay {}
impl api::RefundSync for Authipay {}
impl api::PaymentToken for Authipay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Authipay
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Authipay
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 timestamp = time::OffsetDateTime::now_utc().unix_timestamp_nanos() / 1_000_000;
let auth: authipay::AuthipayAuthType =
authipay::AuthipayAuthType::try_from(&req.connector_auth_type)?;
let mut auth_header = self.get_auth_header(&req.connector_auth_type)?;
let authipay_req = self.get_request_body(req, connectors)?;
let client_request_id = uuid::Uuid::new_v4().to_string();
let hmac = self
.generate_authorization_signature(
auth,
&client_request_id,
authipay_req.get_inner_value().peek(),
timestamp,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let mut headers = vec![
(
headers::CONTENT_TYPE.to_string(),
types::PaymentsAuthorizeType::get_content_type(self)
.to_string()
.into(),
),
("Client-Request-Id".to_string(), client_request_id.into()),
("Auth-Token-Type".to_string(), "HMAC".to_string().into()),
(headers::TIMESTAMP.to_string(), timestamp.to_string().into()),
("Message-Signature".to_string(), hmac.into_masked()),
];
headers.append(&mut auth_header);
Ok(headers)
}
}
impl ConnectorCommon for Authipay {
fn id(&self) -> &'static str {
"authipay"
}
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.authipay.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = authipay::AuthipayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::API_KEY.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: authipay::AuthipayErrorResponse = res
.response
.parse_struct("AuthipayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
let mut error_response = ErrorResponse::from(&response);
// Set status code from the response, or 400 if error code is a "404"
if let Some(error_code) = &response.error.code {
if error_code == "404" {
error_response.status_code = 404;
} else {
error_response.status_code = res.status_code;
}
} else {
error_response.status_code = res.status_code;
}
Ok(error_response)
}
}
impl ConnectorValidation for Authipay {
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::Scheduled | enums::CaptureMethod::ManualMultiple => Err(
utils::construct_not_implemented_error_report(capture_method, self.id()),
),
}
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Authipay {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Authipay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Authipay
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Authipay {
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!("{}payments", 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 = authipay::AuthipayRouterData::from((amount, req));
let connector_req = authipay::AuthipayPaymentsRequest::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: authipay::AuthipayPaymentsResponse = res
.response
.parse_struct("Authipay PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&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 Authipay {
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_transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok(format!(
"{}payments/{}",
self.base_url(connectors),
connector_transaction_id
))
}
fn get_request_body(
&self,
_req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Ok(RequestContent::RawBytes(Vec::new()))
}
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: authipay::AuthipayPaymentsResponse = res
.response
.parse_struct("authipay PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&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 Authipay {
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_transaction_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}payments/{}",
self.base_url(connectors),
connector_transaction_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 = authipay::AuthipayRouterData::from((amount, req));
let connector_req = authipay::AuthipayCaptureRequest::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: authipay::AuthipayPaymentsResponse = res
.response
.parse_struct("Authipay PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&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 Authipay {
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> {
// For void operations, Authipay requires using the /orders/{orderId} endpoint
// The orderId should be stored in connector_meta from the authorization response
let order_id = req
.request
.connector_meta
.as_ref()
.and_then(|meta| meta.get("order_id"))
.and_then(|v| v.as_str())
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
Ok(format!("{}orders/{}", self.base_url(connectors), order_id))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
// For void, we don't need amount conversion since it's always full amount
let connector_router_data =
authipay::AuthipayRouterData::from((FloatMajorUnit::zero(), req));
let connector_req = authipay::AuthipayVoidRequest::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: authipay::AuthipayPaymentsResponse = res
.response
.parse_struct("Authipay PaymentsVoidResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&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 Authipay {
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!(
"{}payments/{}",
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 = authipay::AuthipayRouterData::from((refund_amount, req));
let connector_req = authipay::AuthipayRefundRequest::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: authipay::RefundResponse = res
.response
.parse_struct("authipay RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&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 Authipay {
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 refund_id = req
.request
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
Ok(format!(
"{}payments/{}",
self.base_url(connectors),
refund_id
))
}
fn get_request_body(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Ok(RequestContent::RawBytes(Vec::new()))
}
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: authipay::RefundResponse = res
.response
.parse_struct("authipay RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&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 Authipay {
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 AUTHIPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::SequentialAutomatic,
enums::CaptureMethod::Manual,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
];
let mut authipay_supported_payment_methods = SupportedPaymentMethods::new();
authipay_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
authipay_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
authipay_supported_payment_methods
});
static AUTHIPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Authipay",
description: "Authipay is a Fiserv-powered payment gateway for the EMEA region supporting Visa and Mastercard transactions. Features include flexible capture methods (automatic, manual, sequential), partial captures/refunds, payment tokenization, and secure HMAC SHA256 authentication.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static AUTHIPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Authipay {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&AUTHIPAY_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*AUTHIPAY_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&AUTHIPAY_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/authipay.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6287
}
|
large_file_3755629117506826626
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/chargebee.rs
</path>
<file>
pub mod transformers;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::ResultExt;
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
use hyperswitch_domain_models::{revenue_recovery, router_data_v2::RouterDataV2};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_data_v2::flow_common_types::{SubscriptionCreateData, SubscriptionCustomerData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
revenue_recovery::InvoiceRecordBack,
subscriptions::{
GetSubscriptionEstimate, GetSubscriptionPlanPrices, GetSubscriptionPlans,
SubscriptionCreate,
},
CreateConnectorCustomer,
},
router_request_types::{
revenue_recovery::InvoiceRecordBackRequest,
subscriptions::{
GetSubscriptionEstimateRequest, GetSubscriptionPlanPricesRequest,
GetSubscriptionPlansRequest, SubscriptionCreateRequest,
},
AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
revenue_recovery::InvoiceRecordBackResponse,
subscriptions::{
GetSubscriptionEstimateResponse, GetSubscriptionPlanPricesResponse,
GetSubscriptionPlansResponse, SubscriptionCreateResponse,
},
ConnectorInfo, PaymentsResponseData, RefundsResponseData,
},
types::{
ConnectorCustomerRouterData, GetSubscriptionEstimateRouterData,
GetSubscriptionPlanPricesRouterData, GetSubscriptionPlansRouterData,
InvoiceRecordBackRouterData, PaymentsAuthorizeRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
SubscriptionCreateRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self,
payments::ConnectorCustomer,
subscriptions_v2::{GetSubscriptionPlanPricesV2, GetSubscriptionPlansV2},
ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
connector_integration_v2::ConnectorIntegrationV2,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{Mask, PeekInterface, Secret};
use transformers as chargebee;
use crate::{
connectors::chargebee::transformers::{
ChargebeeGetPlanPricesResponse, ChargebeeListPlansResponse,
},
constants::{self, headers},
types::ResponseRouterData,
utils,
};
#[derive(Clone)]
pub struct Chargebee {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Chargebee {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl ConnectorCustomer for Chargebee {}
impl api::Payment for Chargebee {}
impl api::PaymentSession for Chargebee {}
impl api::ConnectorAccessToken for Chargebee {}
impl api::MandateSetup for Chargebee {}
impl api::PaymentAuthorize for Chargebee {}
impl api::PaymentSync for Chargebee {}
impl api::PaymentCapture for Chargebee {}
impl api::PaymentVoid for Chargebee {}
impl api::Refund for Chargebee {}
impl api::RefundExecute for Chargebee {}
impl api::RefundSync for Chargebee {}
impl api::PaymentToken for Chargebee {}
impl api::subscriptions::Subscriptions for Chargebee {}
#[cfg(all(feature = "v2", feature = "revenue_recovery"))]
impl api::revenue_recovery::RevenueRecoveryRecordBack for Chargebee {}
impl api::subscriptions::SubscriptionCreate for Chargebee {}
impl ConnectorIntegration<SubscriptionCreate, SubscriptionCreateRequest, SubscriptionCreateResponse>
for Chargebee
{
fn get_headers(
&self,
req: &SubscriptionCreateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &SubscriptionCreateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let metadata: chargebee::ChargebeeMetadata =
utils::to_connector_meta_from_secret(req.connector_meta_data.clone())?;
let site = metadata.site.peek();
let mut base = self.base_url(connectors).to_string();
base = base.replace("{{merchant_endpoint_prefix}}", site);
base = base.replace("$", site);
if base.contains("{{merchant_endpoint_prefix}}") || base.contains('$') {
return Err(errors::ConnectorError::InvalidConnectorConfig {
config: "Chargebee base_url has an unresolved placeholder (expected `$` or `{{merchant_endpoint_prefix}}`).",
}
.into());
}
if !base.ends_with('/') {
base.push('/');
}
let customer_id = &req.request.customer_id.get_string_repr().to_string();
Ok(format!(
"{base}v2/customers/{customer_id}/subscription_for_items"
))
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_request_body(
&self,
req: &SubscriptionCreateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = chargebee::ChargebeeRouterData::from((MinorUnit::new(0), req));
let connector_req =
chargebee::ChargebeeSubscriptionCreateRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &SubscriptionCreateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::SubscriptionCreateType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::SubscriptionCreateType::get_headers(
self, req, connectors,
)?)
.set_body(types::SubscriptionCreateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &SubscriptionCreateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SubscriptionCreateRouterData, errors::ConnectorError> {
let response: chargebee::ChargebeeSubscriptionCreateResponse = res
.response
.parse_struct("chargebee ChargebeeSubscriptionCreateResponse")
.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
ConnectorIntegrationV2<
SubscriptionCreate,
SubscriptionCreateData,
SubscriptionCreateRequest,
SubscriptionCreateResponse,
> for Chargebee
{
// Not Implemented (R)
}
impl
ConnectorIntegrationV2<
CreateConnectorCustomer,
SubscriptionCustomerData,
ConnectorCustomerData,
PaymentsResponseData,
> for Chargebee
{
// Not Implemented (R)
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Chargebee
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Chargebee
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.common_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 Chargebee {
fn id(&self) -> &'static str {
"chargebee"
}
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.chargebee.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = chargebee::ChargebeeAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let encoded_api_key = BASE64_ENGINE.encode(auth.full_access_key_v1.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: chargebee::ChargebeeErrorResponse = res
.response
.parse_struct("ChargebeeErrorResponse")
.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.api_error_code.clone(),
message: response.api_error_code.clone(),
reason: Some(response.message),
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 Chargebee {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Chargebee {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Chargebee {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Chargebee
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Chargebee {
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 = chargebee::ChargebeeRouterData::from((amount, req));
let connector_req = chargebee::ChargebeePaymentsRequest::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: chargebee::ChargebeePaymentsResponse = res
.response
.parse_struct("Chargebee 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 Chargebee {
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: chargebee::ChargebeePaymentsResponse = res
.response
.parse_struct("chargebee 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 Chargebee {
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: chargebee::ChargebeePaymentsResponse = res
.response
.parse_struct("Chargebee 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 Chargebee {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Chargebee {
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 = chargebee::ChargebeeRouterData::from((refund_amount, req));
let connector_req = chargebee::ChargebeeRefundRequest::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: chargebee::RefundResponse = res
.response
.parse_struct("chargebee 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 Chargebee {
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: chargebee::RefundResponse = res
.response
.parse_struct("chargebee 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<InvoiceRecordBack, InvoiceRecordBackRequest, InvoiceRecordBackResponse>
for Chargebee
{
fn get_headers(
&self,
req: &InvoiceRecordBackRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &InvoiceRecordBackRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let metadata: chargebee::ChargebeeMetadata =
utils::to_connector_meta_from_secret(req.connector_meta_data.clone())?;
let site = metadata.site.peek();
let mut base = self.base_url(connectors).to_string();
base = base.replace("{{merchant_endpoint_prefix}}", site);
base = base.replace("$", site);
if base.contains("{{merchant_endpoint_prefix}}") || base.contains('$') {
return Err(errors::ConnectorError::InvalidConnectorConfig {
config: "Chargebee base_url has an unresolved placeholder (expected `$` or `{{merchant_endpoint_prefix}}`).",
}
.into());
}
if !base.ends_with('/') {
base.push('/');
}
let invoice_id = req
.request
.merchant_reference_id
.get_string_repr()
.to_string();
Ok(format!("{base}v2/invoices/{invoice_id}/record_payment"))
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_request_body(
&self,
req: &InvoiceRecordBackRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.amount,
req.request.currency,
)?;
let connector_router_data = chargebee::ChargebeeRouterData::from((amount, req));
let connector_req =
chargebee::ChargebeeRecordPaymentRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &InvoiceRecordBackRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::InvoiceRecordBackType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::InvoiceRecordBackType::get_headers(
self, req, connectors,
)?)
.set_body(types::InvoiceRecordBackType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &InvoiceRecordBackRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<InvoiceRecordBackRouterData, errors::ConnectorError> {
let response: chargebee::ChargebeeRecordbackResponse = res
.response
.parse_struct("chargebee ChargebeeRecordbackResponse")
.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_chargebee_plans_query_params(
_req: &RouterData<
GetSubscriptionPlans,
GetSubscriptionPlansRequest,
GetSubscriptionPlansResponse,
>,
) -> CustomResult<String, errors::ConnectorError> {
// Try to get limit from request, else default to 10
let limit = _req.request.limit.unwrap_or(10);
let offset = _req.request.offset.unwrap_or(0);
let param = format!(
"?limit={}&offset={}&type[is]={}",
limit,
offset,
constants::PLAN_ITEM_TYPE
);
Ok(param)
}
impl api::subscriptions::GetSubscriptionPlansFlow for Chargebee {}
impl api::subscriptions::SubscriptionRecordBackFlow for Chargebee {}
impl
ConnectorIntegration<
GetSubscriptionPlans,
GetSubscriptionPlansRequest,
GetSubscriptionPlansResponse,
> for Chargebee
{
fn get_headers(
&self,
req: &GetSubscriptionPlansRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &GetSubscriptionPlansRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let query_params = get_chargebee_plans_query_params(req)?;
let metadata: chargebee::ChargebeeMetadata =
utils::to_connector_meta_from_secret(req.connector_meta_data.clone())?;
let site = metadata.site.peek();
let mut base = self.base_url(connectors).to_string();
base = base.replace("{{merchant_endpoint_prefix}}", site);
base = base.replace("$", site);
if base.contains("{{merchant_endpoint_prefix}}") || base.contains('$') {
return Err(errors::ConnectorError::InvalidConnectorConfig {
config: "Chargebee base_url has an unresolved placeholder (expected `$` or `{{merchant_endpoint_prefix}}`).",
}
.into());
}
if !base.ends_with('/') {
base.push('/');
}
let url = format!("{base}v2/items{query_params}");
Ok(url)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn build_request(
&self,
req: &GetSubscriptionPlansRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::GetSubscriptionPlansType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::GetSubscriptionPlansType::get_headers(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &GetSubscriptionPlansRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<GetSubscriptionPlansRouterData, errors::ConnectorError> {
let response: ChargebeeListPlansResponse = res
.response
.parse_struct("ChargebeeListPlansResponse")
.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 GetSubscriptionPlansV2 for Chargebee {}
impl
ConnectorIntegrationV2<
GetSubscriptionPlans,
hyperswitch_domain_models::router_data_v2::flow_common_types::GetSubscriptionPlansData,
GetSubscriptionPlansRequest,
GetSubscriptionPlansResponse,
> for Chargebee
{
// Not implemented (R)
}
impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>
for Chargebee
{
fn get_headers(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &ConnectorCustomerRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let metadata: chargebee::ChargebeeMetadata =
utils::to_connector_meta_from_secret(req.connector_meta_data.clone())?;
let site = metadata.site.peek();
let mut base = self.base_url(connectors).to_string();
base = base.replace("{{merchant_endpoint_prefix}}", site);
base = base.replace("$", site);
if base.contains("{{merchant_endpoint_prefix}}") || base.contains('$') {
return Err(errors::ConnectorError::InvalidConnectorConfig {
config: "Chargebee base_url has an unresolved placeholder (expected `$` or `{{merchant_endpoint_prefix}}`).",
}
.into());
}
if !base.ends_with('/') {
base.push('/');
}
let url = format!("{base}v2/customers");
Ok(url)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_request_body(
&self,
req: &ConnectorCustomerRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = chargebee::ChargebeeRouterData::from((MinorUnit::new(0), req));
let connector_req =
chargebee::ChargebeeCustomerCreateRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(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: chargebee::ChargebeeCustomerCreateResponse = res
.response
.parse_struct("ChargebeeCustomerCreateResponse")
.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::subscriptions::GetSubscriptionPlanPricesFlow for Chargebee {}
fn get_chargebee_plan_prices_query_params(
req: &GetSubscriptionPlanPricesRouterData,
) -> CustomResult<String, errors::ConnectorError> {
let item_id = req.request.plan_price_id.to_string();
let params = format!("?item_id[is]={item_id}");
Ok(params)
}
impl
ConnectorIntegration<
GetSubscriptionPlanPrices,
GetSubscriptionPlanPricesRequest,
GetSubscriptionPlanPricesResponse,
> for Chargebee
{
fn get_headers(
&self,
req: &GetSubscriptionPlanPricesRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &GetSubscriptionPlanPricesRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let query_params = get_chargebee_plan_prices_query_params(req)?;
let metadata: chargebee::ChargebeeMetadata =
utils::to_connector_meta_from_secret(req.connector_meta_data.clone())?;
let site = metadata.site.peek();
let mut base = self.base_url(connectors).to_string();
base = base.replace("{{merchant_endpoint_prefix}}", site);
base = base.replace("$", site);
if base.contains("{{merchant_endpoint_prefix}}") || base.contains('$') {
return Err(errors::ConnectorError::InvalidConnectorConfig {
config: "Chargebee base_url has an unresolved placeholder (expected `$` or `{{merchant_endpoint_prefix}}`).",
}
.into());
}
if !base.ends_with('/') {
base.push('/');
}
let url = format!("{base}v2/item_prices{query_params}");
Ok(url)
}
// check if get_content_type is required
fn build_request(
&self,
req: &GetSubscriptionPlanPricesRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::GetSubscriptionPlanPricesType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::GetSubscriptionPlanPricesType::get_headers(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &GetSubscriptionPlanPricesRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<GetSubscriptionPlanPricesRouterData, errors::ConnectorError> {
let response: ChargebeeGetPlanPricesResponse = res
.response
.parse_struct("chargebee ChargebeeGetPlanPricesResponse")
.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 GetSubscriptionPlanPricesV2 for Chargebee {}
impl
ConnectorIntegrationV2<
GetSubscriptionPlanPrices,
hyperswitch_domain_models::router_data_v2::flow_common_types::GetSubscriptionPlanPricesData,
GetSubscriptionPlanPricesRequest,
GetSubscriptionPlanPricesResponse,
> for Chargebee
{
// TODO: implement functions when support enabled
}
impl api::subscriptions::GetSubscriptionEstimateFlow for Chargebee {}
impl
ConnectorIntegration<
GetSubscriptionEstimate,
GetSubscriptionEstimateRequest,
GetSubscriptionEstimateResponse,
> for Chargebee
{
fn get_headers(
&self,
req: &GetSubscriptionEstimateRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &GetSubscriptionEstimateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let metadata: chargebee::ChargebeeMetadata =
utils::to_connector_meta_from_secret(req.connector_meta_data.clone())?;
let site = metadata.site.peek();
let mut base = self.base_url(connectors).to_string();
base = base.replace("{{merchant_endpoint_prefix}}", site);
base = base.replace("$", site);
if base.contains("{{merchant_endpoint_prefix}}") || base.contains('$') {
return Err(errors::ConnectorError::InvalidConnectorConfig {
config: "Chargebee base_url has an unresolved placeholder (expected `$` or `{{merchant_endpoint_prefix}}`).",
}
.into());
}
if !base.ends_with('/') {
base.push('/');
}
Ok(format!("{base}v2/estimates/create_subscription_for_items"))
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_request_body(
&self,
req: &GetSubscriptionEstimateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = chargebee::ChargebeeSubscriptionEstimateRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &GetSubscriptionEstimateRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::GetSubscriptionEstimateType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::GetSubscriptionEstimateType::get_headers(
self, req, connectors,
)?)
.set_body(types::GetSubscriptionEstimateType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &GetSubscriptionEstimateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<GetSubscriptionEstimateRouterData, errors::ConnectorError> {
let response: chargebee::SubscriptionEstimateResponse = res
.response
.parse_struct("chargebee SubscriptionEstimateResponse")
.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 Chargebee {
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature = utils::get_header_key_value("authorization", request.headers)?;
let signature = base64_signature.as_bytes().to_owned();
Ok(signature)
}
async fn verify_webhook_source(
&self,
request: &webhooks::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_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::WebhookSourceVerificationFailed)?;
let password = connector_webhook_secrets
.additional_secret
.ok_or(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Failed to get additional secrets")?;
let username = String::from_utf8(connector_webhook_secrets.secret.to_vec())
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Could not convert secret to UTF-8")?;
let secret_auth = format!(
"Basic {}",
base64::engine::general_purpose::STANDARD.encode(format!(
"{}:{}",
username,
password.peek()
))
);
let signature_auth = String::from_utf8(signature.to_vec())
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Could not convert secret to UTF-8")?;
Ok(signature_auth == secret_auth)
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook =
chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::InvoiceId(
api_models::webhooks::InvoiceIdType::ConnectorInvoiceId(
webhook.content.invoice.id.get_string_repr().to_string(),
),
))
}
#[cfg(any(feature = "v1", not(all(feature = "revenue_recovery", feature = "v2"))))]
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook =
chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let subscription_id = webhook.content.invoice.subscription_id;
Ok(api_models::webhooks::ObjectReferenceId::SubscriptionId(
subscription_id,
))
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let webhook =
chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
let event = api_models::webhooks::IncomingWebhookEvent::from(webhook.event_type);
Ok(event)
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook =
chargebee::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(webhook))
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
fn get_revenue_recovery_attempt_details(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<revenue_recovery::RevenueRecoveryAttemptData, errors::ConnectorError> {
let webhook =
transformers::ChargebeeWebhookBody::get_webhook_object_from_body(request.body)?;
revenue_recovery::RevenueRecoveryAttemptData::try_from(webhook)
}
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
fn get_revenue_recovery_invoice_details(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<revenue_recovery::RevenueRecoveryInvoiceData, errors::ConnectorError> {
let webhook =
transformers::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)?;
revenue_recovery::RevenueRecoveryInvoiceData::try_from(webhook)
}
fn get_subscription_mit_payment_data(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
hyperswitch_domain_models::router_flow_types::SubscriptionMitPaymentData,
errors::ConnectorError,
> {
let webhook_body =
transformers::ChargebeeInvoiceBody::get_invoice_webhook_data_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)
.attach_printable("Failed to parse Chargebee invoice webhook body")?;
let chargebee_mit_data = transformers::ChargebeeMitPaymentData::try_from(webhook_body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)
.attach_printable("Failed to extract MIT payment data from Chargebee webhook")?;
// Convert Chargebee-specific data to generic domain model
Ok(
hyperswitch_domain_models::router_flow_types::SubscriptionMitPaymentData {
invoice_id: chargebee_mit_data.invoice_id,
amount_due: chargebee_mit_data.amount_due,
currency_code: chargebee_mit_data.currency_code,
status: chargebee_mit_data.status.map(|s| s.into()),
customer_id: chargebee_mit_data.customer_id,
subscription_id: chargebee_mit_data.subscription_id,
first_invoice: chargebee_mit_data.first_invoice,
},
)
}
}
static CHARGEBEE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Chargebee",
description: "Chargebee is a Revenue Growth Management (RGM) platform that helps subscription businesses manage subscriptions, billing, revenue recognition, collections, and customer retention, essentially streamlining the entire subscription lifecycle.",
connector_type: enums::HyperswitchConnectorCategory::RevenueGrowthManagementPlatform,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static CHARGEBEE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
impl ConnectorSpecifications for Chargebee {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&CHARGEBEE_CONNECTOR_INFO)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&CHARGEBEE_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/chargebee.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 11013
}
|
large_file_3238262297878214754
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs
</path>
<file>
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},
Authenticate, AuthenticationConfirmation, PostAuthenticate, PreAuthenticate,
},
router_request_types::{
unified_authentication_service::{
UasAuthenticationRequestData, UasAuthenticationResponseData,
UasConfirmationRequestData, UasPostAuthenticationRequestData,
UasPreAuthenticationRequestData,
},
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 juspaythreedsserver;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Juspaythreedsserver {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Juspaythreedsserver {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Juspaythreedsserver {}
impl api::PaymentSession for Juspaythreedsserver {}
impl api::ConnectorAccessToken for Juspaythreedsserver {}
impl api::MandateSetup for Juspaythreedsserver {}
impl api::PaymentAuthorize for Juspaythreedsserver {}
impl api::PaymentSync for Juspaythreedsserver {}
impl api::PaymentCapture for Juspaythreedsserver {}
impl api::PaymentVoid for Juspaythreedsserver {}
impl api::Refund for Juspaythreedsserver {}
impl api::RefundExecute for Juspaythreedsserver {}
impl api::RefundSync for Juspaythreedsserver {}
impl api::PaymentToken for Juspaythreedsserver {}
impl api::UnifiedAuthenticationService for Juspaythreedsserver {}
impl api::UasPreAuthentication for Juspaythreedsserver {}
impl api::UasPostAuthentication for Juspaythreedsserver {}
impl api::UasAuthenticationConfirmation for Juspaythreedsserver {}
impl api::UasAuthentication for Juspaythreedsserver {}
impl
ConnectorIntegration<
PreAuthenticate,
UasPreAuthenticationRequestData,
UasAuthenticationResponseData,
> for Juspaythreedsserver
{
}
impl
ConnectorIntegration<
PostAuthenticate,
UasPostAuthenticationRequestData,
UasAuthenticationResponseData,
> for Juspaythreedsserver
{
}
impl
ConnectorIntegration<
AuthenticationConfirmation,
UasConfirmationRequestData,
UasAuthenticationResponseData,
> for Juspaythreedsserver
{
}
impl ConnectorIntegration<Authenticate, UasAuthenticationRequestData, UasAuthenticationResponseData>
for Juspaythreedsserver
{
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Juspaythreedsserver
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Juspaythreedsserver
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 Juspaythreedsserver {
fn id(&self) -> &'static str {
"juspaythreedsserver"
}
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.juspaythreedsserver.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = juspaythreedsserver::JuspaythreedsserverAuthType::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: juspaythreedsserver::JuspaythreedsserverErrorResponse = res
.response
.parse_struct("JuspaythreedsserverErrorResponse")
.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 Juspaythreedsserver {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData>
for Juspaythreedsserver
{
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
for Juspaythreedsserver
{
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Juspaythreedsserver
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for Juspaythreedsserver
{
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 =
juspaythreedsserver::JuspaythreedsserverRouterData::from((amount, req));
let connector_req = juspaythreedsserver::JuspaythreedsserverPaymentsRequest::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: juspaythreedsserver::JuspaythreedsserverPaymentsResponse = res
.response
.parse_struct("Juspaythreedsserver 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 Juspaythreedsserver {
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: juspaythreedsserver::JuspaythreedsserverPaymentsResponse = res
.response
.parse_struct("juspaythreedsserver 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 Juspaythreedsserver
{
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: juspaythreedsserver::JuspaythreedsserverPaymentsResponse = res
.response
.parse_struct("Juspaythreedsserver 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 Juspaythreedsserver {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Juspaythreedsserver {
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 =
juspaythreedsserver::JuspaythreedsserverRouterData::from((refund_amount, req));
let connector_req = juspaythreedsserver::JuspaythreedsserverRefundRequest::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: juspaythreedsserver::RefundResponse = res
.response
.parse_struct("juspaythreedsserver 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 Juspaythreedsserver {
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: juspaythreedsserver::RefundResponse = res
.response
.parse_struct("juspaythreedsserver 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 Juspaythreedsserver {
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 JUSPAYTHREEDSSERVER_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Juspay 3Ds Server",
description: "Juspay 3DS Server provider for comprehensive 3-Domain Secure authentication, cardholder verification, and fraud prevention across card networks",
connector_type: common_enums::HyperswitchConnectorCategory::AuthenticationProvider,
integration_status: common_enums::ConnectorIntegrationStatus::Alpha,
};
impl ConnectorSpecifications for Juspaythreedsserver {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&JUSPAYTHREEDSSERVER_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
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/juspaythreedsserver.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5053
}
|
large_file_9211913821760787499
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/finix.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::{enums, CaptureMethod, ConnectorIntegrationStatus, PaymentMethodType};
use common_utils::{
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, Session, SetupMandate, Void},
refunds::{Execute, RSync},
CreateConnectorCustomer,
},
router_request_types::{
AccessTokenRequestData, ConnectorCustomerData, 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};
use transformers as finix;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Finix {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Finix {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Finix {}
impl api::PaymentSession for Finix {}
impl api::ConnectorAccessToken for Finix {}
impl api::MandateSetup for Finix {}
impl api::PaymentAuthorize for Finix {}
impl api::PaymentSync for Finix {}
impl api::PaymentCapture for Finix {}
impl api::PaymentVoid for Finix {}
impl api::Refund for Finix {}
impl api::RefundExecute for Finix {}
impl api::RefundSync for Finix {}
impl api::PaymentToken for Finix {}
impl api::ConnectorCustomer for Finix {}
impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>
for Finix
{
fn get_headers(
&self,
req: &RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>,
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: &RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/identities", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = finix::FinixRouterData::try_from((MinorUnit::zero(), req))?;
let connector_req = finix::FinixCreateIdentityRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>,
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: &RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>,
errors::ConnectorError,
> {
let response: finix::FinixIdentityResponse = res
.response
.parse_struct("Finix IdentityResponse")
.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 Finix
{
fn get_headers(
&self,
req: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
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: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/payment_instruments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = finix::FinixRouterData::try_from((MinorUnit::zero(), req))?;
let connector_req =
finix::FinixCreatePaymentInstrumentRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::TokenizationType::get_headers(self, req, connectors)?)
.set_body(types::TokenizationType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
errors::ConnectorError,
> {
let response: finix::FinixInstrumentResponse = res
.response
.parse_struct("Finix InstrumentResponse")
.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<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Finix
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 Finix {
fn id(&self) -> &'static str {
"finix"
}
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.finix.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = finix::FinixAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let credentials = format!(
"{}:{}",
auth.finix_user_name.clone().expose(),
auth.finix_password.clone().expose()
);
let encoded = format!(
"Basic {:}",
base64::engine::general_purpose::STANDARD.encode(credentials.as_bytes())
);
Ok(vec![(
headers::AUTHORIZATION.to_string(),
encoded.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: finix::FinixErrorResponse =
res.response
.parse_struct("FinixErrorResponse")
.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.get_code(),
message: response.get_message(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Finix {
fn validate_mandate_payment(
&self,
_pm_type: Option<PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match pm_data {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"validate_mandate_payment does not support cards".to_string(),
)
.into()),
_ => Ok(()),
}
}
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(())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Finix {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Finix {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Finix {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Finix {
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 flow = match req.request.capture_method.unwrap_or_default() {
CaptureMethod::Automatic | CaptureMethod::SequentialAutomatic => "transfers",
CaptureMethod::Manual | CaptureMethod::ManualMultiple | CaptureMethod::Scheduled => {
"authorizations"
}
};
Ok(format!("{}/{}", self.base_url(connectors), flow))
}
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 = finix::FinixRouterData::try_from((amount, req))?;
let connector_req = finix::FinixPaymentsRequest::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: finix::FinixPaymentsResponse = res
.response
.parse_struct("Finix PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
finix::get_finix_response(
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
finix::FinixFlow::get_flow_for_auth(data.request.capture_method.unwrap_or_default()),
)
}
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 Finix {
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_transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
match finix::FinixId::from(connector_transaction_id) {
transformers::FinixId::Auth(id) => Ok(format!(
"{}/authorizations/{}",
self.base_url(connectors),
id
)),
transformers::FinixId::Transfer(id) => {
Ok(format!("{}/transfers/{}", self.base_url(connectors), id))
}
}
}
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: finix::FinixPaymentsResponse = res
.response
.parse_struct("finix PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let response_id = response.id.clone();
finix::get_finix_response(
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
match finix::FinixId::from(response_id) {
finix::FinixId::Auth(_) => finix::FinixFlow::Auth,
finix::FinixId::Transfer(_) => finix::FinixFlow::Transfer,
},
)
}
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 Finix {
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_transaction_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/authorizations/{}",
self.base_url(connectors),
connector_transaction_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 = finix::FinixRouterData::try_from((amount, req))?;
let connector_req = finix::FinixCaptureRequest::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::Put)
.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: finix::FinixPaymentsResponse = res
.response
.parse_struct("Finix PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
finix::get_finix_response(
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
finix::FinixFlow::Capture,
)
}
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 Finix {
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 connector_transaction_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/authorizations/{}",
self.base_url(connectors),
connector_transaction_id
))
}
fn get_request_body(
&self,
_req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = finix::FinixCancelRequest { void_me: true };
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::Put)
.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: finix::FinixPaymentsResponse = res
.response
.parse_struct("Finix PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
finix::get_finix_response(
ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
},
finix::FinixFlow::Transfer,
)
}
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 Finix {
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!(
"{}/transfers/{}/reversals",
self.base_url(connectors),
req.request.connector_transaction_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 = finix::FinixRouterData::try_from((refund_amount, req))?;
let connector_req = finix::FinixCreateRefundRequest::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: finix::FinixPaymentsResponse = res
.response
.parse_struct("FinixPaymentsResponse")
.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 Finix {
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 refund_id = req
.request
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?;
Ok(format!(
"{}/transfers/{}",
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(&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: finix::FinixPaymentsResponse = res
.response
.parse_struct("FinixPaymentsResponse")
.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 Finix {
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 FINIX_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let default_capture_methods = vec![CaptureMethod::Automatic, CaptureMethod::Manual];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::Maestro,
];
let mut finix_supported_payment_methods = SupportedPaymentMethods::new();
finix_supported_payment_methods.add(
common_enums::PaymentMethod::Card,
PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: default_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(),
},
),
),
},
);
finix_supported_payment_methods.add(
common_enums::PaymentMethod::Card,
PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: default_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(),
},
),
),
},
);
finix_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: default_capture_methods.clone(),
specific_features: None,
},
);
finix_supported_payment_methods.add(
common_enums::PaymentMethod::Wallet,
PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: default_capture_methods.clone(),
specific_features: None,
},
);
finix_supported_payment_methods
});
static FINIX_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Finix",
description: "Finix is a payments technology provider enabling businesses to accept and send payments online or in person",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: ConnectorIntegrationStatus::Alpha,
};
static FINIX_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Finix {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&FINIX_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*FINIX_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&FINIX_SUPPORTED_WEBHOOK_FLOWS)
}
fn should_call_connector_customer(
&self,
_payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> bool {
true
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/finix.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7632
}
|
large_file_2481006586739757689
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/dlocal.rs
</path>
<file>
pub mod transformers;
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::enums;
use common_utils::{
crypto::{self, SignMessage},
date_time,
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hex::encode;
use hyperswitch_domain_models::{
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 lazy_static::lazy_static;
use masking::{Mask, Maskable, PeekInterface};
use transformers as dlocal;
use crate::{
connectors::dlocal::transformers::DlocalRouterData, constants::headers,
types::ResponseRouterData, utils::convert_amount,
};
#[derive(Clone)]
pub struct Dlocal {
amount_convertor: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Dlocal {
pub fn new() -> &'static Self {
&Self {
amount_convertor: &MinorUnitForConnector,
}
}
}
impl api::Payment for Dlocal {}
impl api::PaymentToken for Dlocal {}
impl api::PaymentSession for Dlocal {}
impl api::ConnectorAccessToken for Dlocal {}
impl api::MandateSetup for Dlocal {}
impl api::PaymentAuthorize for Dlocal {}
impl api::PaymentSync for Dlocal {}
impl api::PaymentCapture for Dlocal {}
impl api::PaymentVoid for Dlocal {}
impl api::Refund for Dlocal {}
impl api::RefundExecute for Dlocal {}
impl api::RefundSync for Dlocal {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Dlocal
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 dlocal_req = self.get_request_body(req, connectors)?;
let date = date_time::date_as_yyyymmddthhmmssmmmz()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
let auth = dlocal::DlocalAuthType::try_from(&req.connector_auth_type)?;
let sign_req: String = format!(
"{}{}{}",
auth.x_login.peek(),
date,
dlocal_req.get_inner_value().peek().to_owned()
);
let authz = crypto::HmacSha256::sign_message(
&crypto::HmacSha256,
auth.secret.peek().as_bytes(),
sign_req.as_bytes(),
)
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failed to sign the message")?;
let auth_string: String = format!("V2-HMAC-SHA256, Signature: {}", encode(authz));
let headers = vec![
(
headers::AUTHORIZATION.to_string(),
auth_string.into_masked(),
),
(headers::X_LOGIN.to_string(), auth.x_login.into_masked()),
(
headers::X_TRANS_KEY.to_string(),
auth.x_trans_key.into_masked(),
),
(headers::X_VERSION.to_string(), "2.1".to_string().into()),
(headers::X_DATE.to_string(), date.into()),
(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
),
];
Ok(headers)
}
}
impl ConnectorCommon for Dlocal {
fn id(&self) -> &'static str {
"dlocal"
}
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.dlocal.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: dlocal::DlocalErrorResponse = res
.response
.parse_struct("Dlocal ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i: &mut ConnectorEvent| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code.to_string(),
message: response.message,
reason: response.param,
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 Dlocal {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Dlocal
{
// Not Implemented (R)
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Dlocal {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Dlocal {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Dlocal {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Dlocal".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Dlocal {
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!("{}secure_payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = DlocalRouterData::try_from((amount, req))?;
let connector_req = dlocal::DlocalPaymentsRequest::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> {
router_env::logger::debug!(dlocal_payments_authorize_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal 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 Dlocal {
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> {
let sync_data = dlocal::DlocalPaymentsSyncRequest::try_from(req)?;
Ok(format!(
"{}payments/{}/status",
self.base_url(connectors),
sync_data.authz_id,
))
}
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 get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
router_env::logger::debug!(dlocal_payment_sync_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal 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,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Dlocal {
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!("{}payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = dlocal::DlocalPaymentsCaptureRequest::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(&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> {
router_env::logger::debug!(dlocal_payments_capture_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal 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,
})
.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<Void, PaymentsCancelData, PaymentsResponseData> for Dlocal {
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> {
let cancel_data = dlocal::DlocalPaymentsCancelRequest::try_from(req)?;
Ok(format!(
"{}payments/{}/cancel",
self.base_url(connectors),
cancel_data.cancel_id
))
}
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)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
router_env::logger::debug!(dlocal_payments_cancel_response=?res);
let response: dlocal::DlocalPaymentsResponse = res
.response
.parse_struct("Dlocal 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,
})
.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 Dlocal {
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 amount = convert_amount(
self.amount_convertor,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = DlocalRouterData::try_from((amount, req))?;
let connector_req = dlocal::DlocalRefundRequest::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> {
router_env::logger::debug!(dlocal_refund_response=?res);
let response: dlocal::RefundResponse =
res.response
.parse_struct("Dlocal 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,
})
.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<RSync, RefundsData, RefundsResponseData> for Dlocal {
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> {
let sync_data = dlocal::DlocalRefundsSyncRequest::try_from(req)?;
Ok(format!(
"{}refunds/{}/status",
self.base_url(connectors),
sync_data.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)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
router_env::logger::debug!(dlocal_refund_sync_response=?res);
let response: dlocal::RefundResponse = res
.response
.parse_struct("Dlocal 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)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Dlocal {
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<IncomingWebhookEvent, errors::ConnectorError> {
Ok(IncomingWebhookEvent::EventNotSupported)
}
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 DLOCAL_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
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::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::CartesBancaires,
];
let mut dlocal_supported_payment_methods = SupportedPaymentMethods::new();
dlocal_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
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::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
dlocal_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
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::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
dlocal_supported_payment_methods
};
static ref DLOCAL_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "DLOCAL",
description:
"Dlocal is a cross-border payment processor enabling businesses to accept and send payments in emerging markets worldwide.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static ref DLOCAL_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
}
impl ConnectorSpecifications for Dlocal {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*DLOCAL_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*DLOCAL_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*DLOCAL_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/dlocal.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5849
}
|
large_file_9090908554822124759
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/datatrans.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use base64::Engine;
use common_enums::{CaptureMethod, PaymentMethod, PaymentMethodType};
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, 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, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts::NO_ERROR_CODE,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::{Mask, PeekInterface};
use transformers as datatrans;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{
self, convert_amount, PaymentsAuthorizeRequestData, RefundsRequestData,
RouterData as OtherRouterData,
},
};
impl api::Payment for Datatrans {}
impl api::PaymentSession for Datatrans {}
impl api::ConnectorAccessToken for Datatrans {}
impl api::MandateSetup for Datatrans {}
impl api::PaymentAuthorize for Datatrans {}
impl api::PaymentSync for Datatrans {}
impl api::PaymentCapture for Datatrans {}
impl api::PaymentVoid for Datatrans {}
impl api::Refund for Datatrans {}
impl api::RefundExecute for Datatrans {}
impl api::RefundSync for Datatrans {}
impl api::PaymentToken for Datatrans {}
#[derive(Clone)]
pub struct Datatrans {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Datatrans {
pub const fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Datatrans
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Datatrans
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 Datatrans {
fn id(&self) -> &'static str {
"datatrans"
}
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.datatrans.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = datatrans::DatatransAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_key = format!("{}:{}", auth.merchant_id.peek(), auth.passcode.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 (cow, _, _) = encoding_rs::ISO_8859_10.decode(&res.response);
let response = cow.as_ref().to_string();
if utils::is_html_response(&response) {
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_owned(),
message: response.clone(),
reason: Some(response),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
let response: datatrans::DatatransErrorResponse = res
.response
.parse_struct("DatatransErrorType")
.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.clone(),
message: response.error.message.clone(),
reason: Some(response.error.message.clone()),
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 Datatrans {
fn validate_mandate_payment(
&self,
_pm_type: Option<PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let connector = self.id();
match pm_data {
PaymentMethodData::Card(_) => Ok(()),
_ => Err(errors::ConnectorError::NotSupported {
message: " mandate payment".to_string(),
connector,
}
.into()),
}
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Datatrans {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Datatrans {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Datatrans
{
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(format!("{}v1/transactions", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = datatrans::DatatransPaymentsRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
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: datatrans::DatatransResponse = res
.response
.parse_struct("Datatrans 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<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Datatrans {
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 base_url = self.base_url(connectors);
if req.request.payment_method_data == PaymentMethodData::MandatePayment {
// MIT
Ok(format!("{base_url}v1/transactions/authorize"))
} else if req.request.is_mandate_payment() {
// CIT
Ok(format!("{base_url}v1/transactions"))
} else {
// Direct
if req.is_three_ds() && req.request.authentication_data.is_none() {
Ok(format!("{base_url}v1/transactions"))
} else {
Ok(format!("{base_url}v1/transactions/authorize"))
}
}
}
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 = datatrans::DatatransRouterData::try_from((amount, req))?;
let connector_req = datatrans::DatatransPaymentsRequest::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: datatrans::DatatransResponse = res
.response
.parse_struct("Datatrans 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 Datatrans {
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
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
let base_url = self.base_url(connectors);
Ok(format!("{base_url}v1/transactions/{connector_payment_id}"))
}
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: datatrans::DatatransSyncResponse = res
.response
.parse_struct("datatrans DatatransSyncResponse")
.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 Datatrans {
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();
let base_url = self.base_url(connectors);
Ok(format!(
"{base_url}v1/transactions/{connector_payment_id}/settle"
))
}
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 = datatrans::DatatransRouterData::try_from((amount, req))?;
let connector_req = datatrans::DataPaymentCaptureRequest::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 = if res.response.is_empty() {
datatrans::DataTransCaptureResponse::Empty
} else {
res.response
.parse_struct("Datatrans DataTransCaptureResponse")
.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 Datatrans {
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 transaction_id = req.request.connector_transaction_id.clone();
let base_url = self.base_url(connectors);
Ok(format!("{base_url}v1/transactions/{transaction_id}/cancel"))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = 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();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response = if res.response.is_empty() {
datatrans::DataTransCancelResponse::Empty
} else {
res.response
.parse_struct("Datatrans DataTransCancelResponse")
.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 Datatrans {
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 transaction_id = req.request.connector_transaction_id.clone();
let base_url = self.base_url(connectors);
Ok(format!("{base_url}v1/transactions/{transaction_id}/credit"))
}
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 = datatrans::DatatransRouterData::try_from((amount, req))?;
let connector_req = datatrans::DatatransRefundRequest::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: datatrans::DatatransRefundsResponse = res
.response
.parse_struct("datatrans DatatransRefundsResponse")
.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 Datatrans {
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()?;
let base_url = self.base_url(connectors);
Ok(format!("{base_url}v1/transactions/{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: datatrans::DatatransSyncResponse = res
.response
.parse_struct("datatrans DatatransSyncResponse")
.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 Datatrans {
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> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static DATATRANS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
CaptureMethod::Automatic,
CaptureMethod::Manual,
CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Maestro,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::CartesBancaires,
];
let mut datatrans_supported_payment_methods = SupportedPaymentMethods::new();
datatrans_supported_payment_methods.add(
PaymentMethod::Card,
PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: common_enums::enums::FeatureStatus::Supported,
refunds: common_enums::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(),
}
}),
),
},
);
datatrans_supported_payment_methods.add(
PaymentMethod::Card,
PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: common_enums::enums::FeatureStatus::Supported,
refunds: common_enums::enums::FeatureStatus::Supported,
supported_capture_methods,
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(),
}
}),
),
},
);
datatrans_supported_payment_methods
});
static DATATRANS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Datatrans",
description:
"Datatrans is a payment gateway that facilitates the processing of payments, including hosting smart payment forms and correctly routing payment information.",
connector_type: common_enums::enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: common_enums::enums::ConnectorIntegrationStatus::Live,
};
static DATATRANS_SUPPORTED_WEBHOOK_FLOWS: [common_enums::enums::EventClass; 0] = [];
impl ConnectorSpecifications for Datatrans {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&DATATRANS_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*DATATRANS_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> {
Some(&DATATRANS_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/datatrans.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6787
}
|
large_file_7601030175978885028
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/affirm.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
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, CompleteAuthorize, PSync, PaymentMethodToken, Session,
SetupMandate, Void,
},
refunds::{Execute, RSync},
},
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, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{Mask, PeekInterface};
use transformers as affirm;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Affirm {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Affirm {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Affirm {}
impl api::PaymentSession for Affirm {}
impl api::ConnectorAccessToken for Affirm {}
impl api::MandateSetup for Affirm {}
impl api::PaymentAuthorize for Affirm {}
impl api::PaymentsCompleteAuthorize for Affirm {}
impl api::PaymentSync for Affirm {}
impl api::PaymentCapture for Affirm {}
impl api::PaymentVoid for Affirm {}
impl api::Refund for Affirm {}
impl api::RefundExecute for Affirm {}
impl api::RefundSync for Affirm {}
impl api::PaymentToken for Affirm {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Affirm
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Affirm
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 Affirm {
fn id(&self) -> &'static str {
"affirm"
}
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.affirm.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = affirm::AffirmAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let encoded_api_key = BASE64_ENGINE.encode(format!(
"{}:{}",
auth.public_key.peek(),
auth.private_key.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: affirm::AffirmErrorResponse = res
.response
.parse_struct("AffirmErrorResponse")
.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: response.status_code,
code: response.code,
message: response.message,
reason: Some(response.error_type),
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 Affirm {
fn validate_mandate_payment(
&self,
_pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match pm_data {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"validate_mandate_payment does not support cards".to_string(),
)
.into()),
_ => Ok(()),
}
}
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(())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Affirm {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Affirm {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Affirm {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Affirm {
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 endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/v2/checkout/direct"))
}
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 = affirm::AffirmRouterData::from((amount, req));
let connector_req = affirm::AffirmPaymentsRequest::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: affirm::AffirmResponseWrapper = res
.response
.parse_struct("Affirm 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<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Affirm
{
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> {
let endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/v1/transactions"))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = affirm::AffirmCompleteAuthorizeRequest::try_from(req)?;
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: affirm::AffirmCompleteAuthorizeResponse = res
.response
.parse_struct("Affirm PaymentsCompleteAuthorizeResponse")
.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 Affirm {
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 endpoint = self.base_url(connectors);
let transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!("{endpoint}/v1/transactions/{transaction_id}",))
}
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: affirm::AffirmResponseWrapper = res
.response
.parse_struct("affirm 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 Affirm {
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 endpoint = self.base_url(connectors);
let transaction_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{endpoint}/v1/transactions/{transaction_id}/capture"
))
}
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 = affirm::AffirmRouterData::from((amount, req));
let connector_req = affirm::AffirmCaptureRequest::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: affirm::AffirmCaptureResponse = res
.response
.parse_struct("Affirm 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 Affirm {
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 endpoint = self.base_url(connectors);
let transaction_id = req.request.connector_transaction_id.clone();
Ok(format!("{endpoint}/v1/transactions/{transaction_id}/void"))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = affirm::AffirmCancelRequest::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(&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: affirm::AffirmCancelResponse = res
.response
.parse_struct("GetnetPaymentsVoidResponse")
.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 Affirm {
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 endpoint = self.base_url(connectors);
let transaction_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{endpoint}/v1/transactions/{transaction_id}/refund"
))
}
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 = affirm::AffirmRouterData::from((refund_amount, req));
let connector_req = affirm::AffirmRefundRequest::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: affirm::AffirmRefundResponse = res
.response
.parse_struct("affirm 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 Affirm {
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 endpoint = self.base_url(connectors);
let transaction_id = req.request.connector_transaction_id.clone();
Ok(format!("{endpoint}/v1/transactions/{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: affirm::AffirmRsyncResponse = res
.response
.parse_struct("affirm 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 Affirm {
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 AFFIRM_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
];
let mut affirm_supported_payment_methods = SupportedPaymentMethods::new();
affirm_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
enums::PaymentMethodType::Affirm,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
affirm_supported_payment_methods
});
static AFFIRM_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Affirm",
description: "Affirm connector is a payment gateway integration that processes Affirm’s buy now, pay later financing by managing payment authorization, capture, refunds, and transaction sync via Affirm’s API.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static AFFIRM_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Affirm {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&AFFIRM_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*AFFIRM_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&AFFIRM_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/affirm.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6121
}
|
large_file_4427257072457334809
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/barclaycard.rs
</path>
<file>
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, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{
Authorize, Capture, CompleteAuthorize, PSync, PaymentMethodToken, PreProcessing,
Session, SetupMandate, Void,
},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, CompleteAuthorizeData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData,
PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
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, PaymentsVoidType, Response},
webhooks,
};
use masking::{ExposeInterface, Mask, Maskable, PeekInterface};
use ring::{digest, hmac};
use time::OffsetDateTime;
use transformers as barclaycard;
use url::Url;
use crate::{
constants::{self, headers},
types::ResponseRouterData,
utils::{
convert_amount, PaymentsAuthorizeRequestData, RefundsRequestData,
RouterData as OtherRouterData,
},
};
pub const V_C_MERCHANT_ID: &str = "v-c-merchant-id";
#[derive(Clone)]
pub struct Barclaycard {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Barclaycard {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl Barclaycard {
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: barclaycard::BarclaycardAuthType,
host: String,
resource: &str,
payload: &String,
date: OffsetDateTime,
http_method: Method,
) -> CustomResult<String, errors::ConnectorError> {
let barclaycard::BarclaycardAuthType {
api_key,
merchant_account,
api_secret,
} = auth;
let is_post_method = matches!(http_method, Method::Post);
let digest_str = if is_post_method { "digest " } else { "" };
let headers = format!("host date (request-target) {digest_str}{V_C_MERCHANT_ID}");
let request_target = if is_post_method {
format!("(request-target): post {resource}\ndigest: SHA-256={payload}\n")
} else {
format!("(request-target): get {resource}\n")
};
let signature_string = format!(
"host: {host}\ndate: {date}\n{request_target}{V_C_MERCHANT_ID}: {}",
merchant_account.peek()
);
let key_value = consts::BASE64_ENGINE
.decode(api_secret.expose())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "connector_account_details.api_secret",
})?;
let key = hmac::Key::new(hmac::HMAC_SHA256, &key_value);
let signature_value =
consts::BASE64_ENGINE.encode(hmac::sign(&key, signature_string.as_bytes()).as_ref());
let signature_header = format!(
r#"keyid="{}", algorithm="HmacSHA256", headers="{headers}", signature="{signature_value}""#,
api_key.peek()
);
Ok(signature_header)
}
}
impl api::Payment for Barclaycard {}
impl api::PaymentSession for Barclaycard {}
impl api::PaymentsPreProcessing for Barclaycard {}
impl api::ConnectorAccessToken for Barclaycard {}
impl api::MandateSetup for Barclaycard {}
impl api::PaymentAuthorize for Barclaycard {}
impl api::PaymentSync for Barclaycard {}
impl api::PaymentCapture for Barclaycard {}
impl api::PaymentsCompleteAuthorize for Barclaycard {}
impl api::PaymentVoid for Barclaycard {}
impl api::Refund for Barclaycard {}
impl api::RefundExecute for Barclaycard {}
impl api::RefundSync for Barclaycard {}
impl api::PaymentToken for Barclaycard {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Barclaycard
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Barclaycard
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 barclaycard_req = self.get_request_body(req, connectors)?;
let http_method = self.get_http_method();
let auth = barclaycard::BarclaycardAuthType::try_from(&req.connector_auth_type)?;
let merchant_account = auth.merchant_account.clone();
let base_url = connectors.barclaycard.base_url.as_str();
let barclaycard_host =
Url::parse(base_url).change_context(errors::ConnectorError::RequestEncodingFailed)?;
let host = barclaycard_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(barclaycard_req.get_inner_value().expose().as_bytes());
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) {
headers.push((
"Digest".to_string(),
format!("SHA-256={sha256}").into_masked(),
));
}
Ok(headers)
}
}
impl ConnectorCommon for Barclaycard {
fn id(&self) -> &'static str {
"barclaycard"
}
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.barclaycard.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let auth = barclaycard::BarclaycardAuthType::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: barclaycard::BarclaycardErrorResponse = res
.response
.parse_struct("BarclaycardErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error_message = if res.status_code == 401 {
constants::CONNECTOR_UNAUTHORIZED_ERROR
} else {
hyperswitch_interfaces::consts::NO_ERROR_MESSAGE
};
match response {
transformers::BarclaycardErrorResponse::StandardError(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,
})
}
transformers::BarclaycardErrorResponse::AuthenticationError(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,
})
}
}
}
}
impl ConnectorValidation for Barclaycard {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Barclaycard {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Barclaycard {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Barclaycard
{
}
impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
for Barclaycard
{
fn get_headers(
&self,
req: &PaymentsPreProcessingRouterData,
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: &PaymentsPreProcessingRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let redirect_response = req.request.redirect_response.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "redirect_response",
},
)?;
match redirect_response.params {
Some(param) if !param.clone().peek().is_empty() => Ok(format!(
"{}risk/v1/authentications",
self.base_url(connectors)
)),
Some(_) | None => Ok(format!(
"{}risk/v1/authentication-results",
self.base_url(connectors)
)),
}
}
fn get_request_body(
&self,
req: &PaymentsPreProcessingRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_in_minor_unit = MinorUnit::new(req.request.amount.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "amount",
},
)?);
let amount = convert_amount(
self.amount_converter,
amount_in_minor_unit,
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?,
)?;
let connector_router_data = barclaycard::BarclaycardRouterData::try_from((amount, req))?;
let connector_req =
barclaycard::BarclaycardPreProcessingRequest::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: barclaycard::BarclaycardPreProcessingResponse = res
.response
.parse_struct("Barclaycard AuthEnrollmentResponse")
.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 Barclaycard {
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> {
if req.is_three_ds() && req.request.is_card() {
Ok(format!(
"{}risk/v1/authentication-setups",
ConnectorCommon::base_url(self, connectors)
))
} else {
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_in_minor_unit = MinorUnit::new(req.request.amount);
let amount = convert_amount(
self.amount_converter,
amount_in_minor_unit,
req.request.currency,
)?;
let connector_router_data = barclaycard::BarclaycardRouterData::try_from((amount, req))?;
if req.is_three_ds() && req.request.is_card() {
let connector_req =
barclaycard::BarclaycardAuthSetupRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
} else {
let connector_req =
barclaycard::BarclaycardPaymentsRequest::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> {
if data.is_three_ds() && data.request.is_card() {
let response: barclaycard::BarclaycardAuthSetupResponse = res
.response
.parse_struct("Barclaycard AuthSetupResponse")
.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,
})
} else {
let response: barclaycard::BarclaycardPaymentsResponse = res
.response
.parse_struct("Barclaycard 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)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: barclaycard::BarclaycardServerErrorResponse = res
.response
.parse_struct("BarclaycardServerErrorResponse")
.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<PSync, PaymentsSyncData, PaymentsResponseData> for Barclaycard {
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_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/{connector_payment_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(&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: barclaycard::BarclaycardTransactionResponse = res
.response
.parse_struct("Barclaycard 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 Barclaycard {
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/{connector_payment_id}/captures",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_in_minor_unit = MinorUnit::new(req.request.amount_to_capture);
let amount = convert_amount(
self.amount_converter,
amount_in_minor_unit,
req.request.currency,
)?;
let connector_router_data = barclaycard::BarclaycardRouterData::try_from((amount, req))?;
let connector_req =
barclaycard::BarclaycardCaptureRequest::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: barclaycard::BarclaycardPaymentsResponse = res
.response
.parse_struct("Barclaycard 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)
}
fn get_5xx_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: barclaycard::BarclaycardServerErrorResponse = res
.response
.parse_struct("BarclaycardServerErrorResponse")
.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<Void, PaymentsCancelData, PaymentsResponseData> for Barclaycard {
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_in_minor_unit = MinorUnit::new(req.request.amount.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "amount",
},
)?);
let amount = convert_amount(
self.amount_converter,
amount_in_minor_unit,
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "currency",
})?,
)?;
let connector_router_data = barclaycard::BarclaycardRouterData::try_from((amount, req))?;
let connector_req = barclaycard::BarclaycardVoidRequest::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(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: barclaycard::BarclaycardPaymentsResponse = res
.response
.parse_struct("Barclaycard 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: barclaycard::BarclaycardServerErrorResponse = res
.response
.parse_struct("BarclaycardServerErrorResponse")
.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<Execute, RefundsData, RefundsResponseData> for Barclaycard {
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> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{connector_payment_id}/refunds",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_in_minor_unit = MinorUnit::new(req.request.refund_amount);
let amount = convert_amount(
self.amount_converter,
amount_in_minor_unit,
req.request.currency,
)?;
let connector_router_data = barclaycard::BarclaycardRouterData::try_from((amount, req))?;
let connector_req =
barclaycard::BarclaycardRefundRequest::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: barclaycard::BarclaycardRefundResponse = res
.response
.parse_struct("barclaycard 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 Barclaycard {
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/{refund_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(&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: barclaycard::BarclaycardRsyncResponse = res
.response
.parse_struct("barclaycard 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<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Barclaycard
{
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_url(
&self,
_req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}pts/v2/payments/",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount_in_minor_unit = MinorUnit::new(req.request.amount);
let amount = convert_amount(
self.amount_converter,
amount_in_minor_unit,
req.request.currency,
)?;
let connector_router_data = barclaycard::BarclaycardRouterData::try_from((amount, req))?;
let connector_req =
barclaycard::BarclaycardPaymentsRequest::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: barclaycard::BarclaycardPaymentsResponse = res
.response
.parse_struct("Barclaycard 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: barclaycard::BarclaycardServerErrorResponse = res
.response
.parse_struct("BarclaycardServerErrorResponse")
.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,
})
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Barclaycard {
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 BARCLAYCARD_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::Mastercard,
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::Maestro,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::UnionPay,
];
let mut barclaycard_supported_payment_methods = SupportedPaymentMethods::new();
barclaycard_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
barclaycard_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
barclaycard_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,
},
);
barclaycard_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
barclaycard_supported_payment_methods
});
static BARCLAYCARD_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "BarclayCard SmartPay Fuse",
description: "Barclaycard, part of Barclays Bank UK PLC, is a leading global payment business that helps consumers, retailers and businesses to make and take payments flexibly, and to access short-term credit and point of sale finance.",
connector_type: enums::HyperswitchConnectorCategory::BankAcquirer,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static BARCLAYCARD_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Barclaycard {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&BARCLAYCARD_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BARCLAYCARD_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&BARCLAYCARD_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/barclaycard.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 10278
}
|
large_file_1247609101905332824
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/mollie.rs
</path>
<file>
pub mod transformers;
use common_enums::enums;
use common_utils::{
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, 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,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
consts, errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use lazy_static::lazy_static;
use masking::{Mask, PeekInterface};
use transformers as mollie;
// use self::mollie::{webhook_headers, MollieWebhookBodyEventType};
use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount};
#[derive(Clone)]
pub struct Mollie {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Mollie {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl api::Payment for Mollie {}
impl api::PaymentSession for Mollie {}
impl api::ConnectorAccessToken for Mollie {}
impl api::MandateSetup for Mollie {}
impl api::PaymentToken for Mollie {}
impl api::PaymentAuthorize for Mollie {}
impl api::PaymentsCompleteAuthorize for Mollie {}
impl api::PaymentSync for Mollie {}
impl api::PaymentCapture for Mollie {}
impl api::PaymentVoid for Mollie {}
impl api::Refund for Mollie {}
impl api::RefundExecute for Mollie {}
impl api::RefundSync for Mollie {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Mollie
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> {
self.get_auth_header(&req.connector_auth_type)
}
}
impl ConnectorCommon for Mollie {
fn id(&self) -> &'static str {
"mollie"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.mollie.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = mollie::MollieAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", auth.api_key.peek()).into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: mollie::MollieErrorResponse = res
.response
.parse_struct("MollieErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: response.status,
code: response
.title
.unwrap_or_else(|| consts::NO_ERROR_CODE.to_string()),
message: response.detail,
reason: response.field,
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 Mollie {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Mollie {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Mollie {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Mollie
{
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> {
let base_url = connectors
.mollie
.secondary_base_url
.as_ref()
.ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?;
Ok(format!("{base_url}card-tokens"))
}
fn get_request_body(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = mollie::MollieCardTokenRequest::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(&types::TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::TokenizationType::get_headers(self, req, connectors)?)
.set_body(types::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: mollie::MollieCardTokenResponse = res
.response
.parse_struct("MollieTokenResponse")
.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 Mollie {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Mollie".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Mollie {
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(format!("{}payments", self.base_url(connectors)))
}
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 router_obj = mollie::MollieRouterData::from((amount, req));
let connector_req = mollie::MolliePaymentsRequest::try_from(&router_obj)?;
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: mollie::MolliePaymentsResponse = res
.response
.parse_struct("MolliePaymentsResponse")
.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 Mollie
{
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Mollie {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}payments/{}",
self.base_url(connectors),
req.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::RequestEncodingFailed)?
))
}
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: mollie::MolliePaymentsResponse = res
.response
.parse_struct("mollie 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 Mollie {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: self.id().to_string(),
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Mollie {
fn build_request(
&self,
_req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Void".to_string(),
connector: self.id().to_string(),
}
.into())
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Mollie {
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!(
"{}payments/{}/refunds",
self.base_url(connectors),
req.request.connector_transaction_id
))
}
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 router_obj = mollie::MollieRouterData::from((amount, req));
let connector_req = mollie::MollieRefundRequest::try_from(&router_obj)?;
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: mollie::RefundResponse = res
.response
.parse_struct("MollieRefundResponse")
.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 Mollie {
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
.connector_refund_id
.clone()
.ok_or(errors::ConnectorError::RequestEncodingFailed)?;
Ok(format!(
"{}payments/{}/refunds/{}",
self.base_url(connectors),
req.request.connector_transaction_id,
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)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: mollie::RefundResponse = res
.response
.parse_struct("MollieRefundSyncResponse")
.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 Mollie {
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))
}
}
impl ConnectorRedirectResponse for Mollie {
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)
}
}
}
}
// impl ConnectorSpecifications for Mollie {}
lazy_static! {
static ref MOLLIE_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::CartesBancaires,
];
let mut mollie_supported_payment_methods = SupportedPaymentMethods::new();
mollie_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
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::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
mollie_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
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::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
mollie_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Eps,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
mollie_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Giropay,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
mollie_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Ideal,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
mollie_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Sofort,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
mollie_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Przelewy24,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
mollie_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::BancontactCard,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
mollie_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Paypal,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
mollie_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
mollie_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
enums::PaymentMethodType::Sepa,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
mollie_supported_payment_methods
};
static ref MOLLIE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "MOLLIE",
description:
"Mollie is a Developer-friendly processor providing simple and customizable payment solutions for businesses of all sizes.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static ref MOLLIE_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
}
impl ConnectorSpecifications for Mollie {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*MOLLIE_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*MOLLIE_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*MOLLIE_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/mollie.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6095
}
|
large_file_4931826910321176333
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/tesouro.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
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, RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts, errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{Mask, PeekInterface};
use transformers as tesouro;
use crate::{constants::headers, types::ResponseRouterData, utils as connector_utils};
#[derive(Clone)]
pub struct Tesouro {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Tesouro {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Tesouro {}
impl api::PaymentSession for Tesouro {}
impl api::ConnectorAccessToken for Tesouro {}
impl api::MandateSetup for Tesouro {}
impl api::PaymentAuthorize for Tesouro {}
impl api::PaymentSync for Tesouro {}
impl api::PaymentCapture for Tesouro {}
impl api::PaymentVoid for Tesouro {}
impl api::Refund for Tesouro {}
impl api::RefundExecute for Tesouro {}
impl api::RefundSync for Tesouro {}
impl api::PaymentToken for Tesouro {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Tesouro
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Tesouro
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 headers = vec![(
headers::CONTENT_TYPE.to_string(),
self.common_get_content_type().to_string().into(),
)];
let access_token = req
.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_header = (
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", access_token.token.peek()).into_masked(),
);
headers.push(auth_header);
Ok(headers)
}
}
impl ConnectorCommon for Tesouro {
fn id(&self) -> &'static str {
"tesouro"
}
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.tesouro.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let status_code = res.status_code;
let response: Result<tesouro::TesouroGraphQlErrorResponse, _> =
res.response.parse_struct("TesouroGraphQlErrorResponse");
match response {
Ok(response) => {
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let error = response.errors.first();
let error_extensions = error.and_then(|error_data| error_data.extensions.clone());
Ok(ErrorResponse {
status_code,
code: error_extensions
.as_ref()
.and_then(|ext| ext.code.clone())
.unwrap_or(consts::NO_ERROR_CODE.to_string()),
message: error
.map(|error_data| error_data.message.clone())
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: error_extensions.as_ref().and_then(|ext| ext.reason.clone()),
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": status_code})));
router_env::logger::error!(deserialization_error =? error_msg);
connector_utils::handle_json_response_deserialization_failure(res, "tesouro")
}
}
}
}
impl ConnectorValidation for Tesouro {
fn validate_mandate_payment(
&self,
_pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match pm_data {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"validate_mandate_payment does not support cards".to_string(),
)
.into()),
_ => Ok(()),
}
}
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(())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Tesouro {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Tesouro {
fn get_headers(
&self,
_req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let header = vec![(
headers::CONTENT_TYPE.to_string(),
types::RefreshTokenType::get_content_type(self)
.to_string()
.into(),
)];
Ok(header)
}
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/openid/connect/token",
self.base_url(connectors).to_owned()
))
}
fn get_http_method(&self) -> Method {
Method::Post
}
fn get_content_type(&self) -> &'static str {
mime::APPLICATION_WWW_FORM_URLENCODED.as_ref()
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = tesouro::TesouroAccessTokenRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let req = Some(
RequestBuilder::new()
.method(types::RefreshTokenType::get_http_method(self))
.url(&types::RefreshTokenType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefreshTokenType::get_headers(self, req, connectors)?)
.set_body(types::RefreshTokenType::get_request_body(
self, req, connectors,
)?)
.build(),
);
Ok(req)
}
fn handle_response(
&self,
data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: tesouro::TesouroAccessTokenResponse = res
.response
.parse_struct("tesouro TesouroAccessTokenResponse")
.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> {
let response: tesouro::TesouroAccessTokenErrorResponse = res
.response
.parse_struct("tesouro TesouroAccessTokenErrorResponse")
.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.clone(),
message: response
.error_description
.clone()
.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
reason: response.error_uri.clone(),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Tesouro {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Tesouro".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Tesouro {
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::Post
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/graphql", 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 = tesouro::TesouroRouterData::from((amount, req));
let connector_req = tesouro::TesouroAuthorizeRequest::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: tesouro::TesouroAuthorizeResponse = res
.response
.parse_struct("Tesouro TesouroAuthorizeResponse")
.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 Tesouro {
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!("{}/graphql", self.base_url(connectors).to_owned()))
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = tesouro::TesouroSyncRequest::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(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(types::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: tesouro::TesouroSyncResponse = res
.response
.parse_struct("tesouro TesouroSyncResponse")
.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 Tesouro {
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!("{}/graphql", 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 = tesouro::TesouroRouterData::from((amount, req));
let connector_req = tesouro::TesouroCaptureRequest::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: tesouro::TesouroCaptureResponse = res
.response
.parse_struct("Tesouro TesouroCaptureResponse")
.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 Tesouro {
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!("{}/graphql", self.base_url(connectors).to_owned()))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = tesouro::TesouroVoidRequest::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(&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: tesouro::TesouroVoidResponse = res
.response
.parse_struct("Tesouro TesouroVoidResponse")
.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 Tesouro {
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!("{}/graphql", 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 = tesouro::TesouroRouterData::from((refund_amount, req));
let connector_req = tesouro::TesouroRefundRequest::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: tesouro::TesouroRefundResponse = res
.response
.parse_struct("tesouro TesouroRefundResponse")
.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 Tesouro {
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!("{}/graphql", self.base_url(connectors).to_owned()))
}
fn get_request_body(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = tesouro::TesouroSyncRequest::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(&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: tesouro::TesouroSyncResponse = res
.response
.parse_struct("tesouro TesouroSyncResponse")
.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 Tesouro {
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 TESOURO_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
];
let supported_card_network = vec![
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Maestro,
common_enums::CardNetwork::UnionPay,
];
let mut tesouro_supported_payment_methods = SupportedPaymentMethods::new();
tesouro_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
tesouro_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
tesouro_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,
},
);
tesouro_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,
},
);
tesouro_supported_payment_methods
});
static TESOURO_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Tesouro",
description: "Tesouro is a Miami-based fintech company that provides a cloud-native payment gateway platform, offering APIs and streamlined data inflows to connect software companies, banks, and payment facilitators for seamless payment processing",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static TESOURO_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Tesouro {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&TESOURO_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*TESOURO_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&TESOURO_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 =
tesouro::tesouro_constants::MAX_PAYMENT_REFERENCE_ID_LENGTH;
nanoid::nanoid!(max_payment_reference_id_length)
}
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/tesouro.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7210
}
|
large_file_-4680481124332164627
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/netcetera.rs
</path>
<file>
pub mod netcetera_types;
pub mod transformers;
use std::fmt::Debug;
use api_models::webhooks::{AuthenticationIdType, IncomingWebhookEvent, ObjectReferenceId};
use common_utils::{
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
authentication::{
Authentication, PostAuthentication, PreAuthentication, PreAuthenticationVersionCall,
},
AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session,
SetupMandate, Void,
},
router_request_types::{
authentication::{
ConnectorAuthenticationRequestData, ConnectorPostAuthenticationRequestData,
PreAuthNRequestData,
},
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
AuthenticationResponseData, ConnectorInfo, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods,
},
};
use hyperswitch_interfaces::{
api::{
authentication::{
ConnectorAuthentication, ConnectorPostAuthentication, ConnectorPreAuthentication,
ConnectorPreAuthenticationVersionCall, ExternalAuthentication,
},
*,
},
authentication::ExternalAuthenticationPayload,
configs::Connectors,
errors::ConnectorError,
events::connector_api_logs::ConnectorEvent,
types::Response,
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::Maskable;
use transformers as netcetera;
use crate::{
constants::headers,
types::{
ConnectorAuthenticationRouterData, ConnectorAuthenticationType,
ConnectorPreAuthenticationType, PreAuthNRouterData, ResponseRouterData,
},
};
#[derive(Debug, Clone)]
pub struct Netcetera;
impl Payment for Netcetera {}
impl PaymentSession for Netcetera {}
impl ConnectorAccessToken for Netcetera {}
impl MandateSetup for Netcetera {}
impl PaymentAuthorize for Netcetera {}
impl PaymentSync for Netcetera {}
impl PaymentCapture for Netcetera {}
impl PaymentVoid for Netcetera {}
impl Refund for Netcetera {}
impl RefundExecute for Netcetera {}
impl RefundSync for Netcetera {}
impl PaymentToken for Netcetera {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Netcetera
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Netcetera
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, 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 Netcetera {
fn id(&self) -> &'static str {
"netcetera"
}
fn get_currency_unit(&self) -> CurrencyUnit {
CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.netcetera.base_url.as_ref()
}
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
Ok(vec![])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
let response: netcetera::NetceteraErrorResponse = res
.response
.parse_struct("NetceteraErrorResponse")
.change_context(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_details.error_code,
message: response.error_details.error_description,
reason: response.error_details.error_detail,
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 Netcetera {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Netcetera {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Netcetera {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Netcetera
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Netcetera {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Netcetera {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Netcetera {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Netcetera {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Netcetera {}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Netcetera {}
#[async_trait::async_trait]
impl IncomingWebhook for Netcetera {
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, ConnectorError> {
let webhook_body: netcetera::ResultsResponseData = request
.body
.parse_struct("netcetera ResultsResponseData")
.change_context(ConnectorError::WebhookBodyDecodingFailed)?;
Ok(ObjectReferenceId::ExternalAuthenticationID(
AuthenticationIdType::ConnectorAuthenticationId(webhook_body.three_ds_server_trans_id),
))
}
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, ConnectorError> {
Ok(IncomingWebhookEvent::ExternalAuthenticationARes)
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> {
let webhook_body_value: netcetera::ResultsResponseData = request
.body
.parse_struct("netcetera ResultsResponseDatae")
.change_context(ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Box::new(webhook_body_value))
}
fn get_external_authentication_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ExternalAuthenticationPayload, ConnectorError> {
let webhook_body: netcetera::ResultsResponseData = request
.body
.parse_struct("netcetera ResultsResponseData")
.change_context(ConnectorError::WebhookBodyDecodingFailed)?;
let challenge_cancel = webhook_body
.results_request
.as_ref()
.and_then(|v| v.get("challengeCancel").and_then(|v| v.as_str()))
.map(|s| s.to_string());
let challenge_code_reason = webhook_body
.results_request
.as_ref()
.and_then(|v| v.get("transStatusReason").and_then(|v| v.as_str()))
.map(|s| s.to_string());
Ok(ExternalAuthenticationPayload {
trans_status: webhook_body
.trans_status
.unwrap_or(common_enums::TransactionStatus::InformationOnly),
authentication_value: webhook_body.authentication_value,
eci: webhook_body.eci,
challenge_cancel,
challenge_code_reason,
})
}
}
fn build_endpoint(
base_url: &str,
connector_metadata: &Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<String, ConnectorError> {
let metadata = netcetera::NetceteraMetaData::try_from(connector_metadata)?;
let endpoint_prefix = metadata.endpoint_prefix;
Ok(base_url.replace("{{merchant_endpoint_prefix}}", &endpoint_prefix))
}
impl ConnectorPreAuthentication for Netcetera {}
impl ConnectorPreAuthenticationVersionCall for Netcetera {}
impl ExternalAuthentication for Netcetera {}
impl ConnectorAuthentication for Netcetera {}
impl ConnectorPostAuthentication for Netcetera {}
impl ConnectorIntegration<PreAuthentication, PreAuthNRequestData, AuthenticationResponseData>
for Netcetera
{
fn get_headers(
&self,
req: &PreAuthNRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PreAuthNRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
Ok(format!("{base_url}/3ds/versioning"))
}
fn get_request_body(
&self,
req: &PreAuthNRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let connector_router_data = netcetera::NetceteraRouterData::try_from((0, req))?;
let req_obj =
netcetera::NetceteraPreAuthenticationRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(req_obj)))
}
fn build_request(
&self,
req: &PreAuthNRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
let netcetera_auth_type = netcetera::NetceteraAuthType::try_from(&req.connector_auth_type)?;
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&ConnectorPreAuthenticationType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(ConnectorPreAuthenticationType::get_headers(
self, req, connectors,
)?)
.set_body(ConnectorPreAuthenticationType::get_request_body(
self, req, connectors,
)?)
.add_certificate(Some(netcetera_auth_type.certificate))
.add_certificate_key(Some(netcetera_auth_type.private_key))
.build(),
))
}
fn handle_response(
&self,
data: &PreAuthNRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PreAuthNRouterData, ConnectorError> {
let response: netcetera::NetceteraPreAuthenticationResponse = res
.response
.parse_struct("netcetera NetceteraPreAuthenticationResponse")
.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
ConnectorIntegration<
Authentication,
ConnectorAuthenticationRequestData,
AuthenticationResponseData,
> for Netcetera
{
fn get_headers(
&self,
req: &ConnectorAuthenticationRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &ConnectorAuthenticationRouterData,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
let base_url = build_endpoint(self.base_url(connectors), &req.connector_meta_data)?;
Ok(format!("{base_url}/3ds/authentication"))
}
fn get_request_body(
&self,
req: &ConnectorAuthenticationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let connector_router_data = netcetera::NetceteraRouterData::try_from((
&self.get_currency_unit(),
req.request
.currency
.ok_or(ConnectorError::MissingRequiredField {
field_name: "currency",
})?,
req.request
.amount
.ok_or(ConnectorError::MissingRequiredField {
field_name: "amount",
})?,
req,
))?;
let req_obj = netcetera::NetceteraAuthenticationRequest::try_from(&connector_router_data);
Ok(RequestContent::Json(Box::new(req_obj?)))
}
fn build_request(
&self,
req: &ConnectorAuthenticationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
let netcetera_auth_type = netcetera::NetceteraAuthType::try_from(&req.connector_auth_type)?;
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&ConnectorAuthenticationType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(ConnectorAuthenticationType::get_headers(
self, req, connectors,
)?)
.set_body(ConnectorAuthenticationType::get_request_body(
self, req, connectors,
)?)
.add_certificate(Some(netcetera_auth_type.certificate))
.add_certificate_key(Some(netcetera_auth_type.private_key))
.build(),
))
}
fn handle_response(
&self,
data: &ConnectorAuthenticationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<ConnectorAuthenticationRouterData, ConnectorError> {
let response: netcetera::NetceteraAuthenticationResponse = res
.response
.parse_struct("NetceteraAuthenticationResponse")
.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
ConnectorIntegration<
PostAuthentication,
ConnectorPostAuthenticationRequestData,
AuthenticationResponseData,
> for Netcetera
{
}
impl
ConnectorIntegration<
PreAuthenticationVersionCall,
PreAuthNRequestData,
AuthenticationResponseData,
> for Netcetera
{
}
static NETCETERA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Netcetera",
description: "Netcetera authentication provider for comprehensive 3D Secure solutions including certified ACS, Directory Server, and multi-protocol EMV 3DS supports",
connector_type: common_enums::HyperswitchConnectorCategory::AuthenticationProvider,
integration_status: common_enums::ConnectorIntegrationStatus::Sandbox,
};
impl ConnectorSpecifications for Netcetera {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&NETCETERA_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
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/netcetera.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 3618
}
|
large_file_7004871999254420143
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/novalnet.rs
</path>
<file>
pub mod transformers;
use core::str;
use std::{collections::HashSet, sync::LazyLock};
use base64::Engine;
use common_enums::enums;
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::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, 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, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
disputes, errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{ExposeInterface, Mask};
use transformers as novalnet;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, PaymentMethodDataType, PaymentsAuthorizeRequestData},
};
#[derive(Clone)]
pub struct Novalnet {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Novalnet {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Novalnet {}
impl api::PaymentSession for Novalnet {}
impl api::ConnectorAccessToken for Novalnet {}
impl api::MandateSetup for Novalnet {}
impl api::PaymentAuthorize for Novalnet {}
impl api::PaymentSync for Novalnet {}
impl api::PaymentCapture for Novalnet {}
impl api::PaymentVoid for Novalnet {}
impl api::Refund for Novalnet {}
impl api::RefundExecute for Novalnet {}
impl api::RefundSync for Novalnet {}
impl api::PaymentToken for Novalnet {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Novalnet
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Novalnet
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 Novalnet {
fn id(&self) -> &'static str {
"novalnet"
}
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.novalnet.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = novalnet::NovalnetAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let api_key: String = auth.payment_access_key.expose();
let encoded_api_key = common_utils::consts::BASE64_ENGINE.encode(api_key);
Ok(vec![(
headers::X_NN_ACCESS_KEY.to_string(),
encoded_api_key.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: novalnet::NovalnetErrorResponse = res
.response
.parse_struct("NovalnetErrorResponse")
.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 Novalnet {
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> {
if data.encoded_data.is_some()
|| data
.connector_transaction_id
.get_connector_transaction_id()
.is_ok()
{
return Ok(());
}
Err(errors::ConnectorError::MissingConnectorTransactionID.into())
}
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd: HashSet<PaymentMethodDataType> = HashSet::from([
PaymentMethodDataType::Card,
PaymentMethodDataType::GooglePay,
PaymentMethodDataType::PaypalRedirect,
PaymentMethodDataType::ApplePay,
]);
utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl ConnectorRedirectResponse for Novalnet {
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 => Ok(enums::CallConnectorAction::Trigger),
_ => Ok(enums::CallConnectorAction::Avoid),
}
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Novalnet {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Novalnet {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Novalnet
{
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> {
let endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/payment"))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = novalnet::NovalnetPaymentsRequest::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(&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: novalnet::NovalnetPaymentsResponse = res
.response
.parse_struct("Novalnet 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<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Novalnet {
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 endpoint = self.base_url(connectors);
match req.request.is_auto_capture()? {
true => Ok(format!("{endpoint}/payment")),
false => Ok(format!("{endpoint}/authorize")),
}
}
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 = novalnet::NovalnetRouterData::from((amount, req));
let connector_req = novalnet::NovalnetPaymentsRequest::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: novalnet::NovalnetPaymentsResponse = res
.response
.parse_struct("Novalnet 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 Novalnet {
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 endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/transaction/details"))
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = novalnet::NovalnetSyncRequest::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(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(types::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: novalnet::NovalnetPSyncResponse = res
.response
.parse_struct("novalnet 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 Novalnet {
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 endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/transaction/capture"))
}
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 = novalnet::NovalnetRouterData::from((amount, req));
let connector_req = novalnet::NovalnetCaptureRequest::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: novalnet::NovalnetCaptureResponse = res
.response
.parse_struct("Novalnet 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<Execute, RefundsData, RefundsResponseData> for Novalnet {
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 endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/transaction/refund"))
}
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 = novalnet::NovalnetRouterData::from((refund_amount, req));
let connector_req = novalnet::NovalnetRefundRequest::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: novalnet::NovalnetRefundResponse = res
.response
.parse_struct("novalnet 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 Novalnet {
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 endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/transaction/details"))
}
fn get_request_body(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = novalnet::NovalnetSyncRequest::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(&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: novalnet::NovalnetRefundSyncResponse = res
.response
.parse_struct("novalnet 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<Void, PaymentsCancelData, PaymentsResponseData> for Novalnet {
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 endpoint = self.base_url(connectors);
Ok(format!("{endpoint}/transaction/cancel"))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = novalnet::NovalnetCancelRequest::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(&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: novalnet::NovalnetCancelResponse = res
.response
.parse_struct("NovalnetPaymentsVoidResponse")
.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_webhook_object_from_body(
body: &[u8],
) -> CustomResult<novalnet::NovalnetWebhookNotificationResponse, errors::ConnectorError> {
let novalnet_webhook_notification_response = body
.parse_struct("NovalnetWebhookNotificationResponse")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(novalnet_webhook_notification_response)
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Novalnet {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::Sha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::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)?;
hex::decode(notif_item.event.checksum)
.change_context(errors::ConnectorError::WebhookVerificationSecretInvalid)
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
let (amount, currency) = match notif.transaction {
novalnet::NovalnetWebhookTransactionData::CaptureTransactionData(data) => {
(data.amount, data.currency)
}
novalnet::NovalnetWebhookTransactionData::CancelTransactionData(data) => {
(data.amount, data.currency)
}
novalnet::NovalnetWebhookTransactionData::RefundsTransactionData(data) => {
(data.amount, data.currency)
}
novalnet::NovalnetWebhookTransactionData::SyncTransactionData(data) => {
(data.amount, data.currency)
}
};
let amount = amount
.map(|amount| amount.to_string())
.unwrap_or("".to_string());
let currency = currency
.map(|amount| amount.to_string())
.unwrap_or("".to_string());
let secret_auth = String::from_utf8(connector_webhook_secrets.secret.to_vec())
.change_context(errors::ConnectorError::WebhookVerificationSecretInvalid)
.attach_printable("Could not convert webhook secret auth to UTF-8")?;
let reversed_secret_auth = novalnet::reverse_string(&secret_auth);
let message = format!(
"{}{}{}{}{}{}",
notif.event.tid,
notif.event.event_type,
notif.result.status,
amount,
currency,
reversed_secret_auth
);
Ok(message.into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let transaction_order_no = match notif.transaction {
novalnet::NovalnetWebhookTransactionData::CaptureTransactionData(data) => data.order_no,
novalnet::NovalnetWebhookTransactionData::CancelTransactionData(data) => data.order_no,
novalnet::NovalnetWebhookTransactionData::RefundsTransactionData(data) => data.order_no,
novalnet::NovalnetWebhookTransactionData::SyncTransactionData(data) => data.order_no,
};
if novalnet::is_refund_event(¬if.event.event_type) {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(notif.event.tid.to_string()),
))
} else {
match transaction_order_no {
Some(order_no) => Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::PaymentAttemptId(order_no),
)),
None => Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
notif.event.tid.to_string(),
),
)),
}
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
let optional_transaction_status = match notif.transaction {
novalnet::NovalnetWebhookTransactionData::CaptureTransactionData(data) => data.status,
novalnet::NovalnetWebhookTransactionData::CancelTransactionData(data) => data.status,
novalnet::NovalnetWebhookTransactionData::RefundsTransactionData(data) => {
Some(data.status)
}
novalnet::NovalnetWebhookTransactionData::SyncTransactionData(data) => {
Some(data.status)
}
};
let transaction_status =
optional_transaction_status.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "transaction_status",
})?;
// NOTE: transaction_status will always be present for Webhooks
// But we are handling optional type here, since we are reusing TransactionData Struct from NovalnetPaymentsResponseTransactionData for Webhooks response too
// In NovalnetPaymentsResponseTransactionData, transaction_status is optional
let incoming_webhook_event =
novalnet::get_incoming_webhook_event(notif.event.event_type, transaction_status);
Ok(incoming_webhook_event)
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif = get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(notif))
}
fn get_dispute_details(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<disputes::DisputePayload, errors::ConnectorError> {
let notif: transformers::NovalnetWebhookNotificationResponse =
get_webhook_object_from_body(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let (amount, currency, reason, reason_code) = match notif.transaction {
novalnet::NovalnetWebhookTransactionData::CaptureTransactionData(data) => {
(data.amount, data.currency, None, None)
}
novalnet::NovalnetWebhookTransactionData::CancelTransactionData(data) => {
(data.amount, data.currency, None, None)
}
novalnet::NovalnetWebhookTransactionData::RefundsTransactionData(data) => {
(data.amount, data.currency, None, None)
}
novalnet::NovalnetWebhookTransactionData::SyncTransactionData(data) => {
(data.amount, data.currency, data.reason, data.reason_code)
}
};
let dispute_status =
novalnet::get_novalnet_dispute_status(notif.event.event_type).to_string();
Ok(disputes::DisputePayload {
amount: utils::convert_amount(
self.amount_converter,
amount.ok_or(errors::ConnectorError::AmountConversionFailed)?,
novalnet::option_to_result(currency)?,
)?,
currency: novalnet::option_to_result(currency)?,
dispute_stage: api_models::enums::DisputeStage::Dispute,
connector_dispute_id: notif.event.tid.to_string(),
connector_reason: reason,
connector_reason_code: reason_code,
challenge_required_by: None,
connector_status: dispute_status,
created_at: None,
updated_at: None,
})
}
}
static NOVALNET_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::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::Interac,
];
let mut novalnet_supported_payment_methods = SupportedPaymentMethods::new();
novalnet_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(),
}
}),
),
},
);
novalnet_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(),
}
}),
),
},
);
novalnet_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, // three-ds needed for googlepay
},
);
novalnet_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,
},
);
novalnet_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Paypal,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
novalnet_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
enums::PaymentMethodType::Sepa,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
novalnet_supported_payment_methods.add(
enums::PaymentMethod::BankDebit,
enums::PaymentMethodType::SepaGuarenteedDebit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
novalnet_supported_payment_methods
});
static NOVALNET_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Novalnet",
description: "Novalnet provides tailored, data-driven payment solutions that maximize acceptance, boost conversions, and deliver seamless customer experiences worldwide.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static NOVALNET_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 4] = [
enums::EventClass::Payments,
enums::EventClass::Refunds,
enums::EventClass::Disputes,
enums::EventClass::Mandates,
];
impl ConnectorSpecifications for Novalnet {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&NOVALNET_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*NOVALNET_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&NOVALNET_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/novalnet.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 8875
}
|
large_file_3930730880125116659
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/peachpayments.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use common_enums::{self, enums};
use common_utils::{
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt},
id_type,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::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, 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, Secret};
use transformers as peachpayments;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, RefundsRequestData},
};
#[derive(Clone)]
pub struct Peachpayments {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Peachpayments {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Peachpayments {}
impl api::PaymentSession for Peachpayments {}
impl api::ConnectorAccessToken for Peachpayments {}
impl api::MandateSetup for Peachpayments {}
impl api::PaymentAuthorize for Peachpayments {}
impl api::PaymentSync for Peachpayments {}
impl api::PaymentCapture for Peachpayments {}
impl api::PaymentVoid for Peachpayments {}
impl api::Refund for Peachpayments {}
impl api::RefundExecute for Peachpayments {}
impl api::RefundSync for Peachpayments {}
impl api::PaymentToken for Peachpayments {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Peachpayments
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Peachpayments
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 Peachpayments {
fn id(&self) -> &'static str {
"peachpayments"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
// PeachPayments Card Gateway accepts amounts in cents (minor unit)
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.peachpayments.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = peachpayments::PeachpaymentsAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![
("x-api-key".to_string(), auth.api_key.expose().into_masked()),
(
"x-tenant-id".to_string(),
auth.tenant_id.expose().into_masked(),
),
("x-exi-auth-ver".to_string(), "v1".to_string().into_masked()),
])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: peachpayments::PeachpaymentsErrorResponse = res
.response
.parse_struct("PeachpaymentsErrorResponse")
.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_ref.clone(),
message: response.message.clone(),
reason: Some(response.message.clone()),
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 Peachpayments {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Peachpayments {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Peachpayments {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Peachpayments
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented(
"Setup Mandate flow for Peachpayments".to_string(),
)
.into())
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for Peachpayments
{
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!("{}/transactions", 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 = peachpayments::PeachpaymentsRouterData::from((amount, req));
let connector_req =
peachpayments::PeachpaymentsPaymentsRequest::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: peachpayments::PeachpaymentsPaymentsResponse = res
.response
.parse_struct("Peachpayments 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 Peachpayments {
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_transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/transactions/{}",
self.base_url(connectors),
connector_transaction_id
))
}
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: peachpayments::PeachpaymentsPaymentsResponse = res
.response
.parse_struct("peachpayments 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 Peachpayments {
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_transaction_id = &req.request.connector_transaction_id;
Ok(format!(
"{}/transactions/{}/confirm",
self.base_url(connectors),
connector_transaction_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 = peachpayments::PeachpaymentsRouterData::from((amount, req));
let connector_req =
peachpayments::PeachpaymentsConfirmRequest::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: peachpayments::PeachpaymentsConfirmResponse = res
.response
.parse_struct("Peachpayments 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 Peachpayments {
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 connector_transaction_id = &req.request.connector_transaction_id;
Ok(format!(
"{}/transactions/{}/void",
self.base_url(connectors),
connector_transaction_id
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = peachpayments::PeachpaymentsVoidRequest::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(&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: peachpayments::PeachpaymentsPaymentsResponse = res
.response
.parse_struct("Peachpayments PaymentsVoidResponse")
.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 Peachpayments {
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!(
"{}/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 = peachpayments::PeachpaymentsRefundRequest::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(&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: peachpayments::PeachpaymentsRefundResponse = res
.response
.parse_struct("PeachpaymentsRefundResponse")
.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 Peachpayments {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}/transactions/{}",
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)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: peachpayments::PeachpaymentsRsyncResponse = res
.response
.parse_struct("PeachpaymentsRsyncResponse")
.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 Peachpayments {
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook_body: peachpayments::PeachpaymentsIncomingWebhook = request
.body
.parse_struct("PeachpaymentsIncomingWebhook")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let reference_id = webhook_body
.transaction
.as_ref()
.map(|txn| txn.reference_id.clone())
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::PaymentAttemptId(reference_id),
))
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let webhook_body: peachpayments::PeachpaymentsIncomingWebhook = request
.body
.parse_struct("PeachpaymentsIncomingWebhook")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
match webhook_body.webhook_type.as_str() {
"transaction" => {
if let Some(transaction) = webhook_body.transaction {
match transaction.transaction_result {
peachpayments::PeachpaymentsPaymentStatus::Successful
| peachpayments::PeachpaymentsPaymentStatus::ApprovedConfirmed => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
peachpayments::PeachpaymentsPaymentStatus::Authorized
| peachpayments::PeachpaymentsPaymentStatus::Approved => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess)
}
peachpayments::PeachpaymentsPaymentStatus::Pending => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
}
peachpayments::PeachpaymentsPaymentStatus::Declined
| peachpayments::PeachpaymentsPaymentStatus::Failed => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)
}
peachpayments::PeachpaymentsPaymentStatus::Voided
| peachpayments::PeachpaymentsPaymentStatus::Reversed => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentCancelled)
}
peachpayments::PeachpaymentsPaymentStatus::ThreedsRequired => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
}
} else {
Err(errors::ConnectorError::WebhookEventTypeNotFound)
}
}
_ => Err(errors::ConnectorError::WebhookEventTypeNotFound),
}
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook_body: peachpayments::PeachpaymentsIncomingWebhook = request
.body
.parse_struct("PeachpaymentsIncomingWebhook")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Box::new(webhook_body))
}
async fn verify_webhook_source(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &id_type::MerchantId,
_connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
_connector_name: &str,
) -> CustomResult<bool, errors::ConnectorError> {
Ok(false)
}
}
static PEACHPAYMENTS_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
];
let mut peachpayments_supported_payment_methods = SupportedPaymentMethods::new();
peachpayments_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
peachpayments_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
peachpayments_supported_payment_methods
});
static PEACHPAYMENTS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Peachpayments",
description: "The secure African payment gateway with easy integrations, 365-day support, and advanced orchestration.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Beta,
};
static PEACHPAYMENTS_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] =
[enums::EventClass::Payments];
impl ConnectorSpecifications for Peachpayments {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&PEACHPAYMENTS_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*PEACHPAYMENTS_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&PEACHPAYMENTS_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/peachpayments.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6292
}
|
large_file_145677088559165283
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/gigadat.rs
</path>
<file>
pub mod transformers;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts,
crypto::Encryptable,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::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, 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, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundsRouterData,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::{PoCreate, PoFulfill, PoQuote, PoSync},
types::{PayoutsData, PayoutsResponseData, PayoutsRouterData},
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::types::{
PayoutCreateType, PayoutFulfillType, PayoutQuoteType, PayoutSyncType,
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts as api_consts, errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use lazy_static::lazy_static;
use masking::{ExposeInterface, Mask, PeekInterface};
#[cfg(feature = "payouts")]
use router_env::{instrument, tracing};
use transformers as gigadat;
use url::form_urlencoded;
use uuid::Uuid;
#[cfg(feature = "payouts")]
use crate::utils::{to_payout_connector_meta, RouterData as RouterDataTrait};
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Gigadat {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Gigadat {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Gigadat {}
impl api::PaymentSession for Gigadat {}
impl api::ConnectorAccessToken for Gigadat {}
impl api::MandateSetup for Gigadat {}
impl api::PaymentAuthorize for Gigadat {}
impl api::PaymentSync for Gigadat {}
impl api::PaymentCapture for Gigadat {}
impl api::PaymentVoid for Gigadat {}
impl api::Refund for Gigadat {}
impl api::RefundExecute for Gigadat {}
impl api::RefundSync for Gigadat {}
impl api::PaymentToken for Gigadat {}
impl api::Payouts for Gigadat {}
#[cfg(feature = "payouts")]
impl api::PayoutQuote for Gigadat {}
#[cfg(feature = "payouts")]
impl api::PayoutCreate for Gigadat {}
#[cfg(feature = "payouts")]
impl api::PayoutFulfill for Gigadat {}
#[cfg(feature = "payouts")]
impl api::PayoutSync for Gigadat {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Gigadat
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Gigadat
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 Gigadat {
fn id(&self) -> &'static str {
"gigadat"
}
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.gigadat.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = gigadat::GigadatAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_key = format!(
"{}:{}",
auth.access_token.peek(),
auth.security_token.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: gigadat::GigadatErrorResponse = res
.response
.parse_struct("GigadatErrorResponse")
.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.err.clone(),
message: response.err.clone(),
reason: Some(response.err).clone(),
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 Gigadat {
fn validate_mandate_payment(
&self,
_pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match pm_data {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"validate_mandate_payment does not support cards".to_string(),
)
.into()),
_ => Ok(()),
}
}
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(())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Gigadat {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Gigadat {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Gigadat {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Gigadat {
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 auth = gigadat::GigadatAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(format!(
"{}api/payment-token/{}",
self.base_url(connectors),
auth.campaign_id.peek()
))
}
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 = gigadat::GigadatRouterData::from((amount, req));
let connector_req = gigadat::GigadatCpiRequest::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: gigadat::GigadatPaymentResponse = res
.response
.parse_struct("GigadatPaymentResponse")
.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 Gigadat {
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 transaction_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}api/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(&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: gigadat::GigadatTransactionStatusResponse = res
.response
.parse_struct("gigadat 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 Gigadat {
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: gigadat::GigadatTransactionStatusResponse = res
.response
.parse_struct("Gigadat 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 Gigadat {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Gigadat {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = gigadat::GigadatAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_key = format!(
"{}:{}",
auth.access_token.peek(),
auth.security_token.peek()
);
let auth_header = format!("Basic {}", consts::BASE64_ENGINE.encode(auth_key));
Ok(vec![
(
headers::AUTHORIZATION.to_string(),
auth_header.into_masked(),
),
(
headers::IDEMPOTENCY_KEY.to_string(),
Uuid::new_v4().to_string().into_masked(),
),
])
}
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 = gigadat::GigadatRouterData::from((refund_amount, req));
let connector_req = gigadat::GigadatRefundRequest::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: gigadat::RefundResponse = res
.response
.parse_struct("gigadat 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> {
let response: gigadat::GigadatRefundErrorResponse = res
.response
.parse_struct("GigadatRefundErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let code = response
.error
.first()
.and_then(|error_detail| error_detail.code.clone())
.unwrap_or(api_consts::NO_ERROR_CODE.to_string());
let message = response
.error
.first()
.map(|error_detail| error_detail.detail.clone())
.unwrap_or(api_consts::NO_ERROR_MESSAGE.to_string());
Ok(ErrorResponse {
status_code: res.status_code,
code,
message,
reason: Some(response.message).clone(),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Gigadat {
//Gigadat does not support Refund Sync
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> for Gigadat {
fn get_headers(
&self,
req: &PayoutsRouterData<PoQuote>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PayoutsRouterData<PoQuote>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let auth = gigadat::GigadatAuthType::try_from(&req.connector_auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(format!(
"{}api/payment-token/{}",
self.base_url(connectors),
auth.campaign_id.peek()
))
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoQuote>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.destination_currency,
)?;
let connector_router_data = gigadat::GigadatRouterData::from((amount, req));
let connector_req = gigadat::GigadatPayoutQuoteRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoQuote>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutQuoteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutQuoteType::get_headers(self, req, connectors)?)
.set_body(PayoutQuoteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoQuote>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoQuote>, errors::ConnectorError> {
let response: gigadat::GigadatPayoutQuoteResponse = res
.response
.parse_struct("GigadatPayoutQuoteResponse")
.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]
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> for Gigadat {
fn get_headers(
&self,
req: &PayoutsRouterData<PoCreate>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PayoutsRouterData<PoCreate>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let transfer_id = req.get_quote_id()?;
let metadata = Some(req.get_connector_meta()?.clone().expose());
let gigatad_meta: gigadat::GigadatPayoutMeta = to_payout_connector_meta(metadata.clone())?;
Ok(format!(
"{}webflow?transaction={}&token={}",
self.base_url(connectors),
transfer_id,
gigatad_meta.token.peek(),
))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoCreate>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutCreateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutCreateType::get_headers(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoCreate>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoCreate>, errors::ConnectorError> {
let response: gigadat::GigadatPayoutResponse = res
.response
.parse_struct("GigadatPayoutResponse")
.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)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Gigadat {
fn get_headers(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_url(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let transfer_id = req.request.connector_payout_id.to_owned().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "transaction_id",
},
)?;
let metadata = req
.request
.payout_connector_metadata
.clone()
.map(|secret| secret.peek().clone());
let gigatad_meta: gigadat::GigadatPayoutMeta = to_payout_connector_meta(metadata.clone())?;
Ok(format!(
"{}webflow/deposit?transaction={}&token={}",
self.base_url(connectors),
transfer_id,
gigatad_meta.token.peek(),
))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Get)
.url(&PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutFulfillType::get_headers(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>, errors::ConnectorError> {
let response: gigadat::GigadatPayoutResponse = res
.response
.parse_struct("GigadatPayoutResponse")
.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)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoSync, PayoutsData, PayoutsResponseData> for Gigadat {
fn get_url(
&self,
req: &PayoutsRouterData<PoSync>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let transfer_id = req.request.connector_payout_id.to_owned().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "transaction_id",
},
)?;
Ok(format!(
"{}api/transactions/{}",
connectors.gigadat.base_url, transfer_id
))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoSync>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn build_request(
&self,
req: &PayoutsRouterData<PoSync>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Get)
.url(&PayoutSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutSyncType::get_headers(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PayoutsRouterData<PoSync>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoSync>, errors::ConnectorError> {
let response: gigadat::GigadatPayoutSyncResponse = res
.response
.parse_struct("GigadatPayoutSyncResponse")
.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_webhook_query_params(
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<transformers::GigadatWebhookQueryParameters, errors::ConnectorError> {
let query_string = &request.query_params;
let (transaction, status) = query_string
.split('&')
.filter_map(|pair| pair.split_once('='))
.fold((None, None), |(mut txn, mut sts), (key, value)| {
match key {
"transaction" => txn = Some(value.to_string()),
"status" => {
if let Ok(status) =
transformers::GigadatPaymentStatus::try_from(value.to_string())
{
sts = Some(status);
}
}
_ => {}
}
(txn, sts)
});
Ok(transformers::GigadatWebhookQueryParameters {
transaction: transaction.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,
status: status.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,
})
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Gigadat {
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let query_params = get_webhook_query_params(request)?;
let body_str = std::str::from_utf8(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let details: Vec<transformers::GigadatWebhookKeyValue> =
form_urlencoded::parse(body_str.as_bytes())
.map(|(key, value)| transformers::GigadatWebhookKeyValue {
key: key.to_string(),
value: value.to_string(),
})
.collect();
let cpi_type_entry = details
.iter()
.find(|&entry| entry.key == "cpiType")
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let reference_id = match cpi_type_entry.value.as_str() {
#[cfg(feature = "payouts")]
"ETO" | "RTO" | "RTX" | "ANR" | "ANX" => {
api_models::webhooks::ObjectReferenceId::PayoutId(
api_models::webhooks::PayoutIdType::ConnectorPayoutId(query_params.transaction),
)
}
"ETI" | "RFM" => api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
query_params.transaction,
),
),
_ => {
return Err(errors::ConnectorError::NotImplemented(
"Invalid transaction type ".to_string(),
)
.into())
}
};
Ok(reference_id)
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let query_params = get_webhook_query_params(request)?;
let event_type = api_models::webhooks::IncomingWebhookEvent::from(query_params.status);
Ok(event_type)
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let body_str = std::str::from_utf8(request.body)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let details: Vec<transformers::GigadatWebhookKeyValue> =
form_urlencoded::parse(body_str.as_bytes())
.map(|(key, value)| transformers::GigadatWebhookKeyValue {
key: key.to_string(),
value: value.to_string(),
})
.collect();
let resource_object = serde_json::to_string(&details)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Box::new(resource_object))
}
async fn verify_webhook_source(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: Encryptable<masking::Secret<serde_json::Value>>,
_connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
Ok(false)
}
}
lazy_static! {
static ref GIGADAT_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
let mut gigadat_supported_payment_methods = SupportedPaymentMethods::new();
gigadat_supported_payment_methods.add(
enums::PaymentMethod::BankRedirect,
enums::PaymentMethodType::Interac,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
gigadat_supported_payment_methods
};
static ref GIGADAT_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Gigadat",
description: "Gigadat is a financial services product that offers a single API for payment integration. It provides Canadian businesses with a secure payment gateway and various pay-in and pay-out solutions, including Interac e-Transfer",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static ref GIGADAT_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = {
#[cfg(feature = "payouts")]
{
let mut flows = vec![enums::EventClass::Payments];
flows.push(enums::EventClass::Payouts);
flows
}
#[cfg(not(feature = "payouts"))]
{
vec![enums::EventClass::Payments]
}
};
}
impl ConnectorSpecifications for Gigadat {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*GIGADAT_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*GIGADAT_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*GIGADAT_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/gigadat.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 8401
}
|
large_file_-550573331966785214
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/custombilling.rs
</path>
<file>
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::{PaymentsResponseData, RefundsResponseData},
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 transformers as custombilling;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Custombilling {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Custombilling {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Custombilling {}
impl api::PaymentSession for Custombilling {}
impl api::ConnectorAccessToken for Custombilling {}
impl api::MandateSetup for Custombilling {}
impl api::PaymentAuthorize for Custombilling {}
impl api::PaymentSync for Custombilling {}
impl api::PaymentCapture for Custombilling {}
impl api::PaymentVoid for Custombilling {}
impl api::Refund for Custombilling {}
impl api::RefundExecute for Custombilling {}
impl api::RefundSync for Custombilling {}
impl api::PaymentToken for Custombilling {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Custombilling
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Custombilling
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 Custombilling {
fn id(&self) -> &'static str {
"custombilling"
}
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 {
""
}
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: custombilling::CustombillingErrorResponse = res
.response
.parse_struct("CustombillingErrorResponse")
.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 Custombilling {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Custombilling {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Custombilling {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Custombilling
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for Custombilling
{
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 = custombilling::CustombillingRouterData::from((amount, req));
let connector_req =
custombilling::CustombillingPaymentsRequest::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: custombilling::CustombillingPaymentsResponse = res
.response
.parse_struct("Custombilling 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 Custombilling {
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: custombilling::CustombillingPaymentsResponse = res
.response
.parse_struct("custombilling 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 Custombilling {
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: custombilling::CustombillingPaymentsResponse = res
.response
.parse_struct("Custombilling 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 Custombilling {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Custombilling {
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 =
custombilling::CustombillingRouterData::from((refund_amount, req));
let connector_req =
custombilling::CustombillingRefundRequest::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: custombilling::RefundResponse = res
.response
.parse_struct("custombilling 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 Custombilling {
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: custombilling::RefundResponse = res
.response
.parse_struct("custombilling 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 Custombilling {
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 Custombilling {}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/custombilling.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4219
}
|
large_file_6564432968336806959
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/silverflow.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::{enums, CardNetwork};
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::{BytesExt, StringExt},
request::{Method, Request, RequestBuilder, RequestContent},
};
use error_stack::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, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
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 silverflow;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Silverflow;
impl Silverflow {
pub fn new() -> &'static Self {
&Self
}
}
impl api::Payment for Silverflow {}
impl api::PaymentSession for Silverflow {}
impl api::ConnectorAccessToken for Silverflow {}
impl api::MandateSetup for Silverflow {}
impl api::PaymentAuthorize for Silverflow {}
impl api::PaymentSync for Silverflow {}
impl api::PaymentCapture for Silverflow {}
impl api::PaymentVoid for Silverflow {}
impl api::Refund for Silverflow {}
impl api::RefundExecute for Silverflow {}
impl api::RefundSync for Silverflow {}
impl api::PaymentToken for Silverflow {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Silverflow
{
fn get_headers(
&self,
req: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
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: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/processorTokens", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
// Create a simplified tokenization request directly from the tokenization data
let connector_req = silverflow::SilverflowTokenizationRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::TokenizationType::get_headers(self, req, connectors)?)
.set_body(types::TokenizationType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>,
errors::ConnectorError,
> {
let response: silverflow::SilverflowTokenizationResponse = res
.response
.parse_struct("Silverflow TokenizationResponse")
.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<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Silverflow
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(),
),
(
headers::ACCEPT.to_string(),
"application/json".to_string().into(),
),
];
// Add Idempotency-Key for POST requests (Authorize, Capture, Execute, PaymentMethodToken, Void)
let flow_type = std::any::type_name::<Flow>();
if flow_type.contains("Authorize")
|| flow_type.contains("Capture")
|| flow_type.contains("Execute")
|| flow_type.contains("PaymentMethodToken")
|| flow_type.contains("Void")
{
header.push((
"Idempotency-Key".to_string(),
format!("hs_{}", req.payment_id).into(),
));
}
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Silverflow {
fn id(&self) -> &'static str {
"silverflow"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
// Silverflow processes amounts in minor units (cents)
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.silverflow.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = silverflow::SilverflowAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_string = format!("{}:{}", auth.api_key.expose(), auth.api_secret.expose());
let encoded = common_utils::consts::BASE64_ENGINE.encode(auth_string.as_bytes());
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Basic {encoded}").into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: silverflow::SilverflowErrorResponse = res
.response
.parse_struct("SilverflowErrorResponse")
.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.message,
reason: response
.error
.details
.map(|d| format!("Field: {}, Issue: {}", d.field, d.issue)),
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 Silverflow {
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 => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
utils::construct_not_implemented_error_report(capture_method, self.id()),
),
enums::CaptureMethod::SequentialAutomatic => Err(
utils::construct_not_implemented_error_report(capture_method, self.id()),
),
}
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Silverflow {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Silverflow {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Silverflow
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Silverflow {
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!("{}/charges", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data =
silverflow::SilverflowRouterData::from((req.request.minor_amount, req));
let connector_req =
silverflow::SilverflowPaymentsRequest::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: silverflow::SilverflowPaymentsResponse = res
.response
.parse_struct("Silverflow 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 Silverflow {
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
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "connector_transaction_id for payment sync",
})?;
Ok(format!(
"{}/charges/{}",
self.base_url(connectors),
connector_payment_id
))
}
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: silverflow::SilverflowPaymentsResponse = res
.response
.parse_struct("silverflow 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 Silverflow {
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;
Ok(format!(
"{}/charges/{}/clear",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = silverflow::SilverflowCaptureRequest::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(&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: silverflow::SilverflowCaptureResponse = res
.response
.parse_struct("Silverflow 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 Silverflow {
fn get_headers(
&self,
req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
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: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = &req.request.connector_transaction_id;
Ok(format!(
"{}/charges/{}/reverse",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = silverflow::SilverflowVoidRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
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: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
errors::ConnectorError,
> {
let response: silverflow::SilverflowVoidResponse = res
.response
.parse_struct("Silverflow PaymentsVoidResponse")
.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 Silverflow {
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;
Ok(format!(
"{}/charges/{}/refund",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data =
silverflow::SilverflowRouterData::from((req.request.minor_refund_amount, req));
let connector_req = silverflow::SilverflowRefundRequest::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: silverflow::RefundResponse = res
.response
.parse_struct("silverflow 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 Silverflow {
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> {
// According to Silverflow API documentation, refunds are actions on charges
// Endpoint: GET /charges/{chargeKey}/actions/{actionKey}
let charge_key = &req.request.connector_transaction_id;
let action_key = &req.request.refund_id;
Ok(format!(
"{}/charges/{}/actions/{}",
self.base_url(connectors),
charge_key,
action_key
))
}
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: silverflow::RefundResponse = res
.response
.parse_struct("silverflow 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 Silverflow {
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook_body = String::from_utf8(request.body.to_vec())
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let webhook_event: silverflow::SilverflowWebhookEvent = webhook_body
.parse_struct("SilverflowWebhookEvent")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
// For payments, use charge_key; for refunds, use refund_key
if let Some(charge_key) = webhook_event.event_data.charge_key {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(charge_key),
))
} else if let Some(refund_key) = webhook_event.event_data.refund_key {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(refund_key),
))
} else {
Err(errors::ConnectorError::WebhookReferenceIdNotFound.into())
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let webhook_body = String::from_utf8(request.body.to_vec())
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
let webhook_event: silverflow::SilverflowWebhookEvent = webhook_body
.parse_struct("SilverflowWebhookEvent")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match webhook_event.event_type.as_str() {
"charge.authorization.succeeded" => {
// Handle manual capture flow: check if clearing is still pending
if let Some(status) = webhook_event.event_data.status {
match (&status.authorization, &status.clearing) {
(
silverflow::SilverflowAuthorizationStatus::Approved,
silverflow::SilverflowClearingStatus::Pending,
) => {
// Manual capture: authorization succeeded, but clearing is pending
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess)
}
(
silverflow::SilverflowAuthorizationStatus::Approved,
silverflow::SilverflowClearingStatus::Cleared,
) => {
// Automatic capture: authorization and clearing both completed
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
_ => {
// Fallback for other authorization states
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess)
}
}
} else {
// Fallback when status is not available
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentAuthorizationSuccess)
}
}
"charge.authorization.failed" => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)
}
"charge.clearing.succeeded" => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
"charge.clearing.failed" => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)
}
"refund.succeeded" => Ok(api_models::webhooks::IncomingWebhookEvent::RefundSuccess),
"refund.failed" => Ok(api_models::webhooks::IncomingWebhookEvent::RefundFailure),
_ => Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported),
}
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook_body = String::from_utf8(request.body.to_vec())
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
let webhook_event: silverflow::SilverflowWebhookEvent = webhook_body
.parse_struct("SilverflowWebhookEvent")
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(webhook_event))
}
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let signature = request
.headers
.get("X-Silverflow-Signature")
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)?
.to_str()
.change_context(errors::ConnectorError::WebhookSignatureNotFound)?;
hex::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: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
Ok(request.body.to_vec())
}
}
static SILVERFLOW_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
];
let supported_card_networks = vec![
CardNetwork::Visa,
CardNetwork::Mastercard,
CardNetwork::AmericanExpress,
CardNetwork::Discover,
];
let mut silverflow_supported_payment_methods = SupportedPaymentMethods::new();
silverflow_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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_networks.clone(),
}
}),
),
},
);
silverflow_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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_networks.clone(),
}
}),
),
},
);
silverflow_supported_payment_methods
});
static SILVERFLOW_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Silverflow",
description: "Silverflow is a global payment processor that provides secure and reliable payment processing services with support for multiple capture methods and 3DS authentication.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static SILVERFLOW_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] =
[enums::EventClass::Payments, enums::EventClass::Refunds];
impl ConnectorSpecifications for Silverflow {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&SILVERFLOW_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*SILVERFLOW_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&SILVERFLOW_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/silverflow.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7564
}
|
large_file_-8447073614072859766
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/cashtocode.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
api::ApplicationResponse,
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, PaymentsSyncRouterData},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{PaymentsAuthorizeType, Response},
webhooks::{self, IncomingWebhookFlowError},
};
use masking::{Mask, PeekInterface, Secret};
use transformers as cashtocode;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Cashtocode {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Cashtocode {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Cashtocode {}
impl api::PaymentSession for Cashtocode {}
impl api::ConnectorAccessToken for Cashtocode {}
impl api::MandateSetup for Cashtocode {}
impl api::PaymentAuthorize for Cashtocode {}
impl api::PaymentSync for Cashtocode {}
impl api::PaymentCapture for Cashtocode {}
impl api::PaymentVoid for Cashtocode {}
impl api::PaymentToken for Cashtocode {}
impl api::Refund for Cashtocode {}
impl api::RefundExecute for Cashtocode {}
impl api::RefundSync for Cashtocode {}
fn get_b64_auth_cashtocode(
payment_method_type: Option<enums::PaymentMethodType>,
auth_type: &transformers::CashtocodeAuth,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
fn construct_basic_auth(
username: Option<Secret<String>>,
password: Option<Secret<String>>,
) -> Result<masking::Maskable<String>, errors::ConnectorError> {
let username = username.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
let password = password.ok_or(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(format!(
"Basic {}",
base64::engine::general_purpose::STANDARD.encode(format!(
"{}:{}",
username.peek(),
password.peek()
))
)
.into_masked())
}
let auth_header = match payment_method_type {
Some(enums::PaymentMethodType::ClassicReward) => construct_basic_auth(
auth_type.username_classic.to_owned(),
auth_type.password_classic.to_owned(),
),
Some(enums::PaymentMethodType::Evoucher) => construct_basic_auth(
auth_type.username_evoucher.to_owned(),
auth_type.password_evoucher.to_owned(),
),
_ => return Err(errors::ConnectorError::MissingPaymentMethodType)?,
}?;
Ok(vec![(headers::AUTHORIZATION.to_string(), auth_header)])
}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Cashtocode
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Cashtocode where
Self: ConnectorIntegration<Flow, Request, Response>
{
}
impl ConnectorCommon for Cashtocode {
fn id(&self) -> &'static str {
"cashtocode"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.cashtocode.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: cashtocode::CashtocodeErrorResponse = res
.response
.parse_struct("CashtocodeErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error.to_string(),
message: response.error_description.clone(),
reason: Some(response.error_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 Cashtocode {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Cashtocode {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Cashtocode {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Cashtocode
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Cashtocode".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Cashtocode {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
_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_owned()
.into(),
)];
let auth_type = transformers::CashtocodeAuth::try_from((
&req.connector_auth_type,
&req.request.currency,
))?;
let mut api_key = get_b64_auth_cashtocode(req.request.payment_method_type, &auth_type)?;
header.append(&mut api_key);
Ok(header)
}
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!(
"{}/merchant/paytokens",
connectors.cashtocode.base_url
))
}
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_req = cashtocode::CashtocodePaymentsRequest::try_from((req, amount))?;
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: cashtocode::CashtocodePaymentsResponse = res
.response
.parse_struct("Cashtocode 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 Cashtocode {
// default implementation of build_request method will be executed
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: transformers::CashtocodePaymentsSyncResponse = res
.response
.parse_struct("CashtocodePaymentsSyncResponse")
.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 Cashtocode {
fn build_request(
&self,
_req: &RouterData<Capture, PaymentsCaptureData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Cashtocode".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cashtocode {
fn build_request(
&self,
_req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Payments Cancel".to_string(),
connector: "Cashtocode".to_string(),
}
.into())
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Cashtocode {
fn get_webhook_source_verification_signature(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let base64_signature = utils::get_header_key_value("authorization", request.headers)?;
let signature = base64_signature.as_bytes().to_owned();
Ok(signature)
}
async fn verify_webhook_source(
&self,
request: &webhooks::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_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::WebhookSourceVerificationFailed)?;
let secret_auth = String::from_utf8(connector_webhook_secrets.secret.to_vec())
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Could not convert secret to UTF-8")?;
let signature_auth = String::from_utf8(signature.to_vec())
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)
.attach_printable("Could not convert secret to UTF-8")?;
Ok(signature_auth == secret_auth)
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook: transformers::CashtocodePaymentsSyncResponse = request
.body
.parse_struct("CashtocodePaymentsSyncResponse")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(webhook.transaction_id),
))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook: transformers::CashtocodeIncomingWebhook = request
.body
.parse_struct("CashtocodeIncomingWebhook")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Box::new(webhook))
}
fn get_webhook_api_response(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_error_kind: Option<IncomingWebhookFlowError>,
) -> CustomResult<ApplicationResponse<serde_json::Value>, errors::ConnectorError> {
let status = "EXECUTED".to_string();
let obj: transformers::CashtocodePaymentsSyncResponse = request
.body
.parse_struct("CashtocodePaymentsSyncResponse")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let response: serde_json::Value =
serde_json::json!({ "status": status, "transactionId" : obj.transaction_id});
Ok(ApplicationResponse::Json(response))
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cashtocode {
fn build_request(
&self,
_req: &RouterData<Execute, RefundsData, RefundsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Refunds".to_string(),
connector: "Cashtocode".to_string(),
}
.into())
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cashtocode {
// default implementation of build_request method will be executed
}
static CASHTOCODE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let mut cashtocode_supported_payment_methods = SupportedPaymentMethods::new();
cashtocode_supported_payment_methods.add(
enums::PaymentMethod::Reward,
enums::PaymentMethodType::ClassicReward,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
cashtocode_supported_payment_methods.add(
enums::PaymentMethod::Reward,
enums::PaymentMethodType::Evoucher,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
cashtocode_supported_payment_methods
});
static CASHTOCODE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "CashToCode",
description:
"CashToCode is a payment solution that enables users to convert cash into digital vouchers for online transactions",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static CASHTOCODE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
impl ConnectorSpecifications for Cashtocode {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&CASHTOCODE_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*CASHTOCODE_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&CASHTOCODE_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/cashtocode.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4017
}
|
large_file_4039992470175954652
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/stax.rs
</path>
<file>
pub mod transformers;
use std::{fmt::Debug, sync::LazyLock};
use api_models::webhooks::IncomingWebhookEvent;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::ByteSliceExt,
request::{Method, Request, RequestBuilder, RequestContent},
};
use error_stack::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},
},
router_request_types::{
AccessTokenRequestData, ConnectorCustomerData, PaymentMethodTokenizationData,
PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData,
PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
ConnectorCustomerRouterData, PaymentsAuthorizeRouterData, PaymentsCancelRouterData,
PaymentsCaptureRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
TokenizationRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts, errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use masking::{Mask, PeekInterface, Secret};
use transformers as stax;
use self::stax::StaxWebhookEventType;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, RefundsRequestData},
};
#[derive(Debug, Clone)]
pub struct Stax;
impl api::Payment for Stax {}
impl api::PaymentSession for Stax {}
impl api::ConnectorAccessToken for Stax {}
impl api::MandateSetup for Stax {}
impl api::PaymentAuthorize for Stax {}
impl api::PaymentSync for Stax {}
impl api::PaymentCapture for Stax {}
impl api::PaymentVoid for Stax {}
impl api::Refund for Stax {}
impl api::RefundExecute for Stax {}
impl api::RefundSync for Stax {}
impl api::PaymentToken for Stax {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Stax
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(),
types::PaymentsAuthorizeType::get_content_type(self)
.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 Stax {
fn id(&self) -> &'static str {
"stax"
}
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.stax.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = stax::StaxAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", auth.api_key.peek()).into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
_event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
Ok(ErrorResponse {
status_code: res.status_code,
code: consts::NO_ERROR_CODE.to_string(),
message: consts::NO_ERROR_MESSAGE.to_string(),
reason: Some(
std::str::from_utf8(&res.response)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?
.to_owned(),
),
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 Stax {
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(
utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
impl api::ConnectorCustomer for Stax {}
impl ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>
for Stax
{
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!("{}customer", self.base_url(connectors),))
}
fn get_request_body(
&self,
req: &ConnectorCustomerRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = stax::StaxCustomerRequest::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: stax::StaxCustomerResponse = res
.response
.parse_struct("StaxCustomerResponse")
.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 Stax
{
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(format!("{}payment-method/", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &TokenizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = stax::StaxTokenRequest::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(&types::TokenizationType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::TokenizationType::get_headers(self, req, connectors)?)
.set_body(types::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: stax::StaxTokenResponse = res
.response
.parse_struct("StaxTokenResponse")
.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<Session, PaymentsSessionData, PaymentsResponseData> for Stax {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Stax {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Stax {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Stax".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Stax {
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!("{}charge", self.base_url(connectors),))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = stax::StaxRouterData::try_from((
&self.get_currency_unit(),
req.request.currency,
req.request.amount,
req,
))?;
let connector_req = stax::StaxPaymentsRequest::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: stax::StaxPaymentsResponse = res
.response
.parse_struct("StaxPaymentsAuthorizeResponse")
.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 Stax {
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
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/transaction/{connector_payment_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(&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: stax::StaxPaymentsResponse = res
.response
.parse_struct("StaxPaymentsSyncResponse")
.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 Stax {
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!(
"{}/transaction/{}/capture",
self.base_url(connectors),
req.request.connector_transaction_id,
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = stax::StaxRouterData::try_from((
&self.get_currency_unit(),
req.request.currency,
req.request.amount_to_capture,
req,
))?;
let connector_req = stax::StaxCaptureRequest::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: stax::StaxPaymentsResponse = res
.response
.parse_struct("StaxPaymentsCaptureResponse")
.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 Stax {
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!(
"{}/transaction/{}/void-or-refund",
self.base_url(connectors),
req.request.connector_transaction_id,
))
}
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)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: stax::StaxPaymentsResponse = res
.response
.parse_struct("StaxPaymentsVoidResponse")
.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 Stax {
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_transaction_id = if req.request.connector_metadata.is_some() {
let stax_capture: stax::StaxMetaData =
utils::to_connector_meta(req.request.connector_metadata.clone())?;
stax_capture.capture_id
} else {
req.request.connector_transaction_id.clone()
};
Ok(format!(
"{}/transaction/{}/refund",
self.base_url(connectors),
connector_transaction_id,
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = stax::StaxRouterData::try_from((
&self.get_currency_unit(),
req.request.currency,
req.request.refund_amount,
req,
))?;
let connector_req = stax::StaxRefundRequest::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: stax::RefundResponse = res
.response
.parse_struct("StaxRefundResponse")
.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 Stax {
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!(
"{}/transaction/{}",
self.base_url(connectors),
req.request.get_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)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: stax::RefundResponse = res
.response
.parse_struct("StaxRefundSyncResponse")
.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 Stax {
async fn verify_webhook_source(
&self,
_request: &webhooks::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> {
Ok(false)
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook_body: stax::StaxWebhookBody = request
.body
.parse_struct("StaxWebhookBody")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
match webhook_body.transaction_type {
StaxWebhookEventType::Refund => Ok(api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(webhook_body.id),
)),
StaxWebhookEventType::Unknown => {
Err(errors::ConnectorError::WebhookEventTypeNotFound.into())
}
StaxWebhookEventType::PreAuth
| StaxWebhookEventType::Capture
| StaxWebhookEventType::Charge
| StaxWebhookEventType::Void => Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
match webhook_body.transaction_type {
StaxWebhookEventType::Capture => webhook_body
.auth_id
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,
_ => webhook_body.id,
},
),
)),
}
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
let details: stax::StaxWebhookBody = request
.body
.parse_struct("StaxWebhookEventType")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
Ok(match &details.transaction_type {
StaxWebhookEventType::Refund => match &details.success {
true => IncomingWebhookEvent::RefundSuccess,
false => IncomingWebhookEvent::RefundFailure,
},
StaxWebhookEventType::Capture | StaxWebhookEventType::Charge => {
match &details.success {
true => IncomingWebhookEvent::PaymentIntentSuccess,
false => IncomingWebhookEvent::PaymentIntentFailure,
}
}
StaxWebhookEventType::PreAuth
| StaxWebhookEventType::Void
| StaxWebhookEventType::Unknown => IncomingWebhookEvent::EventNotSupported,
})
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let reference_object: serde_json::Value = serde_json::from_slice(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
Ok(Box::new(reference_object))
}
}
static STAX_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::Discover,
];
let mut stax_supported_payment_methods = SupportedPaymentMethods::new();
stax_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,
},
);
stax_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
stax_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
stax_supported_payment_methods
});
static STAX_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Stax",
description:
"Stax is a payment processing platform that helps businesses accept payments and manage their payment ecosystem ",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static STAX_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] =
[enums::EventClass::Payments, enums::EventClass::Refunds];
impl ConnectorSpecifications for Stax {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&STAX_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*STAX_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&STAX_SUPPORTED_WEBHOOK_FLOWS)
}
fn should_call_connector_customer(
&self,
_payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
) -> bool {
true
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/stax.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 7459
}
|
large_file_2195832595263124986
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/prophetpay.rs
</path>
<file>
pub mod transformers;
use std::{fmt::Debug, sync::LazyLock};
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
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, 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, PaymentsCompleteAuthorizeRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, 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, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::{Mask, PeekInterface};
use transformers as prophetpay;
use crate::{constants::headers, types::ResponseRouterData};
#[derive(Debug, Clone)]
pub struct Prophetpay;
impl api::payments::MandateSetup for Prophetpay {}
impl api::Payment for Prophetpay {}
impl api::PaymentSession for Prophetpay {}
impl api::ConnectorAccessToken for Prophetpay {}
impl api::PaymentAuthorize for Prophetpay {}
impl api::PaymentSync for Prophetpay {}
impl api::PaymentCapture for Prophetpay {}
impl api::PaymentVoid for Prophetpay {}
impl api::Refund for Prophetpay {}
impl api::RefundExecute for Prophetpay {}
impl api::RefundSync for Prophetpay {}
impl api::PaymentToken for Prophetpay {}
impl api::payments::PaymentsCompleteAuthorize for Prophetpay {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Prophetpay
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Prophetpay
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 Prophetpay {
fn id(&self) -> &'static str {
"prophetpay"
}
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.prophetpay.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = prophetpay::ProphetpayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_val = format!("{}:{}", auth.user_name.peek(), auth.password.peek());
let basic_token = format!("Basic {}", BASE64_ENGINE.encode(auth_val));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
basic_token.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: serde_json::Value = res
.response
.parse_struct("ProphetPayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: Some(response.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 ConnectorValidation for Prophetpay {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Prophetpay {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Prophetpay {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Prophetpay
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Prophetpay".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Prophetpay {
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!(
"{}hp/api/HostedTokenize/CreateHostedTokenize",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = prophetpay::ProphetpayRouterData::try_from((
&self.get_currency_unit(),
req.request.currency,
req.request.amount,
req,
))?;
let connector_req = prophetpay::ProphetpayTokenRequest::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>
where
PaymentsResponseData: Clone,
{
let response: prophetpay::ProphetpayTokenResponse = res
.response
.parse_struct("prophetpay ProphetpayTokenResponse")
.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 Prophetpay
{
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!(
"{}hp/api/Transactions/ProcessTransaction",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = prophetpay::ProphetpayRouterData::try_from((
&self.get_currency_unit(),
req.request.currency,
req.request.amount,
req,
))?;
let connector_req =
prophetpay::ProphetpayCompleteRequest::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>
where
PaymentsResponseData: Clone,
{
let response: prophetpay::ProphetpayCompleteAuthResponse = res
.response
.parse_struct("prophetpay ProphetpayResponse")
.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 Prophetpay {
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!(
"{}hp/api/Transactions/ProcessTransaction",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = prophetpay::ProphetpaySyncRequest::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(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(types::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: prophetpay::ProphetpaySyncResponse = res
.response
.parse_struct("prophetpay 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 Prophetpay {}
// This is Void Implementation for Prophetpay
// Since Prophetpay does not have capture this have been commented out but kept if it is required for future usage
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Prophetpay {
/*
fn get_headers(
&self,
req: &types::PaymentsCancelRouterData,
connectors: &settings::Connectors,
) -> CustomResult<Vec<(String, request::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: &types::PaymentsCancelRouterData,
connectors: &settings::Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}hp/api/Transactions/ProcessTransaction",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &types::PaymentsCancelRouterData,
_connectors: &settings::Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req =prophetpay::ProphetpayVoidRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
*/
fn build_request(
&self,
_req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("Void flow not implemented".to_string()).into())
}
/*
fn handle_response(
&self,
data: &types::PaymentsCancelRouterData,
res: Response,
) -> CustomResult<types::PaymentsCancelRouterData, errors::ConnectorError> {
let response: prophetpay::ProphetpayVoidResponse = res
.response
.parse_struct("prophetpay PaymentsCancelResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
types::RouterData::try_from(types::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 Prophetpay {
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!(
"{}hp/api/Transactions/ProcessTransaction",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = prophetpay::ProphetpayRouterData::try_from((
&self.get_currency_unit(),
req.request.currency,
req.request.refund_amount,
req,
))?;
let connector_req = prophetpay::ProphetpayRefundRequest::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: prophetpay::ProphetpayRefundResponse = res
.response
.parse_struct("prophetpay ProphetpayRefundResponse")
.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 Prophetpay {
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!(
"{}hp/api/Transactions/ProcessTransaction",
self.base_url(connectors)
))
}
fn get_request_body(
&self,
req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = prophetpay::ProphetpayRefundSyncRequest::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(&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: prophetpay::ProphetpayRefundSyncResponse = res
.response
.parse_struct("prophetpay ProphetpayRefundResponse")
.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 Prophetpay {
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> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static PROPHETPAY_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::SequentialAutomatic,
];
let mut prophetpay_supported_payment_methods = SupportedPaymentMethods::new();
prophetpay_supported_payment_methods.add(
enums::PaymentMethod::CardRedirect,
enums::PaymentMethodType::CardRedirect,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
prophetpay_supported_payment_methods
});
static PROPHETPAY_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Prophetpay",
description: "GlobePay Limited is a professional cross-border payment solution provider (WeChat Pay & Alipay) in the UK",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static PROPHETPAY_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Prophetpay {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&PROPHETPAY_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*PROPHETPAY_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&PROPHETPAY_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/prophetpay.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5541
}
|
large_file_4979311425429699419
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/bambora.rs
</path>
<file>
pub mod transformers;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
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, PaymentsAuthorizeType, PaymentsCaptureType, PaymentsCompleteAuthorizeType,
PaymentsSyncType, PaymentsVoidType, Response,
},
webhooks,
};
use lazy_static::lazy_static;
use masking::Mask;
use transformers as bambora;
use crate::{
connectors::bambora::transformers::BamboraRouterData,
constants::headers,
types::ResponseRouterData,
utils::{self, convert_amount, RefundsRequestData},
};
#[derive(Clone)]
pub struct Bambora {
amount_convertor: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Bambora {
pub fn new() -> &'static Self {
&Self {
amount_convertor: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Bambora {}
impl api::PaymentToken for Bambora {}
impl api::PaymentAuthorize for Bambora {}
impl api::PaymentVoid for Bambora {}
impl api::MandateSetup for Bambora {}
impl api::ConnectorAccessToken for Bambora {}
impl api::PaymentSync for Bambora {}
impl api::PaymentCapture for Bambora {}
impl api::PaymentSession for Bambora {}
impl api::Refund for Bambora {}
impl api::RefundExecute for Bambora {}
impl api::RefundSync for Bambora {}
impl api::PaymentsCompleteAuthorize for Bambora {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Bambora
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 = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Bambora {
fn id(&self) -> &'static str {
"bambora"
}
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.bambora.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = bambora::BamboraAuthType::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: bambora::BamboraErrorResponse = res
.response
.parse_struct("BamboraErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code.to_string(),
message: serde_json::to_string(&response.details)
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
reason: Some(response.message),
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 Bambora {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Bambora
{
// Not Implemented (R)
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Bambora {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Bambora {
//TODO: implement sessions flow
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Bambora {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Bambora".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Bambora {
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!("{}{}", self.base_url(connectors), "/v1/payments"))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = BamboraRouterData::try_from((amount, req))?;
let connector_req = bambora::BamboraPaymentsRequest::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: bambora::BamboraResponse = res
.response
.parse_struct("PaymentIntentResponse")
.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 Bambora
{
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> {
let meta: bambora::BamboraMeta =
utils::to_connector_meta(req.request.connector_meta.clone())?;
Ok(format!(
"{}/v1/payments/{}{}",
self.base_url(connectors),
meta.three_d_session_data,
"/continue"
))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = bambora::BamboraThreedsContinueRequest::try_from(&req.request)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = 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();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: bambora::BamboraPaymentsResponse = res
.response
.parse_struct("BamboraPaymentsResponse")
.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 Bambora {
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
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/v1/payments/{connector_payment_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 get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: bambora::BamboraPaymentsResponse = res
.response
.parse_struct("bambora 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,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Bambora {
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!(
"{}/v1/payments/{}/completions",
self.base_url(connectors),
req.request.connector_transaction_id,
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = BamboraRouterData::try_from((amount, req))?;
let connector_req =
bambora::BamboraPaymentsCaptureRequest::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(self.get_request_body(req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: bambora::BamboraPaymentsResponse = res
.response
.parse_struct("Bambora 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,
})
.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<Void, PaymentsCancelData, PaymentsResponseData> for Bambora {
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 connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/v1/payments/{}/void",
self.base_url(connectors),
connector_payment_id,
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let currency =
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Currency",
})?;
let minor_amount =
req.request
.minor_amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Amount",
})?;
let amount = convert_amount(self.amount_convertor, minor_amount, currency)?;
let connector_router_data = BamboraRouterData::try_from((amount, req))?;
let connector_req = bambora::BamboraVoidRequest::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: bambora::BamboraPaymentsResponse = res
.response
.parse_struct("bambora 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,
})
.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 ConnectorRedirectResponse for Bambora {
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)
}
}
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Bambora {
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/payments/{}/returns",
self.base_url(connectors),
connector_payment_id,
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_convertor,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = BamboraRouterData::try_from((amount, req))?;
let connector_req = bambora::BamboraRefundRequest::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: bambora::RefundResponse = res
.response
.parse_struct("bambora 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,
})
.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<RSync, RefundsData, RefundsResponseData> for Bambora {
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_payment_id = req.request.connector_transaction_id.clone();
let connector_refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}/v1/payments/{}",
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)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: bambora::RefundResponse = res
.response
.parse_struct("bambora 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,
})
.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 Bambora {
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))
}
}
lazy_static! {
static ref BAMBORA_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let default_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::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
];
let mut bambora_supported_payment_methods = SupportedPaymentMethods::new();
bambora_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: default_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(),
}
}),
),
},
);
bambora_supported_payment_methods
};
static ref BAMBORA_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Bambora",
description: "Bambora is a leading online payment provider in Canada and United States.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static ref BAMBORA_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
}
impl ConnectorSpecifications for Bambora {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*BAMBORA_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*BAMBORA_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*BAMBORA_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/bambora.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6598
}
|
large_file_1066799551756040000
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/wellsfargopayout.rs
</path>
<file>
pub mod transformers;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
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::{
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,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors::ConnectorError,
events::connector_api_logs::ConnectorEvent,
types::{
PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, RefundExecuteType,
RefundSyncType, Response,
},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::{ExposeInterface, Mask as _, Maskable};
use self::transformers as wellsfargopayout;
use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount};
#[derive(Clone)]
pub struct Wellsfargopayout {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Wellsfargopayout {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Wellsfargopayout {}
impl api::PaymentSession for Wellsfargopayout {}
impl api::ConnectorAccessToken for Wellsfargopayout {}
impl api::MandateSetup for Wellsfargopayout {}
impl api::PaymentAuthorize for Wellsfargopayout {}
impl api::PaymentSync for Wellsfargopayout {}
impl api::PaymentCapture for Wellsfargopayout {}
impl api::PaymentVoid for Wellsfargopayout {}
impl api::Refund for Wellsfargopayout {}
impl api::RefundExecute for Wellsfargopayout {}
impl api::RefundSync for Wellsfargopayout {}
impl api::PaymentToken for Wellsfargopayout {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Wellsfargopayout
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Wellsfargopayout
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, 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 Wellsfargopayout {
fn id(&self) -> &'static str {
"wellsfargopayout"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
// todo!()
// 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.wellsfargopayout.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let auth = wellsfargopayout::WellsfargopayoutAuthType::try_from(auth_type)
.change_context(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, ConnectorError> {
let response: wellsfargopayout::WellsfargopayoutErrorResponse = res
.response
.parse_struct("WellsfargopayoutErrorResponse")
.change_context(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 Wellsfargopayout {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Wellsfargopayout {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken>
for Wellsfargopayout
{
}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Wellsfargopayout
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
for Wellsfargopayout
{
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, 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, ConnectorError> {
Err(ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data =
wellsfargopayout::WellsfargopayoutRouterData::from((amount, req));
let connector_req =
wellsfargopayout::WellsfargopayoutPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, 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, ConnectorError> {
let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res
.response
.parse_struct("Wellsfargopayout PaymentsAuthorizeResponse")
.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 ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Wellsfargopayout {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, 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, ConnectorError> {
Err(ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, 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, ConnectorError> {
let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res
.response
.parse_struct("wellsfargopayout PaymentsSyncResponse")
.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 ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Wellsfargopayout {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, 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, ConnectorError> {
Err(ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
Err(ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, 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, ConnectorError> {
let response: wellsfargopayout::WellsfargopayoutPaymentsResponse = res
.response
.parse_struct("Wellsfargopayout PaymentsCaptureResponse")
.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 ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Wellsfargopayout {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Wellsfargopayout {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, 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, ConnectorError> {
Err(ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let refund_amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data =
wellsfargopayout::WellsfargopayoutRouterData::from((refund_amount, req));
let connector_req =
wellsfargopayout::WellsfargopayoutRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, 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>, ConnectorError> {
let response: wellsfargopayout::RefundResponse = res
.response
.parse_struct("wellsfargopayout RefundResponse")
.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 ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Wellsfargopayout {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, 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, ConnectorError> {
Err(ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, 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)?)
.set_body(RefundSyncType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, ConnectorError> {
let response: wellsfargopayout::RefundResponse = res
.response
.parse_struct("wellsfargopayout RefundSyncResponse")
.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)
}
}
#[async_trait::async_trait]
impl IncomingWebhook for Wellsfargopayout {
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
}
static WELLSFARGOPAYOUTS_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Wellsfargo Payout",
description: "Wells Fargo Payouts streamlines secure domestic and international payments for businesses via online banking, supporting Bill Pay, Digital Wires, and Zelle",
connector_type: common_enums::HyperswitchConnectorCategory::PayoutProcessor,
integration_status: common_enums::ConnectorIntegrationStatus::Sandbox,
};
impl ConnectorSpecifications for Wellsfargopayout {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&WELLSFARGOPAYOUTS_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
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/wellsfargopayout.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 4575
}
|
large_file_4860340150339798246
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/forte.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector},
};
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, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
consts::NO_ERROR_CODE,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::{Mask, PeekInterface};
use transformers as forte;
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{convert_amount, PaymentsSyncRequestData, RefundsRequestData},
};
#[derive(Clone)]
pub struct Forte {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Forte {
pub fn new() -> &'static Self {
&Self {
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Forte {}
impl api::PaymentSession for Forte {}
impl api::ConnectorAccessToken for Forte {}
impl api::MandateSetup for Forte {}
impl api::PaymentAuthorize for Forte {}
impl api::PaymentSync for Forte {}
impl api::PaymentCapture for Forte {}
impl api::PaymentVoid for Forte {}
impl api::Refund for Forte {}
impl api::RefundExecute for Forte {}
impl api::RefundSync for Forte {}
impl api::PaymentToken for Forte {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Forte
{
}
pub const AUTH_ORG_ID_HEADER: &str = "X-Forte-Auth-Organization-Id";
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Forte
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 content_type = ConnectorCommon::common_get_content_type(self);
let mut common_headers = self.get_auth_header(&req.connector_auth_type)?;
common_headers.push((
headers::CONTENT_TYPE.to_string(),
content_type.to_string().into(),
));
Ok(common_headers)
}
}
impl ConnectorCommon for Forte {
fn id(&self) -> &'static str {
"forte"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.forte.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = forte::ForteAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let raw_basic_token = format!(
"{}:{}",
auth.api_access_id.peek(),
auth.api_secret_key.peek()
);
let basic_token = format!("Basic {}", BASE64_ENGINE.encode(raw_basic_token));
Ok(vec![
(
headers::AUTHORIZATION.to_string(),
basic_token.into_masked(),
),
(
AUTH_ORG_ID_HEADER.to_string(),
auth.organization_id.into_masked(),
),
])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: forte::ForteErrorResponse = res
.response
.parse_struct("Forte ErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
let message = response.response.response_desc;
let code = response
.response
.response_code
.unwrap_or_else(|| NO_ERROR_CODE.to_string());
Ok(ErrorResponse {
status_code: res.status_code,
code,
message,
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Forte {}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Forte {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Forte {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Forte {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Forte".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Forte {
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 auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
"{}/organizations/{}/locations/{}/transactions",
self.base_url(connectors),
auth.organization_id.peek(),
auth.location_id.peek()
))
}
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 = forte::ForteRouterData::from((amount, req));
let connector_req = forte::FortePaymentsRequest::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: forte::FortePaymentsResponse = res
.response
.parse_struct("Forte AuthorizeResponse")
.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 Forte {
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 auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
let txn_id = PaymentsSyncRequestData::get_connector_transaction_id(&req.request)
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/organizations/{}/locations/{}/transactions/{}",
self.base_url(connectors),
auth.organization_id.peek(),
auth.location_id.peek(),
txn_id
))
}
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: forte::FortePaymentsSyncResponse = res
.response
.parse_struct("forte 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 Forte {
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 auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
"{}/organizations/{}/locations/{}/transactions",
self.base_url(connectors),
auth.organization_id.peek(),
auth.location_id.peek()
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = forte::ForteCaptureRequest::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::Put)
.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: forte::ForteCaptureResponse = res
.response
.parse_struct("Forte 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 Forte {
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 auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
"{}/organizations/{}/locations/{}/transactions/{}",
self.base_url(connectors),
auth.organization_id.peek(),
auth.location_id.peek(),
req.request.connector_transaction_id
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = forte::ForteCancelRequest::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::Put)
.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: forte::ForteCancelResponse = res
.response
.parse_struct("forte CancelResponse")
.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 Forte {
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 auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
"{}/organizations/{}/locations/{}/transactions",
self.base_url(connectors),
auth.organization_id.peek(),
auth.location_id.peek()
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = forte::ForteRouterData::from((refund_amount, req));
let connector_req = forte::ForteRefundRequest::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: forte::RefundResponse = res
.response
.parse_struct("forte 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 Forte {
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 auth: forte::ForteAuthType = forte::ForteAuthType::try_from(&req.connector_auth_type)?;
Ok(format!(
"{}/organizations/{}/locations/{}/transactions/{}",
self.base_url(connectors),
auth.organization_id.peek(),
auth.location_id.peek(),
req.request.get_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)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: forte::RefundSyncResponse = res
.response
.parse_struct("forte 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 Forte {
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))
}
}
static FORTE_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::DinersClub,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
];
let mut forte_supported_payment_methods = SupportedPaymentMethods::new();
forte_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
forte_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
forte_supported_payment_methods
});
static FORTE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Forte",
description:
"CSG Forte offers a unified payments platform, enabling businesses to securely process credit cards, debit cards, ACH/eCheck transactions, and more, with advanced fraud prevention and seamless integration.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static FORTE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Forte {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&FORTE_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*FORTE_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&FORTE_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/forte.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5892
}
|
large_file_-8064913599342278431
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/nuvei.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
#[cfg(feature = "payouts")]
use api_models::webhooks::PayoutIdType;
use api_models::{
payments::PaymentIdType,
webhooks::{IncomingWebhookEvent, RefundIdType},
};
use common_enums::{enums, CallConnectorAction, PaymentAction};
use common_utils::{
crypto,
errors::{CustomResult, ReportSwitchExt},
ext_traits::{ByteSliceExt, BytesExt, ValueExt},
id_type,
request::{Method, Request, RequestBuilder, RequestContent},
types::{
AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector, StringMajorUnit,
StringMajorUnitForConnector, StringMinorUnit, StringMinorUnitForConnector,
},
};
use error_stack::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, Session, SetupMandate, Void},
refunds::{Execute, RSync},
AuthorizeSessionToken, CompleteAuthorize, PostCaptureVoid, PreProcessing,
},
router_request_types::{
AccessTokenRequestData, AuthorizeSessionTokenData, CompleteAuthorizeData,
PaymentMethodTokenizationData, PaymentsAuthorizeData, PaymentsCancelData,
PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsPreProcessingData,
PaymentsSessionData, PaymentsSyncData, RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsAuthorizeSessionTokenRouterData,
PaymentsCancelPostCaptureRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData,
PaymentsSyncRouterData, RefundsRouterData,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_flow_types::payouts::PoFulfill, router_request_types::PayoutsData,
router_response_types::PayoutsResponseData, types::PayoutsRouterData,
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorRedirectResponse,
ConnectorSpecifications, ConnectorValidation,
},
configs::Connectors,
disputes, errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
use masking::ExposeInterface;
use transformers as nuvei;
use crate::{
connectors::nuvei::transformers::{NuveiPaymentsResponse, NuveiTransactionSyncResponse},
constants::headers,
types::ResponseRouterData,
utils::{self, is_mandate_supported, PaymentMethodDataType, RouterData as _},
};
#[derive(Clone)]
pub struct Nuvei {
pub amount_convertor: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
amount_converter_string_minor_unit:
&'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
amount_converter_float_major_unit:
&'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Nuvei {
pub fn new() -> &'static Self {
&Self {
amount_convertor: &StringMajorUnitForConnector,
amount_converter_string_minor_unit: &StringMinorUnitForConnector,
amount_converter_float_major_unit: &FloatMajorUnitForConnector,
}
}
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Nuvei
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 headers = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
Ok(headers)
}
}
impl ConnectorCommon for Nuvei {
fn id(&self) -> &'static str {
"nuvei"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.nuvei.base_url.as_ref()
}
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
Ok(vec![])
}
}
impl ConnectorValidation for Nuvei {
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::GooglePay,
PaymentMethodDataType::ApplePay,
PaymentMethodDataType::NetworkTransactionIdAndCardDetails,
]);
is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl api::Payment for Nuvei {}
impl api::PaymentToken for Nuvei {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Nuvei
{
// Not Implemented (R)
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Nuvei {}
impl api::MandateSetup for Nuvei {}
impl api::PaymentVoid for Nuvei {}
impl api::PaymentSync for Nuvei {}
impl api::PaymentCapture for Nuvei {}
impl api::PaymentSession for Nuvei {}
impl api::PaymentAuthorize for Nuvei {}
impl api::PaymentAuthorizeSessionToken for Nuvei {}
impl api::Refund for Nuvei {}
impl api::RefundExecute for Nuvei {}
impl api::RefundSync for Nuvei {}
impl api::PaymentsCompleteAuthorize for Nuvei {}
impl api::ConnectorAccessToken for Nuvei {}
impl api::PaymentsPreProcessing for Nuvei {}
impl api::PaymentPostCaptureVoid for Nuvei {}
impl api::Payouts for Nuvei {}
#[cfg(feature = "payouts")]
impl api::PayoutFulfill for Nuvei {}
#[async_trait::async_trait]
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Nuvei {
fn get_url(
&self,
_req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ppp/api/v1/payout.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoFulfill>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiPayoutRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PayoutFulfillType::get_headers(
self, req, connectors,
)?)
.set_body(types::PayoutFulfillType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PayoutsRouterData<PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoFulfill>, errors::ConnectorError> {
let response: nuvei::NuveiPayoutResponse =
res.response.parse_struct("NuveiPayoutResponse").switch()?;
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<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Nuvei {
fn get_headers(
&self,
req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
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: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ppp/api/v1/payment.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, req.get_session_token()?))?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
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: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
errors::ConnectorError,
> {
let response: NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.switch()?;
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 Nuvei {
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!(
"{}ppp/api/v1/voidTransaction.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiPaymentFlowRequest::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(&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();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.switch()?;
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<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Nuvei
{
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!(
"{}ppp/api/v1/payment.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let meta: nuvei::NuveiMeta = utils::to_connector_meta(req.request.connector_meta.clone())?;
let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, meta.session_token))?;
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: NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.switch()?;
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<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>
for Nuvei
{
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(format!(
"{}ppp/api/v1/voidTransaction.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCancelPostCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiVoidRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelPostCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = 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();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PaymentsCancelPostCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelPostCaptureRouterData, errors::ConnectorError> {
let response: NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.switch()?;
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<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Nuvei {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Nuvei {
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!(
"{}ppp/api/v1/getTransactionDetails.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiPaymentSyncRequest::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(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.set_body(types::PaymentsSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let nuvie_psync_common_response: nuvei::NuveiPaymentSyncResponse = res
.response
.parse_struct("NuveiPaymentSyncResponse")
.switch()?;
event_builder.map(|i| i.set_response_body(&nuvie_psync_common_response));
router_env::logger::info!(connector_response=?nuvie_psync_common_response);
let response = NuveiTransactionSyncResponse::from(nuvie_psync_common_response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Nuvei {
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!(
"{}ppp/api/v1/settleTransaction.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiPaymentFlowRequest::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(&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: NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.switch()?;
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 ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Nuvei {
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!(
"{}ppp/api/v1/payment.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, req.get_session_token()?))?;
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: NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.switch()?;
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<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>
for Nuvei
{
fn get_headers(
&self,
req: &PaymentsAuthorizeSessionTokenRouterData,
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: &PaymentsAuthorizeSessionTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}ppp/api/v1/getSessionToken.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeSessionTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiSessionRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeSessionTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsPreAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsPreAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsPreAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeSessionTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeSessionTokenRouterData, errors::ConnectorError> {
let response: nuvei::NuveiSessionResponse =
res.response.parse_struct("NuveiSessionResponse").switch()?;
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<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
for Nuvei
{
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> {
Ok(format!(
"{}ppp/api/v1/initPayment.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsPreProcessingRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiPaymentsRequest::try_from((req, req.get_session_token()?))?;
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: NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.switch()?;
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 Nuvei {
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!(
"{}ppp/api/v1/refundTransaction.do",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = nuvei::NuveiPaymentFlowRequest::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(&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: NuveiPaymentsResponse = res
.response
.parse_struct("NuveiPaymentsResponse")
.switch()?;
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<RSync, RefundsData, RefundsResponseData> for Nuvei {
fn handle_response(
&self,
data: &RefundsRouterData<RSync>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RouterData<RSync, RefundsData, RefundsResponseData>, errors::ConnectorError>
{
let nuvie_rsync_common_response: nuvei::PaymentDmnNotification = res
.response
.parse_struct("PaymentDmnNotification")
.switch()?;
event_builder.map(|i| i.set_response_body(&nuvie_rsync_common_response));
router_env::logger::info!(connector_response=?nuvie_rsync_common_response);
let response = NuveiTransactionSyncResponse::from(nuvie_rsync_common_response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
}
fn has_payout_prefix(id_option: &Option<String>) -> bool {
// - Default value returns false if the Option is `None`.
// - The argument is a closure that runs if the Option is `Some`.
// It takes the contained value (`s`) and its result is returned.
id_option
.as_deref()
.is_some_and(|s| s.starts_with("payout_"))
}
#[async_trait::async_trait]
impl IncomingWebhook for Nuvei {
fn get_webhook_source_verification_algorithm(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::Sha256))
}
fn get_webhook_source_verification_signature(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let webhook = get_webhook_object_from_body(request.body)?;
let nuvei_notification_signature = match webhook {
nuvei::NuveiWebhook::PaymentDmn(notification) => notification
.advance_response_checksum
.ok_or(errors::ConnectorError::WebhookSignatureNotFound)?,
nuvei::NuveiWebhook::Chargeback(_) => {
utils::get_header_key_value("Checksum", request.headers)?.to_string()
}
};
hex::decode(nuvei_notification_signature)
.change_context(errors::ConnectorError::WebhookSignatureNotFound)
}
fn get_webhook_source_verification_message(
&self,
request: &IncomingWebhookRequestDetails<'_>,
_merchant_id: &id_type::MerchantId,
connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
// Parse the webhook payload
let webhook = get_webhook_object_from_body(request.body)?;
let secret_str = std::str::from_utf8(&connector_webhook_secrets.secret)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
// Generate signature based on webhook type
match webhook {
nuvei::NuveiWebhook::PaymentDmn(notification) => {
// For payment DMNs, use the same format as before
let status = notification
.status
.as_ref()
.map(|s| format!("{s:?}").to_uppercase())
.unwrap_or_default();
let to_sign = transformers::concat_strings(&[
secret_str.to_string(),
notification.total_amount,
notification.currency,
notification.response_time_stamp,
notification.ppp_transaction_id,
status,
notification.product_id.unwrap_or("NA".to_string()),
]);
Ok(to_sign.into_bytes())
}
nuvei::NuveiWebhook::Chargeback(notification) => {
// For chargeback notifications, use a different format based on Nuvei's documentation
// Note: This is a placeholder - you'll need to adjust based on Nuvei's actual chargeback signature format
let response = serde_json::to_string(¬ification)
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let to_sign = format!("{secret_str}{response}");
Ok(to_sign.into_bytes())
}
}
}
fn get_webhook_object_reference_id(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
// Parse the webhook payload
let webhook = get_webhook_object_from_body(request.body)?;
// Extract transaction ID from the webhook
match &webhook {
nuvei::NuveiWebhook::PaymentDmn(notification) => {
// if prefix contains 'payout_' then it is a payout related webhook
if has_payout_prefix(¬ification.client_request_id) {
#[cfg(feature = "payouts")]
{
Ok(api_models::webhooks::ObjectReferenceId::PayoutId(
PayoutIdType::PayoutAttemptId(
notification
.client_request_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorTransactionID)?,
),
))
}
#[cfg(not(feature = "payouts"))]
{
Err(errors::ConnectorError::WebhookEventTypeNotFound.into())
}
} else {
match notification.transaction_type {
Some(nuvei::NuveiTransactionType::Auth)
| Some(nuvei::NuveiTransactionType::Sale)
| Some(nuvei::NuveiTransactionType::Settle)
| Some(nuvei::NuveiTransactionType::Void)
| Some(nuvei::NuveiTransactionType::Auth3D)
| Some(nuvei::NuveiTransactionType::InitAuth3D) => {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
PaymentIdType::ConnectorTransactionId(
notification.transaction_id.clone().ok_or(
errors::ConnectorError::MissingConnectorTransactionID,
)?,
),
))
}
Some(nuvei::NuveiTransactionType::Credit) => {
Ok(api_models::webhooks::ObjectReferenceId::RefundId(
RefundIdType::ConnectorRefundId(
notification
.transaction_id
.clone()
.ok_or(errors::ConnectorError::MissingConnectorRefundID)?,
),
))
}
None => Err(errors::ConnectorError::WebhookEventTypeNotFound.into()),
}
}
}
nuvei::NuveiWebhook::Chargeback(notification) => {
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
PaymentIdType::ConnectorTransactionId(
notification.transaction_details.transaction_id.to_string(),
),
))
}
}
}
fn get_webhook_event_type(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, errors::ConnectorError> {
// Parse the webhook payload
let webhook = get_webhook_object_from_body(request.body)?;
// Map webhook type to event type
match webhook {
nuvei::NuveiWebhook::PaymentDmn(notification) => {
if has_payout_prefix(¬ification.client_request_id) {
#[cfg(feature = "payouts")]
{
if let Some((status, transaction_type)) =
notification.status.zip(notification.transaction_type)
{
nuvei::map_notification_to_event_for_payout(status, transaction_type)
} else {
Err(errors::ConnectorError::WebhookEventTypeNotFound.into())
}
}
#[cfg(not(feature = "payouts"))]
{
Err(errors::ConnectorError::WebhookEventTypeNotFound.into())
}
} else if let Some((status, transaction_type)) =
notification.status.zip(notification.transaction_type)
{
nuvei::map_notification_to_event(status, transaction_type)
} else {
Err(errors::ConnectorError::WebhookEventTypeNotFound.into())
}
}
nuvei::NuveiWebhook::Chargeback(notification) => {
if let Some(dispute_event) = notification.chargeback.dispute_unified_status_code {
nuvei::map_dispute_notification_to_event(dispute_event)
} else {
Err(errors::ConnectorError::WebhookEventTypeNotFound.into())
}
}
}
}
fn get_webhook_resource_object(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notification = get_webhook_object_from_body(request.body)?;
Ok(Box::new(notification))
}
fn get_dispute_details(
&self,
request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<disputes::DisputePayload, errors::ConnectorError> {
let webhook = request
.body
.parse_struct::<nuvei::ChargebackNotification>("ChargebackNotification")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let currency = webhook
.chargeback
.reported_currency
.to_uppercase()
.parse::<enums::Currency>()
.map_err(|_| errors::ConnectorError::ResponseDeserializationFailed)?;
let amount_minorunit = utils::convert_back_amount_to_minor_units(
self.amount_converter_float_major_unit,
webhook.chargeback.reported_amount,
currency,
)?;
let amount = utils::convert_amount(
self.amount_converter_string_minor_unit,
amount_minorunit,
currency,
)?;
let dispute_unified_status_code = webhook
.chargeback
.dispute_unified_status_code
.ok_or(errors::ConnectorError::WebhookEventTypeNotFound)?;
let connector_dispute_id = webhook
.chargeback
.dispute_id
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(disputes::DisputePayload {
amount,
currency,
dispute_stage: api_models::enums::DisputeStage::from(
dispute_unified_status_code.clone(),
),
connector_dispute_id,
connector_reason: webhook.chargeback.chargeback_reason,
connector_reason_code: webhook.chargeback.chargeback_reason_category,
challenge_required_by: webhook.chargeback.dispute_due_date,
connector_status: dispute_unified_status_code.to_string(),
created_at: webhook.chargeback.date,
updated_at: None,
})
}
}
fn get_webhook_object_from_body(
body: &[u8],
) -> CustomResult<nuvei::NuveiWebhook, errors::ConnectorError> {
let payments_response = serde_urlencoded::from_bytes::<nuvei::NuveiWebhook>(body)
.change_context(errors::ConnectorError::ResponseDeserializationFailed);
match payments_response {
Ok(webhook) => Ok(webhook),
Err(_) => body
.parse_struct::<nuvei::NuveiWebhook>("NuveiWebhook")
.change_context(errors::ConnectorError::ResponseDeserializationFailed),
}
}
impl ConnectorRedirectResponse for Nuvei {
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::PaymentAuthenticateCompleteAuthorize => {
Ok(CallConnectorAction::Trigger)
}
PaymentAction::CompleteAuthorize => {
if let Some(payload) = json_payload {
let redirect_response: nuvei::NuveiRedirectionResponse =
payload.parse_value("NuveiRedirectionResponse").switch()?;
let acs_response: nuvei::NuveiACSResponse =
utils::base64_decode(redirect_response.cres.expose())?
.as_slice()
.parse_struct("NuveiACSResponse")
.switch()?;
match acs_response.trans_status {
None | Some(nuvei::LiabilityShift::Failed) => {
Ok(CallConnectorAction::StatusUpdate {
status: enums::AttemptStatus::AuthenticationFailed,
error_code: None,
error_message: Some("3ds Authentication failed".to_string()),
})
}
_ => Ok(CallConnectorAction::Trigger),
}
} else {
Ok(CallConnectorAction::Trigger)
}
}
}
}
}
static NUVEI_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::UnionPay,
common_enums::CardNetwork::Interac,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::CartesBancaires,
];
let mut nuvei_supported_payment_methods = SupportedPaymentMethods::new();
nuvei_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(),
}
}),
),
},
);
nuvei_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(),
}
}),
),
},
);
nuvei_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
enums::PaymentMethodType::Klarna,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
nuvei_supported_payment_methods.add(
enums::PaymentMethod::PayLater,
enums::PaymentMethodType::AfterpayClearpay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
nuvei_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,
},
);
nuvei_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,
},
);
nuvei_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,
},
);
nuvei_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,
},
);
nuvei_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,
},
);
nuvei_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,
},
);
nuvei_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,
},
);
nuvei_supported_payment_methods
});
static NUVEI_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Nuvei",
description: "Nuvei is the Canadian fintech company accelerating the business of clients around the world.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Beta,
};
static NUVEI_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 2] =
[enums::EventClass::Payments, enums::EventClass::Disputes];
impl ConnectorSpecifications for Nuvei {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&NUVEI_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*NUVEI_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&NUVEI_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/nuvei.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 12279
}
|
large_file_-3985516820319502585
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/coingate.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use common_enums::{enums, CaptureMethod, PaymentMethod, PaymentMethodType};
use common_utils::{
crypto,
errors::CustomResult,
ext_traits::{ByteSliceExt, BytesExt, ValueExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::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, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
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, PeekInterface};
use transformers::{self as coingate, CoingateWebhookBody};
use crate::{
constants::headers,
types::ResponseRouterData,
utils::{self, RefundsRequestData},
};
#[derive(Clone)]
pub struct Coingate {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Coingate {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl api::Payment for Coingate {}
impl api::PaymentSession for Coingate {}
impl api::ConnectorAccessToken for Coingate {}
impl api::MandateSetup for Coingate {}
impl api::PaymentAuthorize for Coingate {}
impl api::PaymentSync for Coingate {}
impl api::PaymentCapture for Coingate {}
impl api::PaymentVoid for Coingate {}
impl api::Refund for Coingate {}
impl api::RefundExecute for Coingate {}
impl api::RefundSync for Coingate {}
impl api::PaymentToken for Coingate {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Coingate
{
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Coingate
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 Coingate {
fn id(&self) -> &'static str {
"coingate"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.coingate.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = coingate::CoingateAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Bearer {}", auth.api_key.peek()).into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: coingate::CoingateErrorResponse = res
.response
.parse_struct("CoingateErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let reason = match &response.errors {
Some(errors) => errors.join(" & "),
None => response.reason.clone(),
};
Ok(ErrorResponse {
status_code: res.status_code,
code: response.message.to_string(),
message: response.message.clone(),
reason: Some(reason),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Coingate {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Coingate {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Coingate
{
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Coingate {
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!("{}{}", self.base_url(connectors), "/api/v2/orders"))
}
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 = coingate::CoingateRouterData::from((amount, req));
let connector_req = coingate::CoingatePaymentsRequest::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: coingate::CoingatePaymentsResponse = res
.response
.parse_struct("Coingate 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 Coingate {
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_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/{}{}",
self.base_url(connectors),
"api/v2/orders/",
connector_id
))
}
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: coingate::CoingateSyncResponse = res
.response
.parse_struct("coingate 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 Coingate {
fn build_request(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Capture".to_string(),
connector: "Coingate".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Coingate {
fn build_request(
&self,
_req: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Void".to_string(),
connector: "Coingate".to_string(),
}
.into())
}
}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Coingate {
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!(
"{}/api/v2/orders/{connector_payment_id}/refunds",
self.base_url(connectors),
))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = coingate::CoingateRouterData::from((amount, req));
let connector_req = coingate::CoingateRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(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: coingate::CoingateRefundResponse = res
.response
.parse_struct("coingate 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 Coingate {
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 order_id = req.request.connector_transaction_id.clone();
let id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}/api/v2/orders/{order_id}/refunds/{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(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
req: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: coingate::CoingateRefundResponse = res
.response
.parse_struct("coingate 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: req.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 Coingate {}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Coingate {
fn get_webhook_source_verification_algorithm(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn crypto::VerifySignature + Send>, errors::ConnectorError> {
Ok(Box::new(crypto::HmacSha256))
}
fn get_webhook_source_verification_message(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_secrets: &api_models::webhooks::ConnectorWebhookSecrets,
) -> CustomResult<Vec<u8>, errors::ConnectorError> {
let message = std::str::from_utf8(request.body)
.change_context(errors::ConnectorError::WebhookSourceVerificationFailed)?;
Ok(message.to_string().into_bytes())
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let notif: CoingateWebhookBody = request
.body
.parse_struct("CoingateWebhookBody")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(notif.id.to_string()),
))
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let notif: CoingateWebhookBody = request
.body
.parse_struct("CoingateWebhookBody")
.change_context(errors::ConnectorError::WebhookEventTypeNotFound)?;
match notif.status {
transformers::CoingatePaymentStatus::Pending => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentProcessing)
}
transformers::CoingatePaymentStatus::Confirming
| transformers::CoingatePaymentStatus::New => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentActionRequired)
}
transformers::CoingatePaymentStatus::Paid => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentSuccess)
}
transformers::CoingatePaymentStatus::Invalid
| transformers::CoingatePaymentStatus::Expired
| transformers::CoingatePaymentStatus::Canceled => {
Ok(api_models::webhooks::IncomingWebhookEvent::PaymentIntentFailure)
}
}
}
async fn verify_webhook_source(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
connector_account_details: crypto::Encryptable<masking::Secret<serde_json::Value>>,
_connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
let connector_account_details: ConnectorAuthType = connector_account_details
.parse_value::<ConnectorAuthType>("ConnectorAuthType")
.change_context_lazy(|| errors::ConnectorError::WebhookSourceVerificationFailed)?;
let auth_type = coingate::CoingateAuthType::try_from(&connector_account_details)?;
let secret_key = auth_type.merchant_token.expose();
let request_body: CoingateWebhookBody = request
.body
.parse_struct("CoingateWebhookBody")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
let token = request_body.token.expose();
Ok(secret_key == token)
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let notif: CoingateWebhookBody = request
.body
.parse_struct("CoingateWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
Ok(Box::new(notif))
}
}
static COINGATE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods =
vec![CaptureMethod::Automatic, CaptureMethod::SequentialAutomatic];
let mut coingate_supported_payment_methods = SupportedPaymentMethods::new();
coingate_supported_payment_methods.add(
PaymentMethod::Crypto,
PaymentMethodType::CryptoCurrency,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods,
specific_features: None,
},
);
coingate_supported_payment_methods
});
static COINGATE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Coingate",
description: "CoinGate's online payment solution makes it easy for businesses to accept Bitcoin, Ethereum, stablecoins and other cryptocurrencies for payments on any website.",
connector_type: enums::HyperswitchConnectorCategory::AlternativePaymentMethod,
integration_status: enums::ConnectorIntegrationStatus::Sandbox,
};
static COINGATE_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 1] = [enums::EventClass::Payments];
impl ConnectorSpecifications for Coingate {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&COINGATE_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*COINGATE_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&COINGATE_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/coingate.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 5145
}
|
large_file_7559428210946272709
|
clm
|
file
|
<path>
Repository: hyperswitch
Crate: hyperswitch_connectors
File: crates/hyperswitch_connectors/src/connectors/jpmorgan.rs
</path>
<file>
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
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,
consts, errors,
events::connector_api_logs::ConnectorEvent,
types::{self, RefreshTokenType, Response},
webhooks,
};
use masking::{Mask, Maskable, PeekInterface};
use transformers::{self as jpmorgan, JpmorganErrorResponse};
use crate::{
constants::headers,
types::{RefreshTokenRouterData, ResponseRouterData},
utils,
};
#[derive(Clone)]
pub struct Jpmorgan {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Jpmorgan {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Jpmorgan {}
impl api::PaymentSession for Jpmorgan {}
impl api::ConnectorAccessToken for Jpmorgan {}
impl api::MandateSetup for Jpmorgan {}
impl api::PaymentAuthorize for Jpmorgan {}
impl api::PaymentSync for Jpmorgan {}
impl api::PaymentCapture for Jpmorgan {}
impl api::PaymentVoid for Jpmorgan {}
impl api::Refund for Jpmorgan {}
impl api::RefundExecute for Jpmorgan {}
impl api::RefundSync for Jpmorgan {}
impl api::PaymentToken for Jpmorgan {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Jpmorgan
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Jpmorgan
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 headers = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let auth_header = (
headers::AUTHORIZATION.to_string(),
format!(
"Bearer {}",
req.access_token
.clone()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?
.token
.peek()
)
.into_masked(),
);
let request_id = (
headers::REQUEST_ID.to_string(),
req.connector_request_reference_id
.clone()
.to_string()
.into_masked(),
);
let merchant_id = (
headers::MERCHANT_ID.to_string(),
req.merchant_id.get_string_repr().to_string().into_masked(),
);
headers.push(auth_header);
headers.push(request_id);
headers.push(merchant_id);
Ok(headers)
}
}
impl ConnectorCommon for Jpmorgan {
fn id(&self) -> &'static str {
"jpmorgan"
}
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.jpmorgan.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: JpmorganErrorResponse = res
.response
.parse_struct("JpmorganErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
router_env::logger::info!(connector_response=?response);
event_builder.map(|i| i.set_response_body(&response));
let response_message = response
.response_message
.as_ref()
.map_or_else(|| consts::NO_ERROR_MESSAGE.to_string(), ToString::to_string);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.response_code,
message: response_message.clone(),
reason: Some(response_message),
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 Jpmorgan {
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> {
if data.encoded_data.is_some()
|| data
.connector_transaction_id
.get_connector_transaction_id()
.is_ok()
{
return Ok(());
}
Err(errors::ConnectorError::MissingConnectorTransactionID.into())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Jpmorgan {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Jpmorgan {
fn get_headers(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
let client_id = req.request.app_id.clone();
let client_secret = req.request.id.clone();
let creds = format!(
"{}:{}",
client_id.peek(),
client_secret.unwrap_or_default().peek()
);
let encoded_creds = common_utils::consts::BASE64_ENGINE.encode(creds);
let auth_string = format!("Basic {encoded_creds}");
Ok(vec![
(
headers::CONTENT_TYPE.to_string(),
RefreshTokenType::get_content_type(self).to_string().into(),
),
(
headers::AUTHORIZATION.to_string(),
auth_string.into_masked(),
),
])
}
fn get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn get_url(
&self,
_req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}/am/oauth2/alpha/access_token",
connectors
.jpmorgan
.secondary_base_url
.as_ref()
.ok_or(errors::ConnectorError::FailedToObtainIntegrationUrl)?
))
}
fn get_request_body(
&self,
req: &RefreshTokenRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = jpmorgan::JpmorganAuthUpdateRequest::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefreshTokenRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.attach_default_headers()
.headers(RefreshTokenType::get_headers(self, req, connectors)?)
.url(&RefreshTokenType::get_url(self, req, connectors)?)
.set_body(RefreshTokenType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefreshTokenRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> {
let response: jpmorgan::JpmorganAuthUpdateResponse = res
.response
.parse_struct("jpmorgan JpmorganAuthUpdateResponse")
.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<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
for Jpmorgan
{
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for JPMorgan".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Jpmorgan {
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!("{}/payments", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount: MinorUnit = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = jpmorgan::JpmorganRouterData::from((amount, req));
let connector_req = jpmorgan::JpmorganPaymentsRequest::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: jpmorgan::JpmorganPaymentsResponse = res
.response
.parse_struct("Jpmorgan 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<Capture, PaymentsCaptureData, PaymentsResponseData> for Jpmorgan {
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 tid = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/payments/{}/captures",
self.base_url(connectors),
tid
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount: MinorUnit = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = jpmorgan::JpmorganRouterData::from((amount, req));
let connector_req = jpmorgan::JpmorganCaptureRequest::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: jpmorgan::JpmorganPaymentsResponse = res
.response
.parse_struct("Jpmorgan 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 Jpmorgan {
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> {
let tid = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!("{}/payments/{}", self.base_url(connectors), tid))
}
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: jpmorgan::JpmorganPaymentsResponse = res
.response
.parse_struct("jpmorgan 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<Void, PaymentsCancelData, PaymentsResponseData> for Jpmorgan {
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> {
let tid = req.request.connector_transaction_id.clone();
Ok(format!("{}/payments/{}", self.base_url(connectors), tid))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount: MinorUnit = utils::convert_amount(
self.amount_converter,
req.request.minor_amount.unwrap_or_default(),
req.request.currency.unwrap_or_default(),
)?;
let connector_router_data = jpmorgan::JpmorganRouterData::from((amount, req));
let connector_req = jpmorgan::JpmorganCancelRequest::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::Patch)
.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: jpmorgan::JpmorganCancelResponse = res
.response
.parse_struct("JpmrorganPaymentsVoidResponse")
.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 Jpmorgan {
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 = jpmorgan::JpmorganRouterData::from((refund_amount, req));
let connector_req = jpmorgan::JpmorganRefundRequest::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> {
Ok(Some(
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(),
))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: jpmorgan::JpmorganRefundResponse = res
.response
.parse_struct("JpmorganRefundResponse")
.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 Jpmorgan {
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> {
let tid = req.request.connector_transaction_id.clone();
Ok(format!("{}/refunds/{}", self.base_url(connectors), tid))
}
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: jpmorgan::JpmorganRefundSyncResponse = res
.response
.parse_struct("jpmorgan 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 Jpmorgan {
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 JPMORGAN_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Visa,
];
let mut jpmorgan_supported_payment_methods = SupportedPaymentMethods::new();
jpmorgan_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
jpmorgan_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::NotSupported,
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(),
}
}),
),
},
);
jpmorgan_supported_payment_methods
});
static JPMORGAN_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Jpmorgan",
description:
"J.P. Morgan is a global financial services firm and investment bank, offering banking, asset management, and payment processing solutions",
connector_type: enums::HyperswitchConnectorCategory::BankAcquirer,
integration_status: enums::ConnectorIntegrationStatus::Beta,
};
static JPMORGAN_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = [];
impl ConnectorSpecifications for Jpmorgan {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&JPMORGAN_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*JPMORGAN_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&JPMORGAN_SUPPORTED_WEBHOOK_FLOWS)
}
}
</file>
|
{
"crate": "hyperswitch_connectors",
"file": "crates/hyperswitch_connectors/src/connectors/jpmorgan.rs",
"files": null,
"module": null,
"num_files": null,
"token_count": 6697
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.