text
stringlengths
65
57.3k
file_path
stringlengths
22
92
module
stringclasses
38 values
type
stringclasses
7 values
struct_name
stringlengths
3
60
impl_count
int64
0
60
traits
listlengths
0
59
tokens
int64
16
8.19k
function_name
stringlengths
3
85
type_name
stringlengths
1
67
trait_name
stringclasses
573 values
method_count
int64
0
31
public_method_count
int64
0
19
submodule_count
int64
0
56
export_count
int64
0
9
// File: crates/drainer/src/metrics.rs // Module: drainer use router_env::{counter_metric, global_meter, histogram_metric_f64, histogram_metric_u64}; global_meter!(DRAINER_METER, "DRAINER"); counter_metric!(JOBS_PICKED_PER_STREAM, DRAINER_METER); counter_metric!(CYCLES_COMPLETED_SUCCESSFULLY, DRAINER_METER); counter_metric!(CYCLES_COMPLETED_UNSUCCESSFULLY, DRAINER_METER); counter_metric!(ERRORS_WHILE_QUERY_EXECUTION, DRAINER_METER); counter_metric!(SUCCESSFUL_QUERY_EXECUTION, DRAINER_METER); counter_metric!(SHUTDOWN_SIGNAL_RECEIVED, DRAINER_METER); counter_metric!(SUCCESSFUL_SHUTDOWN, DRAINER_METER); counter_metric!(STREAM_EMPTY, DRAINER_METER); counter_metric!(STREAM_PARSE_FAIL, DRAINER_METER); counter_metric!(DRAINER_HEALTH, DRAINER_METER); histogram_metric_f64!(QUERY_EXECUTION_TIME, DRAINER_METER); // Time in (ms) milliseconds histogram_metric_f64!(REDIS_STREAM_READ_TIME, DRAINER_METER); // Time in (ms) milliseconds histogram_metric_f64!(REDIS_STREAM_TRIM_TIME, DRAINER_METER); // Time in (ms) milliseconds histogram_metric_f64!(CLEANUP_TIME, DRAINER_METER); // Time in (ms) milliseconds histogram_metric_u64!(DRAINER_DELAY_SECONDS, DRAINER_METER); // Time in (s) seconds histogram_metric_f64!(REDIS_STREAM_DEL_TIME, DRAINER_METER); // Time in (ms) milliseconds
crates/drainer/src/metrics.rs
drainer
full_file
null
null
null
361
null
null
null
null
null
null
null
// Function: consumer_error_handler // File: crates/scheduler/src/consumer.rs // Module: scheduler pub fn consumer_error_handler( state: &(dyn SchedulerInterface + 'static)
crates/scheduler/src/consumer.rs
scheduler
function_signature
null
null
null
40
consumer_error_handler
null
null
null
null
null
null
// File: crates/router/src/types/api/verify_connector/paypal.rs // Module: router use error_stack::ResultExt; use super::{VerifyConnector, VerifyConnectorData}; use crate::{ connector, core::errors, routes::SessionState, services, types::{self, api}, }; #[async_trait::async_trait] impl VerifyConnector for connector::Paypal { async fn get_access_token( state: &SessionState, connector_data: VerifyConnectorData, ) -> errors::CustomResult<Option<types::AccessToken>, errors::ApiErrorResponse> { let token_data: types::AccessTokenRequestData = connector_data.connector_auth.clone().try_into()?; let router_data = connector_data.get_router_data(state, token_data, None); let request = connector_data .connector .get_connector_integration() .build_request(&router_data, &state.conf.connectors) .change_context(errors::ApiErrorResponse::InvalidRequestData { message: "Payment request cannot be built".to_string(), })? .ok_or(errors::ApiErrorResponse::InternalServerError)?; let response = services::call_connector_api(&state.to_owned(), request, "get_access_token") .await .change_context(errors::ApiErrorResponse::InternalServerError)?; match response { Ok(res) => Some( connector_data .connector .get_connector_integration() .handle_response(&router_data, None, res) .change_context(errors::ApiErrorResponse::InternalServerError)? .response .map_err(|_| errors::ApiErrorResponse::InternalServerError.into()), ) .transpose(), Err(response_data) => { Self::handle_access_token_error_response::< api::AccessTokenAuth, types::AccessTokenFlowData, types::AccessTokenRequestData, types::AccessToken, >( connector_data.connector.get_connector_integration(), response_data, ) .await } } } }
crates/router/src/types/api/verify_connector/paypal.rs
router
full_file
null
null
null
409
null
null
null
null
null
null
null
// File: crates/storage_impl/src/payments/payment_intent.rs // Module: storage_impl #[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) = &params.customer_id { query = query.filter(pi_dsl::customer_id.eq(customer_id.clone())); } if let Some(profile_id) = &params.profile_id { query = query.filter(pi_dsl::profile_id.eq_any(profile_id.clone())); } query = match (params.starting_at, &params.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, &params.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.currency { Some(currency) => query.filter(pi_dsl::currency.eq_any(currency.clone())), None => query, }; query = match &params.status { Some(status) => query.filter(pi_dsl::status.eq_any(status.clone())), None => query, }; if let Some(currency) = &params.currency { query = query.filter(pi_dsl::currency.eq_any(currency.clone())); } if let Some(status) = &params.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))
crates/storage_impl/src/payments/payment_intent.rs#chunk0
storage_impl
chunk
null
null
null
8,191
null
null
null
null
null
null
null
// Struct: PaymentRequestCards // File: crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaymentRequestCards
crates/hyperswitch_connectors/src/connectors/trustpay/transformers.rs
hyperswitch_connectors
struct_definition
PaymentRequestCards
0
[]
48
null
null
null
null
null
null
null
// Implementation: impl api::ConnectorCustomer for for Gocardless // File: crates/hyperswitch_connectors/src/connectors/gocardless.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::ConnectorCustomer for for Gocardless
crates/hyperswitch_connectors/src/connectors/gocardless.rs
hyperswitch_connectors
impl_block
null
null
null
60
null
Gocardless
api::ConnectorCustomer for
0
0
null
null
// Struct: ItaubankAuthType // File: crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ItaubankAuthType
crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs
hyperswitch_connectors
struct_definition
ItaubankAuthType
0
[]
53
null
null
null
null
null
null
null
// Struct: HipayRouterData // File: crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct HipayRouterData<T>
crates/hyperswitch_connectors/src/connectors/hipay/transformers.rs
hyperswitch_connectors
struct_definition
HipayRouterData
0
[]
52
null
null
null
null
null
null
null
// Implementation: impl api::ConnectorAccessToken for for Blackhawknetwork // File: crates/hyperswitch_connectors/src/connectors/blackhawknetwork.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::ConnectorAccessToken for for Blackhawknetwork
crates/hyperswitch_connectors/src/connectors/blackhawknetwork.rs
hyperswitch_connectors
impl_block
null
null
null
60
null
Blackhawknetwork
api::ConnectorAccessToken for
0
0
null
null
account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SplitPaymentMethodDataRequest { pub payment_method_data: PaymentMethodData, #[schema(value_type = PaymentMethod)] pub payment_method_type: api_enums::PaymentMethod, #[schema(value_type = PaymentMethodType)] pub payment_method_subtype: api_enums::PaymentMethodType, } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct RecordAttemptPaymentMethodDataRequest { /// Additional details for the payment method (e.g., card expiry date, card network). #[serde(flatten)] pub payment_method_data: AdditionalPaymentData, /// billing details for the payment method. pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct ProxyPaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<ProxyPaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum ProxyPaymentMethodData { #[schema(title = "ProxyCardData")] VaultDataCard(Box<ProxyCardData>), VaultToken(VaultToken), } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ProxyCardData { /// The token which refers to the card number #[schema(value_type = String, example = "token_card_number")] pub card_number: Secret<String>, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, /// The first six digit of the card number #[schema(value_type = String, example = "424242")] pub bin_number: Option<String>, /// The last four digit of the card number #[schema(value_type = String, example = "4242")] pub last_four: Option<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct VaultToken { /// The tokenized CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BluecodeRedirect {} => api_enums::PaymentMethodType::Bluecode, Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPay(_) | Self::AmazonPayRedirect(_) => { api_enums::PaymentMethodType::AmazonPay } Self::Skrill(_) => api_enums::PaymentMethodType::Skrill, Self::Paysera(_) => api_enums::PaymentMethodType::Paysera, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, Self::RevolutPay(_) => api_enums::PaymentMethodType::RevolutPay, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::FlexitiRedirect {} => api_enums::PaymentMethodType::Flexiti, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, Self::BreadpayRedirect {} => api_enums::PaymentMethodType::Breadpay, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, Self::InstantBankTransferFinland {} => { api_enums::PaymentMethodType::InstantBankTransferFinland } Self::InstantBankTransferPoland {} => { api_enums::PaymentMethodType::InstantBankTransferPoland } Self::IndonesianBankTransfer { .. } => { api_enums::PaymentMethodType::IndonesianBankTransfer } } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, Self::BhnCardNetwork(_) => api_enums::PaymentMethodType::BhnCardNetwork, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, BhnCardNetwork(BHNGiftCardDetails), } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct BHNGiftCardDetails { /// The gift card or account number #[schema(value_type = String)] pub account_number: Secret<String>, /// The security PIN for gift cards requiring it #[schema(value_type = String)] pub pin: Option<Secret<String>>, /// The CVV2 code for Open Loop/VPLN products #[schema(value_type = String)] pub cvv2: Option<Secret<String>>, /// The expiration date in MMYYYY format for Open Loop/VPLN products #[schema(value_type = String)] pub expiration_date: Option<String>, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, 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>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, /// Indicates if the card issuer is regulated under government-imposed interchange fee caps. /// In the United States, this includes debit cards that fall under the Durbin Amendment, /// which imposes capped interchange fees. pub is_regulated: Option<bool>, /// The global signature network under which the card is issued. /// This represents the primary global card brand, even if the transaction uses a local network pub signature_network: Option<api_enums::CardNetwork>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } impl AdditionalPaymentData { pub fn get_additional_card_info(&self) -> Option<AdditionalCardInfo> { match self { Self::Card(additional_card_info) => Some(*additional_card_info.clone()), _ => None,
crates/api_models/src/payments.rs#chunk3
api_models
chunk
null
null
null
8,192
null
null
null
null
null
null
null
// Struct: PayoutVendorDetails // File: crates/api_models/src/payouts.rs // Module: api_models // Implementations: 0 pub struct PayoutVendorDetails
crates/api_models/src/payouts.rs
api_models
struct_definition
PayoutVendorDetails
0
[]
39
null
null
null
null
null
null
null
// Function: server // File: crates/router/src/routes/app.rs // Module: router pub fn server(state: AppState) -> Scope
crates/router/src/routes/app.rs
router
function_signature
null
null
null
29
server
null
null
null
null
null
null
// Struct: RoutingDictionaryRecord // File: crates/router/src/core/payments/routing/utils.rs // Module: router // Implementations: 0 pub struct RoutingDictionaryRecord
crates/router/src/core/payments/routing/utils.rs
router
struct_definition
RoutingDictionaryRecord
0
[]
38
null
null
null
null
null
null
null
// Struct: SankeyResponse // File: crates/api_models/src/analytics.rs // Module: api_models // Implementations: 0 pub struct SankeyResponse
crates/api_models/src/analytics.rs
api_models
struct_definition
SankeyResponse
0
[]
36
null
null
null
null
null
null
null
// Implementation: impl ConnectorValidation for for Authorizedotnet // File: crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs // Module: hyperswitch_connectors // Methods: 1 total (0 public) impl ConnectorValidation for for Authorizedotnet
crates/hyperswitch_connectors/src/connectors/authorizedotnet.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Authorizedotnet
ConnectorValidation for
1
0
null
null
// Implementation: impl api::PaymentSession for for Santander // File: crates/hyperswitch_connectors/src/connectors/santander.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentSession for for Santander
crates/hyperswitch_connectors/src/connectors/santander.rs
hyperswitch_connectors
impl_block
null
null
null
58
null
Santander
api::PaymentSession for
0
0
null
null
// Struct: UserAuthenticationMethod // File: crates/diesel_models/src/user_authentication_method.rs // Module: diesel_models // Implementations: 0 pub struct UserAuthenticationMethod
crates/diesel_models/src/user_authentication_method.rs
diesel_models
struct_definition
UserAuthenticationMethod
0
[]
38
null
null
null
null
null
null
null
// Implementation: impl webhooks::IncomingWebhook for for Checkbook // File: crates/hyperswitch_connectors/src/connectors/checkbook.rs // Module: hyperswitch_connectors // Methods: 6 total (0 public) impl webhooks::IncomingWebhook for for Checkbook
crates/hyperswitch_connectors/src/connectors/checkbook.rs
hyperswitch_connectors
impl_block
null
null
null
61
null
Checkbook
webhooks::IncomingWebhook for
6
0
null
null
// Function: payment_start_redirection // File: crates/router/src/core/payments.rs // Module: router pub fn payment_start_redirection( state: SessionState, merchant_context: domain::MerchantContext, req: api_models::payments::PaymentStartRedirectionRequest, ) -> RouterResponse<serde_json::Value>
crates/router/src/core/payments.rs
router
function_signature
null
null
null
70
payment_start_redirection
null
null
null
null
null
null
// Implementation: impl api::PaymentSession for for Fiserv // File: crates/hyperswitch_connectors/src/connectors/fiserv.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentSession for for Fiserv
crates/hyperswitch_connectors/src/connectors/fiserv.rs
hyperswitch_connectors
impl_block
null
null
null
60
null
Fiserv
api::PaymentSession for
0
0
null
null
// File: crates/router/src/core/payments/operations/payment_session.rs // Module: router // Public structs: 1 use std::marker::PhantomData; use api_models::{admin::PaymentMethodsEnabled, enums::FrmSuggestion}; use async_trait::async_trait; use common_utils::ext_traits::{AsyncExt, ValueExt}; use error_stack::ResultExt; use router_derive::PaymentOperation; use router_env::{instrument, logger, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, RouterResult, StorageErrorExt}, payments::{self, helpers, operations, PaymentData}, }, routes::{app::ReqState, SessionState}, services, types::{ api::{self, PaymentIdTypeExt}, domain, storage::{self, enums as storage_enums}, }, utils::OptionExt, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "session")] pub struct PaymentSession; type PaymentSessionOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsSessionRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for PaymentSession { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsSessionRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult< operations::GetTrackerResponse<'a, F, api::PaymentsSessionRequest, PaymentData<F>>, > { let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let mut payment_intent = db .find_payment_intent_by_payment_id_merchant_id( &state.into(), &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // TODO (#7195): Add platform merchant account validation once publishable key auth is solved helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Succeeded, ], "create a session token for", )?; helpers::authenticate_client_secret(Some(&request.client_secret), &payment_intent)?; let mut payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, payment_intent.active_attempt.get_id().as_str(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let currency = payment_intent.currency.get_required_value("currency")?; payment_attempt.payment_method = Some(storage_enums::PaymentMethod::Wallet); let amount = payment_attempt.get_total_amount().into(); let shipping_address = helpers::get_address_by_id( state, payment_intent.shipping_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; payment_intent.shipping_address_id = shipping_address.clone().map(|x| x.address_id); payment_intent.billing_address_id = billing_address.clone().map(|x| x.address_id); let customer_details = payments::CustomerDetails { customer_id: payment_intent.customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, tax_registration_id: None, }; let creds_identifier = request .merchant_connector_details .as_ref() .map(|mcd| mcd.creds_identifier.to_owned()); request .merchant_connector_details .to_owned() .async_map(|mcd| async { helpers::insert_merchant_connector_creds_to_config( db, merchant_context.get_merchant_account().get_id(), mcd, ) .await }) .await .transpose()?; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: None, mandate_id: None, mandate_connector: None, customer_acceptance: None, token: None, token_data: None, setup_mandate: None, address: payments::PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), confirm: None, payment_method_data: None, payment_method_token: None, payment_method_info: None, force_sync: None, all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: None, creds_identifier, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data: None, ephemeral_key: None, multiple_capture_data: None, redirect_response: None, surcharge_details: None, frm_message: None, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details: None, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: None, whole_connector_response: None, is_manual_retry_enabled: None, }; let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details: Some(customer_details), payment_data, business_profile, mandate_type: None, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsSessionRequest> for PaymentSession { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, _req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(PaymentSessionOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { let metadata = payment_data.payment_intent.metadata.clone(); payment_data.payment_intent = match metadata { Some(metadata) => state .store .update_payment_intent( &state.into(), payment_data.payment_intent, storage::PaymentIntentUpdate::MetadataUpdate { metadata, updated_by: storage_scheme.to_string(), }, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?, None => payment_data.payment_intent, }; Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsSessionRequest, PaymentData<F>> for PaymentSession { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsSessionRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<(PaymentSessionOperation<'b, F>, operations::ValidateResult)> { //paymentid is already generated and should be sent in the request let given_payment_id = request.payment_id.clone(); Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id: api::PaymentIdType::PaymentIntentId(given_payment_id), storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: false, }, )) } } #[async_trait] impl< F: Clone + Send, Op: Send + Sync + Operation<F, api::PaymentsSessionRequest, Data = PaymentData<F>>, > Domain<F, api::PaymentsSessionRequest, PaymentData<F>> for Op where for<'a> &'a Op: Operation<F, api::PaymentsSessionRequest, Data = PaymentData<F>>, { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<payments::CustomerDetails>, key_store: &domain::MerchantKeyStore, storage_scheme: common_enums::enums::MerchantStorageScheme, ) -> errors::CustomResult< (PaymentSessionOperation<'a, F>, Option<domain::Customer>), errors::StorageError, > { helpers::create_customer_if_not_exist( state, Box::new(self), payment_data, request, &key_store.merchant_id, key_store, storage_scheme, ) .await } #[instrument(skip_all)] async fn make_pm_data<'b>( &'b self, _state: &'b SessionState, _payment_data: &mut PaymentData<F>, _storage_scheme: storage_enums::MerchantStorageScheme, _merchant_key_store: &domain::MerchantKeyStore, _customer: &Option<domain::Customer>, _business_profile: &domain::Profile, _should_retry_with_pan: bool, ) -> RouterResult<( PaymentSessionOperation<'b, F>, Option<domain::PaymentMethodData>, Option<String>, )> { //No payment method data for this operation Ok((Box::new(self), None, None)) } /// Returns `SessionConnectorDatas` /// Steps carried out in this function /// Get all the `merchant_connector_accounts` which are not disabled /// Filter out connectors which have `invoke_sdk_client` enabled in `payment_method_types` /// If session token is requested for certain wallets only, then return them, else /// return all eligible connectors /// /// `GetToken` parameter specifies whether to get the session token from connector integration /// or from separate implementation ( for googlepay - from metadata and applepay - from metadata and call connector) async fn get_connector<'a>( &'a self, merchant_context: &domain::MerchantContext, state: &SessionState, request: &api::PaymentsSessionRequest, payment_intent: &storage::PaymentIntent, ) -> RouterResult<api::ConnectorChoice> { let db = &state.store; let all_connector_accounts = db .find_merchant_connector_account_by_merchant_id_and_disabled_list( &state.into(), merchant_context.get_merchant_account().get_id(), false, merchant_context.get_merchant_key_store(), ) .await .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Database error when querying for merchant connector accounts")?; let profile_id = payment_intent .profile_id .clone() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("profile_id is not set in payment_intent")?; let filtered_connector_accounts = all_connector_accounts .filter_based_on_profile_and_connector_type( &profile_id, common_enums::ConnectorType::PaymentProcessor, ); let requested_payment_method_types = request.wallets.clone(); let mut connector_and_supporting_payment_method_type = Vec::new(); filtered_connector_accounts .iter() .for_each(|connector_account| { let res = connector_account .payment_methods_enabled .clone() .unwrap_or_default() .into_iter() .map(|payment_methods_enabled| { payment_methods_enabled .parse_value::<PaymentMethodsEnabled>("payment_methods_enabled") }) .filter_map(|parsed_payment_method_result| { parsed_payment_method_result .inspect_err(|err| { logger::error!(session_token_parsing_error=?err); }) .ok() }) .flat_map(|parsed_payment_methods_enabled| { parsed_payment_methods_enabled .payment_method_types .unwrap_or_default() .into_iter() .filter(|payment_method_type| { let is_invoke_sdk_client = matches!( payment_method_type.payment_experience, Some(api_models::enums::PaymentExperience::InvokeSdkClient) ); // If session token is requested for the payment method type, // filter it out // if not, then create all sessions tokens let is_sent_in_request = requested_payment_method_types .contains(&payment_method_type.payment_method_type) || requested_payment_method_types.is_empty(); is_invoke_sdk_client && is_sent_in_request }) .map(|payment_method_type| { ( connector_account, payment_method_type.payment_method_type, parsed_payment_methods_enabled.payment_method, ) }) .collect::<Vec<_>>() }) .collect::<Vec<_>>(); connector_and_supporting_payment_method_type.extend(res); }); let mut session_connector_data = api::SessionConnectorDatas::with_capacity( connector_and_supporting_payment_method_type.len(), ); for (merchant_connector_account, payment_method_type, payment_method) in connector_and_supporting_payment_method_type { let connector_type = api::GetToken::from(payment_method_type); if let Ok(connector_data) = api::ConnectorData::get_connector_by_name( &state.conf.connectors, &merchant_connector_account.connector_name.to_string(), connector_type, Some(merchant_connector_account.get_id()), ) .inspect_err(|err| { logger::error!(session_token_error=?err); }) { #[cfg(feature = "v1")] { let new_session_connector_data = api::SessionConnectorData::new( payment_method_type, connector_data, merchant_connector_account.business_sub_label.clone(), payment_method, ); session_connector_data.push(new_session_connector_data) } #[cfg(feature = "v2")] { let new_session_connector_data = api::SessionConnectorData::new(payment_method_type, connector_data, None); session_connector_data.push(new_session_connector_data) } }; } Ok(api::ConnectorChoice::SessionMultiple( session_connector_data, )) } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut PaymentData<F>, ) -> errors::CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } impl From<api_models::enums::PaymentMethodType> for api::GetToken { fn from(value: api_models::enums::PaymentMethodType) -> Self { match value { api_models::enums::PaymentMethodType::GooglePay => Self::GpayMetadata, api_models::enums::PaymentMethodType::ApplePay => Self::ApplePayMetadata, api_models::enums::PaymentMethodType::SamsungPay => Self::SamsungPayMetadata, api_models::enums::PaymentMethodType::Paypal => Self::PaypalSdkMetadata, api_models::enums::PaymentMethodType::Paze => Self::PazeMetadata, api_models::enums::PaymentMethodType::AmazonPay => Self::AmazonPayMetadata, _ => Self::Connector, } } }
crates/router/src/core/payments/operations/payment_session.rs
router
full_file
null
null
null
3,802
null
null
null
null
null
null
null
// Struct: PaymentDetail // File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaymentDetail
crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
hyperswitch_connectors
struct_definition
PaymentDetail
0
[]
47
null
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/barclaycard.rs // Module: hyperswitch_connectors // Public functions: 3 // Public structs: 1 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> {
crates/hyperswitch_connectors/src/connectors/barclaycard.rs#chunk0
hyperswitch_connectors
chunk
null
null
null
8,176
null
null
null
null
null
null
null
// Function: find_payout_link_by_link_id // File: crates/diesel_models/src/query/generic_link.rs // Module: diesel_models pub fn find_payout_link_by_link_id( conn: &PgPooledConn, link_id: &str, ) -> StorageResult<PayoutLink>
crates/diesel_models/src/query/generic_link.rs
diesel_models
function_signature
null
null
null
66
find_payout_link_by_link_id
null
null
null
null
null
null
// Implementation: impl Dispute for for Adyen // File: crates/hyperswitch_connectors/src/connectors/adyen.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl Dispute for for Adyen
crates/hyperswitch_connectors/src/connectors/adyen.rs
hyperswitch_connectors
impl_block
null
null
null
54
null
Adyen
Dispute for
0
0
null
null
// Function: new // File: crates/masking/src/strong_secret.rs // Module: masking // Documentation: Take ownership of a secret value pub fn new(secret: Secret) -> Self
crates/masking/src/strong_secret.rs
masking
function_signature
null
null
null
41
new
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/payload/requests.rs // Module: hyperswitch_connectors // Public structs: 7 use common_utils::types::StringMajorUnit; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::connectors::payload::responses; #[derive(Debug, Serialize, PartialEq)] #[serde(untagged)] pub enum PayloadPaymentsRequest { PayloadCardsRequest(Box<PayloadCardsRequestData>), PayloadMandateRequest(Box<PayloadMandateRequestData>), } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "snake_case")] pub enum TransactionTypes { Credit, Chargeback, ChargebackReversal, Deposit, Payment, Refund, Reversal, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct BillingAddress { #[serde(rename = "payment_method[billing_address][city]")] pub city: String, #[serde(rename = "payment_method[billing_address][country_code]")] pub country: common_enums::CountryAlpha2, #[serde(rename = "payment_method[billing_address][postal_code]")] pub postal_code: Secret<String>, #[serde(rename = "payment_method[billing_address][state_province]")] pub state_province: Secret<String>, #[serde(rename = "payment_method[billing_address][street_address]")] pub street_address: Secret<String>, } #[derive(Debug, Clone, Serialize, PartialEq)] pub struct PayloadCardsRequestData { pub amount: StringMajorUnit, #[serde(flatten)] pub card: PayloadCard, #[serde(rename = "type")] pub transaction_types: TransactionTypes, // For manual capture, set status to "authorized", otherwise omit #[serde(skip_serializing_if = "Option::is_none")] pub status: Option<responses::PayloadPaymentStatus>, #[serde(rename = "payment_method[type]")] pub payment_method_type: String, // Billing address fields are for AVS validation #[serde(flatten)] pub billing_address: BillingAddress, pub processing_id: Option<Secret<String>>, /// Allows one-time payment by customer without saving their payment method /// This is true by default #[serde(rename = "payment_method[keep_active]")] pub keep_active: bool, } #[derive(Debug, Clone, Serialize, PartialEq)] pub struct PayloadMandateRequestData { pub amount: StringMajorUnit, #[serde(rename = "type")] pub transaction_types: TransactionTypes, // Based on the connectors' response, we can do recurring payment either based on a default payment method id saved in the customer profile or a specific payment method id // Connector by default, saves every payment method pub payment_method_id: Secret<String>, // For manual capture, set status to "authorized", otherwise omit #[serde(skip_serializing_if = "Option::is_none")] pub status: Option<responses::PayloadPaymentStatus>, } #[derive(Default, Clone, Debug, Serialize, Eq, PartialEq)] pub struct PayloadCard { #[serde(rename = "payment_method[card][card_number]")] pub number: cards::CardNumber, #[serde(rename = "payment_method[card][expiry]")] pub expiry: Secret<String>, #[serde(rename = "payment_method[card][card_code]")] pub cvc: Secret<String>, } #[derive(Clone, Debug, Serialize, PartialEq)] pub struct PayloadCancelRequest { pub status: responses::PayloadPaymentStatus, } // Type definition for CaptureRequest #[derive(Clone, Debug, Serialize, PartialEq)] pub struct PayloadCaptureRequest { pub status: responses::PayloadPaymentStatus, } // Type definition for RefundRequest #[derive(Debug, Serialize)] pub struct PayloadRefundRequest { #[serde(rename = "type")] pub transaction_type: TransactionTypes, pub amount: StringMajorUnit, #[serde(rename = "ledger[0][assoc_transaction_id]")] pub ledger_assoc_transaction_id: String, }
crates/hyperswitch_connectors/src/connectors/payload/requests.rs
hyperswitch_connectors
full_file
null
null
null
849
null
null
null
null
null
null
null
// Implementation: impl TrustpaymentsErrorResponse // File: crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs // Module: hyperswitch_connectors // Methods: 1 total (1 public) impl TrustpaymentsErrorResponse
crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
hyperswitch_connectors
impl_block
null
null
null
51
null
TrustpaymentsErrorResponse
null
1
1
null
null
// Struct: BraintreeApiErrorResponse // File: crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BraintreeApiErrorResponse
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
hyperswitch_connectors
struct_definition
BraintreeApiErrorResponse
0
[]
50
null
null
null
null
null
null
null
// File: crates/router/src/core/revenue_recovery/api.rs // Module: router // Public functions: 5 use actix_web::{web, Responder}; use api_models::{payments as payments_api, payments as api_payments}; use common_utils::id_type; use error_stack::{report, FutureExt, ResultExt}; use hyperswitch_domain_models::{ merchant_context::{Context, MerchantContext}, payments as payments_domain, }; use crate::{ core::{ errors::{self, RouterResult}, payments::{self, operations::Operation}, webhooks::recovery_incoming, }, db::{ errors::{RouterResponse, StorageErrorExt}, storage::revenue_recovery_redis_operation::RedisTokenManager, }, logger, routes::{app::ReqState, SessionState}, services, types::{ api::payments as api_types, domain, storage::{self, revenue_recovery as revenue_recovery_types}, transformers::ForeignFrom, }, }; pub async fn call_psync_api( state: &SessionState, global_payment_id: &id_type::GlobalPaymentId, revenue_recovery_data: &revenue_recovery_types::RevenueRecoveryPaymentData, force_sync_bool: bool, expand_attempts_bool: bool, ) -> RouterResult<payments_domain::PaymentStatusData<api_types::PSync>> { let operation = payments::operations::PaymentGet; let req = payments_api::PaymentsRetrieveRequest { force_sync: force_sync_bool, param: None, expand_attempts: expand_attempts_bool, return_raw_connector_response: None, merchant_connector_details: None, }; let merchant_context_from_revenue_recovery_data = MerchantContext::NormalMerchant(Box::new(Context( revenue_recovery_data.merchant_account.clone(), revenue_recovery_data.key_store.clone(), ))); // TODO : Use api handler instead of calling get_tracker and payments_operation_core // Get the tracker related information. This includes payment intent and payment attempt let get_tracker_response = operation .to_get_tracker()? .get_trackers( state, global_payment_id, &req, &merchant_context_from_revenue_recovery_data, &revenue_recovery_data.profile, &payments_domain::HeaderPayload::default(), ) .await?; let (payment_data, _req, _, _, _, _) = Box::pin(payments::payments_operation_core::< api_types::PSync, _, _, _, payments_domain::PaymentStatusData<api_types::PSync>, >( state, state.get_req_state(), merchant_context_from_revenue_recovery_data, &revenue_recovery_data.profile, operation, req, get_tracker_response, payments::CallConnectorAction::Trigger, payments_domain::HeaderPayload::default(), )) .await?; Ok(payment_data) } pub async fn call_proxy_api( state: &SessionState, payment_intent: &payments_domain::PaymentIntent, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, revenue_recovery: &payments_api::PaymentRevenueRecoveryMetadata, payment_processor_token: &str, ) -> RouterResult<payments_domain::PaymentConfirmData<api_types::Authorize>> { let operation = payments::operations::proxy_payments_intent::PaymentProxyIntent; let recurring_details = api_models::mandates::ProcessorPaymentToken { processor_payment_token: payment_processor_token.to_string(), merchant_connector_id: Some(revenue_recovery.get_merchant_connector_id_for_api_request()), }; let req = payments_api::ProxyPaymentsRequest { return_url: None, amount: payments_api::AmountDetails::new(payment_intent.amount_details.clone().into()), recurring_details, shipping: None, browser_info: None, connector: revenue_recovery.connector.to_string(), merchant_connector_id: revenue_recovery.get_merchant_connector_id_for_api_request(), }; logger::info!( "Call made to payments proxy api , with the request body {:?}", req ); let merchant_context_from_revenue_recovery_payment_data = MerchantContext::NormalMerchant(Box::new(Context( revenue_recovery_payment_data.merchant_account.clone(), revenue_recovery_payment_data.key_store.clone(), ))); // TODO : Use api handler instead of calling get_tracker and payments_operation_core // Get the tracker related information. This includes payment intent and payment attempt let get_tracker_response = operation .to_get_tracker()? .get_trackers( state, payment_intent.get_id(), &req, &merchant_context_from_revenue_recovery_payment_data, &revenue_recovery_payment_data.profile, &payments_domain::HeaderPayload::default(), ) .await?; let (payment_data, _req, _, _) = Box::pin(payments::proxy_for_payments_operation_core::< api_types::Authorize, _, _, _, payments_domain::PaymentConfirmData<api_types::Authorize>, >( state, state.get_req_state(), merchant_context_from_revenue_recovery_payment_data, revenue_recovery_payment_data.profile.clone(), operation, req, get_tracker_response, payments::CallConnectorAction::Trigger, payments_domain::HeaderPayload::default(), None, )) .await?; Ok(payment_data) } pub async fn update_payment_intent_api( state: &SessionState, global_payment_id: id_type::GlobalPaymentId, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, update_req: payments_api::PaymentsUpdateIntentRequest, ) -> RouterResult<payments_domain::PaymentIntentData<api_types::PaymentUpdateIntent>> { // TODO : Use api handler instead of calling payments_intent_operation_core let operation = payments::operations::PaymentUpdateIntent; let merchant_context_from_revenue_recovery_payment_data = MerchantContext::NormalMerchant(Box::new(Context( revenue_recovery_payment_data.merchant_account.clone(), revenue_recovery_payment_data.key_store.clone(), ))); let (payment_data, _req, _) = payments::payments_intent_operation_core::< api_types::PaymentUpdateIntent, _, _, payments_domain::PaymentIntentData<api_types::PaymentUpdateIntent>, >( state, state.get_req_state(), merchant_context_from_revenue_recovery_payment_data, revenue_recovery_payment_data.profile.clone(), operation, update_req, global_payment_id, payments_domain::HeaderPayload::default(), ) .await?; Ok(payment_data) } pub async fn record_internal_attempt_api( state: &SessionState, payment_intent: &payments_domain::PaymentIntent, revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData, revenue_recovery_metadata: &payments_api::PaymentRevenueRecoveryMetadata, card_info: payments_api::AdditionalCardInfo, payment_processor_token: &str, ) -> RouterResult<payments_api::PaymentAttemptRecordResponse> { let revenue_recovery_attempt_data = recovery_incoming::RevenueRecoveryAttempt::get_revenue_recovery_attempt( payment_intent, revenue_recovery_metadata, &revenue_recovery_payment_data.billing_mca, card_info, payment_processor_token, ) .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "get_revenue_recovery_attempt was not constructed".to_string(), })?; let request_payload = revenue_recovery_attempt_data .create_payment_record_request( state, &revenue_recovery_payment_data.billing_mca.id, Some( revenue_recovery_metadata .active_attempt_payment_connector_id .clone(), ), Some(revenue_recovery_metadata.connector), common_enums::TriggeredBy::Internal, ) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Cannot Create the payment record Request".to_string(), })?; let merchant_context_from_revenue_recovery_payment_data = MerchantContext::NormalMerchant(Box::new(Context( revenue_recovery_payment_data.merchant_account.clone(), revenue_recovery_payment_data.key_store.clone(), ))); let attempt_response = Box::pin(payments::record_attempt_core( state.clone(), state.get_req_state(), merchant_context_from_revenue_recovery_payment_data, revenue_recovery_payment_data.profile.clone(), request_payload, payment_intent.id.clone(), hyperswitch_domain_models::payments::HeaderPayload::default(), )) .await; match attempt_response { Ok(services::ApplicationResponse::JsonWithHeaders((attempt_response, _))) => { Ok(attempt_response) } Ok(_) => Err(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("Unexpected response from record attempt core"), error @ Err(_) => { router_env::logger::error!(?error); Err(errors::ApiErrorResponse::PaymentNotFound) .attach_printable("failed to record attempt for revenue recovery workflow") } } } pub async fn custom_revenue_recovery_core( state: SessionState, req_state: ReqState, merchant_context: MerchantContext, profile: domain::Profile, request: api_models::payments::RecoveryPaymentsCreate, ) -> RouterResponse<payments_api::RecoveryPaymentsResponse> { let store = state.store.as_ref(); let key_manager_state = &(&state).into(); let payment_merchant_connector_account_id = request.payment_merchant_connector_id.to_owned(); // Find the payment & billing merchant connector id at the top level to avoid multiple DB calls. let payment_merchant_connector_account = store .find_merchant_connector_account_by_id( key_manager_state, &payment_merchant_connector_account_id, merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: payment_merchant_connector_account_id .clone() .get_string_repr() .to_string(), })?; let billing_connector_account = store .find_merchant_connector_account_by_id( key_manager_state, &request.billing_merchant_connector_id.clone(), merchant_context.get_merchant_key_store(), ) .await .to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound { id: request .billing_merchant_connector_id .clone() .get_string_repr() .to_string(), })?; let recovery_intent = recovery_incoming::RevenueRecoveryInvoice::get_or_create_custom_recovery_intent( request.clone(), &state, &req_state, &merchant_context, &profile, ) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: format!( "Failed to load recovery intent for merchant reference id : {:?}", request.merchant_reference_id.to_owned() ) .to_string(), })?; let (revenue_recovery_attempt_data, updated_recovery_intent) = recovery_incoming::RevenueRecoveryAttempt::load_recovery_attempt_from_api( request.clone(), &state, &req_state, &merchant_context, &profile, recovery_intent.clone(), payment_merchant_connector_account, ) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: format!( "Failed to load recovery attempt for merchant reference id : {:?}", request.merchant_reference_id.to_owned() ) .to_string(), })?; let intent_retry_count = updated_recovery_intent .feature_metadata .as_ref() .and_then(|metadata| metadata.get_retry_count()) .ok_or(report!(errors::ApiErrorResponse::GenericNotFoundError { message: "Failed to fetch retry count from intent feature metadata".to_string(), }))?; router_env::logger::info!("Intent retry count: {:?}", intent_retry_count); let recovery_action = recovery_incoming::RecoveryAction { action: request.action.to_owned(), }; let mca_retry_threshold = billing_connector_account .get_retry_threshold() .ok_or(report!(errors::ApiErrorResponse::GenericNotFoundError { message: "Failed to fetch retry threshold from billing merchant connector account" .to_string(), }))?; recovery_action .handle_action( &state, &profile, &merchant_context, &billing_connector_account, mca_retry_threshold, intent_retry_count, &( Some(revenue_recovery_attempt_data), updated_recovery_intent.clone(), ), ) .await .change_context(errors::ApiErrorResponse::GenericNotFoundError { message: "Unexpected response from recovery core".to_string(), })?; let response = api_models::payments::RecoveryPaymentsResponse { id: updated_recovery_intent.payment_id.to_owned(), intent_status: updated_recovery_intent.status.to_owned(), merchant_reference_id: updated_recovery_intent.merchant_reference_id.to_owned(), }; Ok(hyperswitch_domain_models::api::ApplicationResponse::Json( response, )) }
crates/router/src/core/revenue_recovery/api.rs
router
full_file
null
null
null
2,768
null
null
null
null
null
null
null
// Implementation: impl Responder // File: crates/router/src/analytics.rs // Module: router // Methods: 0 total (0 public) impl Responder
crates/router/src/analytics.rs
router
impl_block
null
null
null
35
null
Responder
null
0
0
null
null
// Struct: SantanderPaymentsCancelRequest // File: crates/hyperswitch_connectors/src/connectors/santander/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct SantanderPaymentsCancelRequest
crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
hyperswitch_connectors
struct_definition
SantanderPaymentsCancelRequest
0
[]
52
null
null
null
null
null
null
null
// Struct: PaymentProcessorTokenWithRetryInfo // File: crates/router/src/types/storage/revenue_recovery_redis_operation.rs // Module: router // Implementations: 0 pub struct PaymentProcessorTokenWithRetryInfo
crates/router/src/types/storage/revenue_recovery_redis_operation.rs
router
struct_definition
PaymentProcessorTokenWithRetryInfo
0
[]
45
null
null
null
null
null
null
null
// Struct: ThirdPartyMessages // File: crates/hyperswitch_connectors/src/connectors/nordea/requests.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ThirdPartyMessages
crates/hyperswitch_connectors/src/connectors/nordea/requests.rs
hyperswitch_connectors
struct_definition
ThirdPartyMessages
0
[]
47
null
null
null
null
null
null
null
// Implementation: impl api::Refund for for Fiserv // File: crates/hyperswitch_connectors/src/connectors/fiserv.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::Refund for for Fiserv
crates/hyperswitch_connectors/src/connectors/fiserv.rs
hyperswitch_connectors
impl_block
null
null
null
60
null
Fiserv
api::Refund for
0
0
null
null
// Implementation: impl api::PaymentAuthorize for for Placetopay // File: crates/hyperswitch_connectors/src/connectors/placetopay.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentAuthorize for for Placetopay
crates/hyperswitch_connectors/src/connectors/placetopay.rs
hyperswitch_connectors
impl_block
null
null
null
63
null
Placetopay
api::PaymentAuthorize for
0
0
null
null
// Implementation: impl PaypalUpdateOrderRequest // File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs // Module: hyperswitch_connectors // Methods: 1 total (1 public) impl PaypalUpdateOrderRequest
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
hyperswitch_connectors
impl_block
null
null
null
52
null
PaypalUpdateOrderRequest
null
1
1
null
null
// Implementation: impl api::PaymentVoid for for Worldpay // File: crates/hyperswitch_connectors/src/connectors/worldpay.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentVoid for for Worldpay
crates/hyperswitch_connectors/src/connectors/worldpay.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Worldpay
api::PaymentVoid for
0
0
null
null
// Implementation: impl ConnectorCommon for for Nomupay // File: crates/hyperswitch_connectors/src/connectors/nomupay.rs // Module: hyperswitch_connectors // Methods: 6 total (0 public) impl ConnectorCommon for for Nomupay
crates/hyperswitch_connectors/src/connectors/nomupay.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Nomupay
ConnectorCommon for
6
0
null
null
// Struct: SamsungPayPaymentInformation // File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct SamsungPayPaymentInformation
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
hyperswitch_connectors
struct_definition
SamsungPayPaymentInformation
0
[]
51
null
null
null
null
null
null
null
// Implementation: impl ConnectorSpecifications for for Klarna // File: crates/hyperswitch_connectors/src/connectors/klarna.rs // Module: hyperswitch_connectors // Methods: 3 total (0 public) impl ConnectorSpecifications for for Klarna
crates/hyperswitch_connectors/src/connectors/klarna.rs
hyperswitch_connectors
impl_block
null
null
null
54
null
Klarna
ConnectorSpecifications for
3
0
null
null
// Function: get_header_value_by_key // File: crates/router/src/services/authentication.rs // Module: router pub fn get_header_value_by_key(&self, key: &str) -> Option<&str>
crates/router/src/services/authentication.rs
router
function_signature
null
null
null
44
get_header_value_by_key
null
null
null
null
null
null
// Struct: SmithyEnumValue // File: crates/smithy-core/src/types.rs // Module: smithy-core // Implementations: 0 pub struct SmithyEnumValue
crates/smithy-core/src/types.rs
smithy-core
struct_definition
SmithyEnumValue
0
[]
40
null
null
null
null
null
null
null
// Function: add_payment_method_token // File: crates/router/src/core/payments/tokenization.rs // Module: router pub fn add_payment_method_token<F: Clone, T: types::Tokenizable + Clone>( state: &SessionState, connector: &api::ConnectorData, tokenization_action: &payments::TokenizationAction, router_data: &mut types::RouterData<F, T, types::PaymentsResponseData>, pm_token_request_data: types::PaymentMethodTokenizationData, should_continue_payment: bool, ) -> RouterResult<types::PaymentMethodTokenResult>
crates/router/src/core/payments/tokenization.rs
router
function_signature
null
null
null
126
add_payment_method_token
null
null
null
null
null
null
// Struct: GetSubscriptionPlanPrices // File: crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs // Module: hyperswitch_domain_models // Implementations: 0 pub struct GetSubscriptionPlanPrices
crates/hyperswitch_domain_models/src/router_flow_types/subscriptions.rs
hyperswitch_domain_models
struct_definition
GetSubscriptionPlanPrices
0
[]
47
null
null
null
null
null
null
null
// Implementation: impl super::refunds::metrics::RefundMetricAnalytics for for SqlxClient // File: crates/analytics/src/sqlx.rs // Module: analytics // Methods: 0 total (0 public) impl super::refunds::metrics::RefundMetricAnalytics for for SqlxClient
crates/analytics/src/sqlx.rs
analytics
impl_block
null
null
null
64
null
SqlxClient
super::refunds::metrics::RefundMetricAnalytics for
0
0
null
null
// Struct: PaymentMethodOptions // File: crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaymentMethodOptions
crates/hyperswitch_connectors/src/connectors/rapyd/transformers.rs
hyperswitch_connectors
struct_definition
PaymentMethodOptions
0
[]
48
null
null
null
null
null
null
null
// Implementation: impl NetworkTokenWebhookResponse // File: crates/router/src/core/webhooks/network_tokenization_incoming.rs // Module: router // Methods: 3 total (1 public) impl NetworkTokenWebhookResponse
crates/router/src/core/webhooks/network_tokenization_incoming.rs
router
impl_block
null
null
null
47
null
NetworkTokenWebhookResponse
null
3
1
null
null
// Function: mock_get_card // File: crates/router/src/core/payment_methods/cards.rs // Module: router pub fn mock_get_card<'a>( db: &dyn db::StorageInterface, card_id: &'a str, ) -> errors::CustomResult<(payment_methods::GetCardResponse, Option<String>), errors::VaultError>
crates/router/src/core/payment_methods/cards.rs
router
function_signature
null
null
null
73
mock_get_card
null
null
null
null
null
null
// Implementation: impl RedisConnInterface for for RouterStore // File: crates/storage_impl/src/lib.rs // Module: storage_impl // Methods: 1 total (0 public) impl RedisConnInterface for for RouterStore
crates/storage_impl/src/lib.rs
storage_impl
impl_block
null
null
null
46
null
RouterStore
RedisConnInterface for
1
0
null
null
// Implementation: impl api::MandateSetup for for Peachpayments // File: crates/hyperswitch_connectors/src/connectors/peachpayments.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::MandateSetup for for Peachpayments
crates/hyperswitch_connectors/src/connectors/peachpayments.rs
hyperswitch_connectors
impl_block
null
null
null
63
null
Peachpayments
api::MandateSetup for
0
0
null
null
// Function: unlock_connector_customer_status // File: crates/router/src/core/revenue_recovery_data_backfill.rs // Module: router pub fn unlock_connector_customer_status( state: SessionState, connector_customer_id: String, ) -> RouterResult<ApplicationResponse<UnlockStatusResponse>>
crates/router/src/core/revenue_recovery_data_backfill.rs
router
function_signature
null
null
null
59
unlock_connector_customer_status
null
null
null
null
null
null
// Function: get_connector_tokenization_action_when_confirm_true // File: crates/router/src/core/payments.rs // Module: router pub fn get_connector_tokenization_action_when_confirm_true<F, Req, D>( state: &SessionState, operation: &BoxedOperation<'_, F, Req, D>, payment_data: &mut D, validate_result: &operations::ValidateResult, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, should_retry_with_pan: bool, ) -> RouterResult<(D, TokenizationAction)> where F: Send + Clone, D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
crates/router/src/core/payments.rs
router
function_signature
null
null
null
166
get_connector_tokenization_action_when_confirm_true
null
null
null
null
null
null
// Function: find_by_merchant_id_payment_id // File: crates/diesel_models/src/query/dispute.rs // Module: diesel_models pub fn find_by_merchant_id_payment_id( conn: &PgPooledConn, merchant_id: &common_utils::id_type::MerchantId, payment_id: &common_utils::id_type::PaymentId, ) -> StorageResult<Vec<Self>>
crates/diesel_models/src/query/dispute.rs
diesel_models
function_signature
null
null
null
85
find_by_merchant_id_payment_id
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs // Module: hyperswitch_connectors // Public functions: 11 // Public structs: 32 use base64::Engine; use common_enums::enums; use common_utils::{ consts::BASE64_ENGINE, crypto::{EncodeMessage, SignMessage}, ext_traits::{Encode, ValueExt}, types::StringMinorUnit, }; use error_stack::ResultExt; use hyperswitch_domain_models::{ address::Address, payment_method_data::PaymentMethodData, router_data::{ConnectorAuthType, ErrorResponse, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::{ BrowserInformation, CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData, PaymentsPreProcessingData, PaymentsSyncData, ResponseId, }, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{ PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData, PaymentsCompleteAuthorizeRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::errors; use masking::{ExposeInterface, PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{ self as connector_utils, AddressDetailsData, BrowserInformationData, CardData, PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, RouterData as _, }, }; type Error = error_stack::Report<errors::ConnectorError>; const DS_VERSION: &str = "0.0"; const SIGNATURE_VERSION: &str = "HMAC_SHA256_V1"; const XMLNS_WEB_URL: &str = "http://webservices.apl02.redsys.es"; pub const REDSYS_SOAP_ACTION: &str = "consultaOperaciones"; // Specifies the type of transaction for XML requests pub mod transaction_type { pub const PAYMENT: &str = "0"; pub const PREAUTHORIZATION: &str = "1"; pub const CONFIRMATION: &str = "2"; pub const REFUND: &str = "3"; pub const CANCELLATION: &str = "9"; } pub struct RedsysRouterData<T> { pub amount: StringMinorUnit, pub currency: api_models::enums::Currency, pub router_data: T, } impl<T> From<(StringMinorUnit, T, api_models::enums::Currency)> for RedsysRouterData<T> { fn from((amount, item, currency): (StringMinorUnit, T, api_models::enums::Currency)) -> Self { Self { amount, currency, router_data: item, } } } #[derive(Debug, Serialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub struct PaymentsRequest { ds_merchant_emv3ds: Option<EmvThreedsData>, ds_merchant_transactiontype: RedsysTransactionType, ds_merchant_currency: String, ds_merchant_pan: cards::CardNumber, ds_merchant_merchantcode: Secret<String>, ds_merchant_terminal: Secret<String>, ds_merchant_order: String, ds_merchant_amount: StringMinorUnit, ds_merchant_expirydate: Secret<String>, ds_merchant_cvv2: Secret<String>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct EmvThreedsData { three_d_s_info: RedsysThreeDsInfo, protocol_version: Option<String>, browser_accept_header: Option<String>, browser_user_agent: Option<String>, browser_java_enabled: Option<bool>, browser_javascript_enabled: Option<bool>, browser_language: Option<String>, browser_color_depth: Option<String>, browser_screen_height: Option<String>, browser_screen_width: Option<String>, browser_t_z: Option<String>, browser_i_p: Option<Secret<String, common_utils::pii::IpAddress>>, three_d_s_server_trans_i_d: Option<String>, notification_u_r_l: Option<String>, three_d_s_comp_ind: Option<ThreeDSCompInd>, cres: Option<String>, #[serde(flatten)] billing_data: Option<BillingData>, #[serde(flatten)] shipping_data: Option<ShippingData>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct BillingData { bill_addr_city: Option<String>, bill_addr_country: Option<String>, bill_addr_line1: Option<Secret<String>>, bill_addr_line2: Option<Secret<String>>, bill_addr_line3: Option<Secret<String>>, bill_addr_postal_code: Option<Secret<String>>, bill_addr_state: Option<Secret<String>>, } #[derive(Debug, Serialize)] #[serde(rename_all = "camelCase")] pub struct ShippingData { ship_addr_city: Option<String>, ship_addr_country: Option<String>, ship_addr_line1: Option<Secret<String>>, ship_addr_line2: Option<Secret<String>>, ship_addr_line3: Option<Secret<String>>, ship_addr_postal_code: Option<Secret<String>>, ship_addr_state: Option<Secret<String>>, } impl EmvThreedsData { pub fn new(three_d_s_info: RedsysThreeDsInfo) -> Self { Self { three_d_s_info, protocol_version: None, browser_accept_header: None, browser_user_agent: None, browser_java_enabled: None, browser_javascript_enabled: None, browser_language: None, browser_color_depth: None, browser_screen_height: None, browser_screen_width: None, browser_t_z: None, browser_i_p: None, three_d_s_server_trans_i_d: None, notification_u_r_l: None, three_d_s_comp_ind: None, cres: None, billing_data: None, shipping_data: None, } } pub fn add_browser_data(mut self, browser_info: BrowserInformation) -> Result<Self, Error> { self.browser_accept_header = Some(browser_info.get_accept_header()?); self.browser_user_agent = Some(browser_info.get_user_agent()?); self.browser_java_enabled = Some(browser_info.get_java_enabled()?); self.browser_javascript_enabled = browser_info.get_java_script_enabled().ok(); self.browser_language = Some(browser_info.get_language()?); self.browser_color_depth = Some(browser_info.get_color_depth()?.to_string()); self.browser_screen_height = Some(browser_info.get_screen_height()?.to_string()); self.browser_screen_width = Some(browser_info.get_screen_width()?.to_string()); self.browser_t_z = Some(browser_info.get_time_zone()?.to_string()); self.browser_i_p = Some(browser_info.get_ip_address()?); Ok(self) } pub fn set_three_d_s_server_trans_i_d(mut self, three_d_s_server_trans_i_d: String) -> Self { self.three_d_s_server_trans_i_d = Some(three_d_s_server_trans_i_d); self } pub fn set_protocol_version(mut self, protocol_version: String) -> Self { self.protocol_version = Some(protocol_version); self } pub fn set_notification_u_r_l(mut self, notification_u_r_l: String) -> Self { self.notification_u_r_l = Some(notification_u_r_l); self } pub fn set_three_d_s_comp_ind(mut self, three_d_s_comp_ind: ThreeDSCompInd) -> Self { self.three_d_s_comp_ind = Some(three_d_s_comp_ind); self } pub fn set_three_d_s_cres(mut self, cres: String) -> Self { self.cres = Some(cres); self } fn get_state_code(state: Secret<String>) -> Result<Secret<String>, Error> { let state = connector_utils::normalize_string(state.expose()) .change_context(errors::ConnectorError::RequestEncodingFailed)?; let addr_state_value = if state.len() > 3 { let addr_state = match state.as_str() { "acoruna" | "lacoruna" | "esc" => Ok("C"), "alacant" | "esa" | "alicante" => Ok("A"), "albacete" | "esab" => Ok("AB"), "almeria" | "esal" => Ok("AL"), "andalucia" | "esan" => Ok("AN"), "araba" | "esvi" => Ok("VI"), "aragon" | "esar" => Ok("AR"), "asturias" | "eso" => Ok("O"), "asturiasprincipadode" | "principadodeasturias" | "esas" => Ok("AS"), "badajoz" | "esba" => Ok("BA"), "barcelona" | "esb" => Ok("B"), "bizkaia" | "esbi" => Ok("BI"), "burgos" | "esbu" => Ok("BU"), "canarias" | "escn" => Ok("CN"), "cantabria" | "ess" => Ok("S"), "castello" | "escs" => Ok("CS"), "castellon" => Ok("C"), "castillayleon" | "escl" => Ok("CL"), "castillalamancha" | "escm" => Ok("CM"), "cataluna" | "catalunya" | "esct" => Ok("CT"), "ceuta" | "esce" => Ok("CE"), "ciudadreal" | "escr" | "ciudad" => Ok("CR"), "cuenca" | "escu" => Ok("CU"), "caceres" | "escc" => Ok("CC"), "cadiz" | "esca" => Ok("CA"), "cordoba" | "esco" => Ok("CO"), "euskalherria" | "espv" => Ok("PV"), "extremadura" | "esex" => Ok("EX"), "galicia" | "esga" => Ok("GA"), "gipuzkoa" | "esss" => Ok("SS"), "girona" | "esgi" | "gerona" => Ok("GI"), "granada" | "esgr" => Ok("GR"), "guadalajara" | "esgu" => Ok("GU"), "huelva" | "esh" => Ok("H"), "huesca" | "eshu" => Ok("HU"), "illesbalears" | "islasbaleares" | "espm" => Ok("PM"), "esib" => Ok("IB"), "jaen" | "esj" => Ok("J"), "larioja" | "eslo" => Ok("LO"), "esri" => Ok("RI"), "laspalmas" | "palmas" | "esgc" => Ok("GC"), "leon" => Ok("LE"), "lleida" | "lerida" | "esl" => Ok("L"), "lugo" | "eslu" => Ok("LU"), "madrid" | "esm" => Ok("M"), "comunidaddemadrid" | "madridcomunidadde" | "esmd" => Ok("MD"), "melilla" | "esml" => Ok("ML"), "murcia" | "esmu" => Ok("MU"), "murciaregionde" | "regiondemurcia" | "esmc" => Ok("MC"), "malaga" | "esma" => Ok("MA"), "nafarroa" | "esnc" => Ok("NC"), "nafarroakoforukomunitatea" | "esna" => Ok("NA"), "navarra" => Ok("NA"), "navarracomunidadforalde" | "comunidadforaldenavarra" => Ok("NC"), "ourense" | "orense" | "esor" => Ok("OR"), "palencia" | "esp" => Ok("P"), "paisvasco" => Ok("PV"), "pontevedra" | "espo" => Ok("PO"), "salamanca" | "essa" => Ok("SA"), "santacruzdetenerife" | "estf" => Ok("TF"), "segovia" | "essg" => Ok("SG"), "sevilla" | "esse" => Ok("SE"), "soria" | "esso" => Ok("SO"), "tarragona" | "est" => Ok("T"), "teruel" | "este" => Ok("TE"), "toledo" | "esto" => Ok("TO"), "valencia" | "esv" => Ok("V"), "valencianacomunidad" | "esvc" => Ok("VC"), "valencianacomunitat" => Ok("V"), "valladolid" | "esva" => Ok("VA"), "zamora" | "esza" => Ok("ZA"), "zaragoza" | "esz" => Ok("Z"), "alava" => Ok("VI"), "avila" | "esav" => Ok("AV"), _ => Err(errors::ConnectorError::InvalidDataFormat { field_name: "address.state", }), }?; addr_state.to_string() } else { state.to_string() }; Ok(Secret::new(addr_state_value)) } pub fn set_billing_data(mut self, address: Option<&Address>) -> Result<Self, Error> { self.billing_data = address .and_then(|address| { address.address.as_ref().map(|address_details| { let state = address_details .get_optional_state() .map(Self::get_state_code) .transpose(); match state { Ok(bill_addr_state) => Ok(BillingData { bill_addr_city: address_details.get_optional_city(), bill_addr_country: address_details.get_optional_country().map( |country| { common_enums::CountryAlpha2::from_alpha2_to_alpha3(country) .to_string() }, ), bill_addr_line1: address_details.get_optional_line1(), bill_addr_line2: address_details.get_optional_line2(), bill_addr_line3: address_details.get_optional_line3(), bill_addr_postal_code: address_details.get_optional_zip(), bill_addr_state, }), Err(err) => Err(err), } }) }) .transpose()?; Ok(self) } pub fn set_shipping_data(mut self, address: Option<&Address>) -> Result<Self, Error> { self.shipping_data = address .and_then(|address| { address.address.as_ref().map(|address_details| { let state = address_details .get_optional_state() .map(Self::get_state_code) .transpose(); match state { Ok(ship_addr_state) => Ok(ShippingData { ship_addr_city: address_details.get_optional_city(), ship_addr_country: address_details.get_optional_country().map( |country| { common_enums::CountryAlpha2::from_alpha2_to_alpha3(country) .to_string() }, ), ship_addr_line1: address_details.get_optional_line1(), ship_addr_line2: address_details.get_optional_line2(), ship_addr_line3: address_details.get_optional_line3(), ship_addr_postal_code: address_details.get_optional_zip(), ship_addr_state, }), Err(err) => Err(err), } }) }) .transpose()?; Ok(self) } } #[derive(Debug)] pub struct RedsysCardData { card_number: cards::CardNumber, expiry_date: Secret<String>, cvv2: Secret<String>, } impl TryFrom<&Option<PaymentMethodData>> for RedsysCardData { type Error = Error; fn try_from(payment_method_data: &Option<PaymentMethodData>) -> Result<Self, Self::Error> { match payment_method_data { Some(PaymentMethodData::Card(card)) => { let year = card.get_card_expiry_year_2_digit()?.expose(); let month = card.get_card_expiry_month_2_digit()?.expose(); let expiry_date = Secret::new(format!("{year}{month}")); Ok(Self { card_number: card.card_number.clone(), expiry_date, cvv2: card.card_cvc.clone(), }) } Some(PaymentMethodData::Wallet(..)) | Some(PaymentMethodData::PayLater(..)) | Some(PaymentMethodData::BankDebit(..)) | Some(PaymentMethodData::BankRedirect(..)) | Some(PaymentMethodData::BankTransfer(..)) | Some(PaymentMethodData::Crypto(..)) | Some(PaymentMethodData::MandatePayment) | Some(PaymentMethodData::GiftCard(..)) | Some(PaymentMethodData::Voucher(..)) | Some(PaymentMethodData::CardRedirect(..)) | Some(PaymentMethodData::Reward) | Some(PaymentMethodData::RealTimePayment(..)) | Some(PaymentMethodData::MobilePayment(..)) | Some(PaymentMethodData::Upi(..)) | Some(PaymentMethodData::OpenBanking(_)) | Some(PaymentMethodData::CardToken(..)) | Some(PaymentMethodData::NetworkToken(..)) | Some(PaymentMethodData::CardDetailsForNetworkTransactionId(_)) | None => Err(errors::ConnectorError::NotImplemented( connector_utils::get_unimplemented_payment_method_error_message("redsys"), ) .into()), } } } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "PascalCase")] pub enum RedsysThreeDsInfo { CardData, CardConfiguration, ChallengeRequest, ChallengeResponse, AuthenticationData, } #[derive(Debug, Serialize, Deserialize)] pub enum RedsysTransactionType { #[serde(rename = "0")] Payment, #[serde(rename = "1")] Preauthorization, #[serde(rename = "2")] Confirmation, #[serde(rename = "3")] Refund, #[serde(rename = "9")] Cancellation, } pub struct RedsysAuthType { pub(super) merchant_id: Secret<String>, pub(super) terminal_id: Secret<String>, pub(super) sha256_pwd: Secret<String>, } impl TryFrom<&ConnectorAuthType> for RedsysAuthType { type Error = Error; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { if let ConnectorAuthType::SignatureKey { api_key, key1, api_secret, } = auth_type { Ok(Self { merchant_id: api_key.to_owned(), terminal_id: key1.to_owned(), sha256_pwd: api_secret.to_owned(), }) } else { Err(errors::ConnectorError::FailedToObtainAuthType)? } } } impl TryFrom<&RedsysRouterData<&PaymentsPreProcessingRouterData>> for RedsysTransaction { type Error = Error; fn try_from( item: &RedsysRouterData<&PaymentsPreProcessingRouterData>, ) -> Result<Self, Self::Error> { let auth = RedsysAuthType::try_from(&item.router_data.connector_auth_type)?; if !item.router_data.is_three_ds() { Err(errors::ConnectorError::NotSupported { message: "PreProcessing flow for no-3ds cards".to_string(), connector: "redsys", })? }; let redsys_preprocessing_request = if item.router_data.auth_type == enums::AuthenticationType::ThreeDs { let ds_merchant_emv3ds = Some(EmvThreedsData::new(RedsysThreeDsInfo::CardData)); let ds_merchant_transactiontype = if item.router_data.request.is_auto_capture()? { RedsysTransactionType::Payment } else { RedsysTransactionType::Preauthorization }; let ds_merchant_order = if item.router_data.connector_request_reference_id.len() <= 12 { Ok(item.router_data.connector_request_reference_id.clone()) } else { Err(errors::ConnectorError::MaxFieldLengthViolated { connector: "Redsys".to_string(), field_name: "ds_merchant_order".to_string(), max_length: 12, received_length: item.router_data.connector_request_reference_id.len(), }) }?; let card_data = RedsysCardData::try_from(&item.router_data.request.payment_method_data)?; Ok(PaymentsRequest { ds_merchant_emv3ds, ds_merchant_transactiontype, ds_merchant_currency: item.currency.iso_4217().to_owned(), ds_merchant_pan: card_data.card_number, ds_merchant_merchantcode: auth.merchant_id.clone(), ds_merchant_terminal: auth.terminal_id.clone(), ds_merchant_order, ds_merchant_amount: item.amount.clone(), ds_merchant_expirydate: card_data.expiry_date, ds_merchant_cvv2: card_data.cvv2, }) } else { Err(errors::ConnectorError::FlowNotSupported { flow: "PreProcessing".to_string(), connector: "redsys".to_string(), }) }?; Self::try_from((&redsys_preprocessing_request, &auth)) } } #[derive(Debug, Deserialize, Serialize, Clone)] #[serde(untagged)] pub enum RedsysResponse { RedsysResponse(RedsysTransaction), RedsysErrorResponse(RedsysErrorResponse), } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub struct RedsysErrorResponse { pub error_code: String, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum CardPSD2 { Y, N, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum ThreeDSCompInd { Y, N, } #[derive(Debug, Serialize, Deserialize)] pub struct RedsysPaymentsResponse { #[serde(rename = "Ds_Order")] ds_order: String, #[serde(rename = "Ds_EMV3DS")] ds_emv3ds: Option<RedsysEmv3DSData>, #[serde(rename = "Ds_Card_PSD2")] ds_card_psd2: Option<CardPSD2>, #[serde(rename = "Ds_Response")] ds_response: Option<DsResponse>, #[serde(rename = "Ds_AuthorisationCode")] ds_authorisation_code: Option<String>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct DsResponse(String); #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct RedsysEmv3DSData { protocol_version: String, three_d_s_server_trans_i_d: Option<String>, three_d_s_info: Option<RedsysThreeDsInfo>, three_d_s_method_u_r_l: Option<String>, acs_u_r_l: Option<String>, creq: Option<String>, } #[derive(Debug, Serialize, Deserialize)] #[serde(rename_all = "camelCase")] pub struct ThreedsInvokeRequest { three_d_s_server_trans_i_d: String, three_d_s_method_notification_u_r_l: String, } #[derive(Debug, Serialize, Deserialize)] pub struct RedsysThreeDsInvokeData { pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: String, pub directory_server_id: String, pub three_ds_method_data_submission: bool, } #[derive(Debug, Serialize, Deserialize)] pub struct ThreeDsInvokeExempt { pub three_d_s_server_trans_i_d: String, pub message_version: String, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct RedsysTransaction { #[serde(rename = "Ds_SignatureVersion")] ds_signature_version: String, #[serde(rename = "Ds_MerchantParameters")] ds_merchant_parameters: Secret<String>, #[serde(rename = "Ds_Signature")] ds_signature: Secret<String>, } fn to_connector_response_data<T>(connector_response: &str) -> Result<T, Error> where T: serde::de::DeserializeOwned, { let decoded_bytes = BASE64_ENGINE .decode(connector_response) .change_context(errors::ConnectorError::ResponseDeserializationFailed) .attach_printable("Failed to decode Base64")?; let response_data: T = serde_json::from_slice(&decoded_bytes) .change_context(errors::ConnectorError::ResponseHandlingFailed)?; Ok(response_data) } impl<F> TryFrom<ResponseRouterData<F, RedsysResponse, PaymentsPreProcessingData, PaymentsResponseData>> for RouterData<F, PaymentsPreProcessingData, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData< F, RedsysResponse, PaymentsPreProcessingData, PaymentsResponseData, >, ) -> Result<Self, Self::Error> { match item.response.clone() { RedsysResponse::RedsysResponse(response) => { let response_data: RedsysPaymentsResponse = to_connector_response_data(&response.ds_merchant_parameters.clone().expose())?; handle_redsys_preprocessing_response(item, &response_data) } RedsysResponse::RedsysErrorResponse(response) => { let response = Err(ErrorResponse { code: response.error_code.clone(), message: response.error_code.clone(), reason: Some(response.error_code.clone()), status_code: item.http_code, attempt_status: None, connector_transaction_id: None, network_advice_code: None, network_decline_code: None, network_error_message: None, connector_metadata: None, }); Ok(Self { status: enums::AttemptStatus::Failure, response, ..item.data }) } } } } fn handle_redsys_preprocessing_response<F>( item: ResponseRouterData<F, RedsysResponse, PaymentsPreProcessingData, PaymentsResponseData>, response_data: &RedsysPaymentsResponse, ) -> Result< RouterData<F, PaymentsPreProcessingData, PaymentsResponseData>, error_stack::Report<errors::ConnectorError>, > { match ( response_data .ds_emv3ds .as_ref() .and_then(|emv3ds_data| emv3ds_data.three_d_s_method_u_r_l.clone()), response_data .ds_emv3ds .as_ref() .and_then(|emv3ds_data| emv3ds_data.three_d_s_server_trans_i_d.clone()), response_data .ds_emv3ds .as_ref() .map(|emv3ds_data| emv3ds_data.protocol_version.clone()), ) { ( Some(three_d_s_method_u_r_l), Some(three_d_s_server_trans_i_d), Some(protocol_version), ) => handle_threeds_invoke( item, response_data, three_d_s_method_u_r_l, three_d_s_server_trans_i_d, protocol_version, ), (None, Some(three_d_s_server_trans_i_d), Some(protocol_version)) => { handle_threeds_invoke_exempt( item, response_data, three_d_s_server_trans_i_d, protocol_version, ) } _ => Err(errors::ConnectorError::NotSupported { message: "3DS payment with a non-3DS card".to_owned(), connector: "redsys", } .into()), } } fn handle_threeds_invoke<F>( item: ResponseRouterData<F, RedsysResponse, PaymentsPreProcessingData, PaymentsResponseData>, response_data: &RedsysPaymentsResponse, three_d_s_method_u_r_l: String, three_d_s_server_trans_i_d: String, protocol_version: String, ) -> Result< RouterData<F, PaymentsPreProcessingData, PaymentsResponseData>, error_stack::Report<errors::ConnectorError>, > { let three_d_s_method_notification_u_r_l = item.data.request.get_webhook_url()?; let threeds_invoke_data = ThreedsInvokeRequest { three_d_s_server_trans_i_d: three_d_s_method_u_r_l.clone(), three_d_s_method_notification_u_r_l, }; let three_ds_data_string = threeds_invoke_data .encode_to_string_of_json() .change_context(errors::ConnectorError::RequestEncodingFailed)?; let three_ds_method_data = BASE64_ENGINE.encode(&three_ds_data_string); let three_ds_data = RedsysThreeDsInvokeData { three_ds_method_url: three_d_s_method_u_r_l, three_ds_method_data, message_version: protocol_version.clone(), directory_server_id: three_d_s_server_trans_i_d, three_ds_method_data_submission: true, }; let connector_metadata = Some( serde_json::to_value(&three_ds_data) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to serialize ThreeDsData")?, ); Ok(RouterData { status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(response_data.ds_order.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some(response_data.ds_order.clone()), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } fn handle_threeds_invoke_exempt<F>( item: ResponseRouterData<F, RedsysResponse, PaymentsPreProcessingData, PaymentsResponseData>, response_data: &RedsysPaymentsResponse, three_d_s_server_trans_i_d: String, protocol_version: String, ) -> Result< RouterData<F, PaymentsPreProcessingData, PaymentsResponseData>, error_stack::Report<errors::ConnectorError>, > { let three_ds_data = ThreeDsInvokeExempt { message_version: protocol_version.clone(), three_d_s_server_trans_i_d, }; let connector_metadata = Some( serde_json::to_value(&three_ds_data) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to serialize ThreeDsData")?, ); Ok(RouterData { status: enums::AttemptStatus::AuthenticationPending, response: Ok(PaymentsResponseData::TransactionResponse { resource_id: ResponseId::ConnectorTransactionId(response_data.ds_order.clone()), redirection_data: Box::new(None), mandate_reference: Box::new(None), connector_metadata, network_txn_id: None, connector_response_reference_id: Some(response_data.ds_order.clone()), incremental_authorization_allowed: None, charges: None, }), ..item.data }) } fn des_encrypt( message: &str, key: &str, ) -> Result<Vec<u8>, error_stack::Report<errors::ConnectorError>> { // Connector decrypts the signature using an initialization vector (IV) set to all zeros let iv_array = [0u8; common_utils::crypto::TripleDesEde3CBC::TRIPLE_DES_IV_LENGTH]; let iv = iv_array.to_vec(); let key_bytes = BASE64_ENGINE .decode(key) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Base64 decoding failed")?; let triple_des = common_utils::crypto::TripleDesEde3CBC::new(Some(enums::CryptoPadding::ZeroPadding), iv) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Triple DES encryption failed")?; let encrypted = triple_des .encode_message(&key_bytes, message.as_bytes()) .change_context(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Triple DES encryption failed")?; let expected_len = encrypted.len() - common_utils::crypto::TripleDesEde3CBC::TRIPLE_DES_IV_LENGTH; let encrypted_trimmed = encrypted .get(..expected_len) .ok_or(errors::ConnectorError::RequestEncodingFailed) .attach_printable("Failed to trim encrypted data to the expected length")?; Ok(encrypted_trimmed.to_vec()) } fn get_signature( order_id: &str, params: &str, key: &str, ) -> Result<String, error_stack::Report<errors::ConnectorError>> { let secret_ko = des_encrypt(order_id, key)?; let result = common_utils::crypto::HmacSha256::sign_message( &common_utils::crypto::HmacSha256, &secret_ko, params.as_bytes(), ) .map_err(|_| errors::ConnectorError::RequestEncodingFailed)?; let encoded = BASE64_ENGINE.encode(result); Ok(encoded) } pub trait SignatureCalculationData { fn get_merchant_parameters(&self) -> Result<String, Error>; fn get_order_id(&self) -> String; } impl SignatureCalculationData for PaymentsRequest { fn get_merchant_parameters(&self) -> Result<String, Error> { self.encode_to_string_of_json() .change_context(errors::ConnectorError::RequestEncodingFailed) } fn get_order_id(&self) -> String { self.ds_merchant_order.clone() } } impl SignatureCalculationData for RedsysOperationRequest { fn get_merchant_parameters(&self) -> Result<String, Error> { self.encode_to_string_of_json() .change_context(errors::ConnectorError::RequestEncodingFailed) } fn get_order_id(&self) -> String { self.ds_merchant_order.clone() } } impl<T> TryFrom<(&T, &RedsysAuthType)> for RedsysTransaction where T: SignatureCalculationData, { type Error = Error; fn try_from(data: (&T, &RedsysAuthType)) -> Result<Self, Self::Error> { let (request_data, auth) = data; let merchant_parameters = request_data.get_merchant_parameters()?; let ds_merchant_parameters = BASE64_ENGINE.encode(&merchant_parameters); let sha256_pwd = auth.sha256_pwd.clone().expose(); let ds_merchant_order = request_data.get_order_id(); let signature = get_signature(&ds_merchant_order, &ds_merchant_parameters, &sha256_pwd)?; Ok(Self { ds_signature_version: SIGNATURE_VERSION.to_string(), ds_merchant_parameters: Secret::new(ds_merchant_parameters), ds_signature: Secret::new(signature), }) } } fn get_redsys_attempt_status( ds_response: DsResponse, capture_method: Option<enums::CaptureMethod>, ) -> Result<enums::AttemptStatus, error_stack::Report<errors::ConnectorError>> { // Redsys consistently provides a 4-digit response code, where numbers ranging from 0000 to 0099 indicate successful transactions if ds_response.0.starts_with("00") { match capture_method { Some(enums::CaptureMethod::Automatic) | None => Ok(enums::AttemptStatus::Charged), Some(enums::CaptureMethod::Manual) => Ok(enums::AttemptStatus::Authorized), _ => Err(errors::ConnectorError::CaptureMethodNotSupported.into()), } } else { match ds_response.0.as_str() { "0900" => Ok(enums::AttemptStatus::Charged), "0400" => Ok(enums::AttemptStatus::Voided), "0950" => Ok(enums::AttemptStatus::VoidFailed), "9998" => Ok(enums::AttemptStatus::AuthenticationPending), "9256" | "9257" | "0184" => Ok(enums::AttemptStatus::AuthenticationFailed), "0101" | "0102" | "0106" | "0125" | "0129" | "0172" | "0173" | "0174" | "0180" | "0190" | "0191" | "0195" | "0202" | "0904" | "0909" | "0913" | "0944" | "9912" | "0912" | "9064" | "9078" | "9093" | "9094" | "9104" | "9218" | "9253" | "9261"
crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs#chunk0
hyperswitch_connectors
chunk
null
null
null
8,173
null
null
null
null
null
null
null
// Struct: FrmFulfillmentResponse // File: crates/router/src/core/fraud_check/types.rs // Module: router // Implementations: 0 pub struct FrmFulfillmentResponse
crates/router/src/core/fraud_check/types.rs
router
struct_definition
FrmFulfillmentResponse
0
[]
41
null
null
null
null
null
null
null
// Struct: RelayWebhooks // File: crates/router/src/routes/app.rs // Module: router // Implementations: 1 pub struct RelayWebhooks
crates/router/src/routes/app.rs
router
struct_definition
RelayWebhooks
1
[]
34
null
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/opennode/transformers.rs // Module: hyperswitch_connectors // Public structs: 9 use std::collections::HashMap; use common_enums::{enums, AttemptStatus}; use common_utils::{request::Method, types::MinorUnit}; use hyperswitch_domain_models::{ router_data::{ConnectorAuthType, RouterData}, router_flow_types::refunds::{Execute, RSync}, router_request_types::ResponseId, router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData}, types::{PaymentsAuthorizeRouterData, RefundsRouterData}, }; use hyperswitch_interfaces::errors; use masking::Secret; use serde::{Deserialize, Serialize}; use crate::{ types::{RefundsResponseRouterData, ResponseRouterData}, utils::{PaymentsAuthorizeRequestData, RouterData as OtherRouterData}, }; #[derive(Debug, Serialize)] pub struct OpennodeRouterData<T> { pub amount: MinorUnit, pub router_data: T, } impl<T> TryFrom<(MinorUnit, T)> for OpennodeRouterData<T> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from((amount, router_data): (MinorUnit, T)) -> Result<Self, Self::Error> { Ok(Self { amount, router_data, }) } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Serialize, Eq, PartialEq)] pub struct OpennodePaymentsRequest { amount: MinorUnit, currency: String, description: String, auto_settle: bool, success_url: String, callback_url: String, order_id: String, } impl TryFrom<&OpennodeRouterData<&PaymentsAuthorizeRouterData>> for OpennodePaymentsRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: &OpennodeRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<Self, Self::Error> { get_crypto_specific_payment_data(item) } } //TODO: Fill the struct with respective fields // Auth Struct pub struct OpennodeAuthType { pub(super) api_key: Secret<String>, } impl TryFrom<&ConnectorAuthType> for OpennodeAuthType { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> { match auth_type { ConnectorAuthType::HeaderKey { api_key } => Ok(Self { api_key: api_key.to_owned(), }), _ => Err(errors::ConnectorError::FailedToObtainAuthType.into()), } } } // PaymentsResponse //TODO: Append the remaining status flags #[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)] #[serde(rename_all = "lowercase")] pub enum OpennodePaymentStatus { Unpaid, Paid, Expired, #[default] Processing, Underpaid, Refunded, #[serde(other)] Unknown, } impl From<OpennodePaymentStatus> for AttemptStatus { fn from(item: OpennodePaymentStatus) -> Self { match item { OpennodePaymentStatus::Unpaid => Self::AuthenticationPending, OpennodePaymentStatus::Paid => Self::Charged, OpennodePaymentStatus::Expired => Self::Failure, OpennodePaymentStatus::Underpaid => Self::Unresolved, _ => Self::Pending, } } } #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct OpennodePaymentsResponseData { id: String, hosted_checkout_url: String, status: OpennodePaymentStatus, order_id: Option<String>, } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct OpennodePaymentsResponse { data: OpennodePaymentsResponseData, } impl<F, T> TryFrom<ResponseRouterData<F, OpennodePaymentsResponse, T, PaymentsResponseData>> for RouterData<F, T, PaymentsResponseData> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: ResponseRouterData<F, OpennodePaymentsResponse, T, PaymentsResponseData>, ) -> Result<Self, Self::Error> { let form_fields = HashMap::new(); let redirection_data = RedirectForm::Form { endpoint: item.response.data.hosted_checkout_url.to_string(), method: Method::Get, form_fields, }; let connector_id = ResponseId::ConnectorTransactionId(item.response.data.id); let attempt_status = item.response.data.status; let response_data = if attempt_status != OpennodePaymentStatus::Underpaid { Ok(PaymentsResponseData::TransactionResponse { resource_id: connector_id, redirection_data: Box::new(Some(redirection_data)), mandate_reference: Box::new(None), connector_metadata: None, network_txn_id: None, connector_response_reference_id: item.response.data.order_id, incremental_authorization_allowed: None, charges: None, }) } else { Ok(PaymentsResponseData::TransactionUnresolvedResponse { resource_id: connector_id, reason: Some(api_models::enums::UnresolvedResponseReason { code: "UNDERPAID".to_string(), message: "Please check the transaction in opennode dashboard and resolve manually" .to_string(), }), connector_response_reference_id: item.response.data.order_id, }) }; Ok(Self { status: AttemptStatus::from(attempt_status), response: response_data, ..item.data }) } } //TODO: Fill the struct with respective fields // REFUND : // Type definition for RefundRequest #[derive(Default, Debug, Serialize)] pub struct OpennodeRefundRequest { pub amount: i64, } impl<F> TryFrom<&OpennodeRouterData<&RefundsRouterData<F>>> for OpennodeRefundRequest { type Error = error_stack::Report<errors::ConnectorError>; fn try_from(item: &OpennodeRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> { Ok(Self { amount: item.router_data.request.refund_amount, }) } } // Type definition for Refund Response #[allow(dead_code)] #[derive(Debug, Serialize, Default, Deserialize, Clone)] pub enum RefundStatus { Refunded, #[default] Processing, } impl From<RefundStatus> for enums::RefundStatus { fn from(item: RefundStatus) -> Self { match item { RefundStatus::Refunded => Self::Success, RefundStatus::Processing => Self::Pending, } } } //TODO: Fill the struct with respective fields #[derive(Default, Debug, Clone, Serialize, Deserialize)] pub struct RefundResponse { id: String, status: RefundStatus, } impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<Execute, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } impl TryFrom<RefundsResponseRouterData<RSync, RefundResponse>> for RefundsRouterData<RSync> { type Error = error_stack::Report<errors::ConnectorError>; fn try_from( item: RefundsResponseRouterData<RSync, RefundResponse>, ) -> Result<Self, Self::Error> { Ok(Self { response: Ok(RefundsResponseData { connector_refund_id: item.response.id.to_string(), refund_status: enums::RefundStatus::from(item.response.status), }), ..item.data }) } } //TODO: Fill the struct with respective fields #[derive(Debug, Deserialize, Serialize)] pub struct OpennodeErrorResponse { pub message: String, } fn get_crypto_specific_payment_data( item: &OpennodeRouterData<&PaymentsAuthorizeRouterData>, ) -> Result<OpennodePaymentsRequest, error_stack::Report<errors::ConnectorError>> { let amount = item.amount; let currency = item.router_data.request.currency.to_string(); let description = item.router_data.get_description()?; let auto_settle = true; let success_url = item.router_data.request.get_router_return_url()?; let callback_url = item.router_data.request.get_webhook_url()?; let order_id = item.router_data.connector_request_reference_id.clone(); Ok(OpennodePaymentsRequest { amount, currency, description, auto_settle, success_url, callback_url, order_id, }) } #[derive(Debug, Serialize, Deserialize)] pub struct OpennodeWebhookDetails { pub id: String, pub callback_url: String, pub success_url: String, pub status: OpennodePaymentStatus, pub payment_method: String, pub missing_amt: String, pub order_id: String, pub description: String, pub price: String, pub fee: String, pub auto_settle: String, pub fiat_value: String, pub net_fiat_value: String, pub overpaid_by: String, pub hashed_order: String, }
crates/hyperswitch_connectors/src/connectors/opennode/transformers.rs
hyperswitch_connectors
full_file
null
null
null
2,070
null
null
null
null
null
null
null
// Struct: BokuAuthType // File: crates/hyperswitch_connectors/src/connectors/boku/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BokuAuthType
crates/hyperswitch_connectors/src/connectors/boku/transformers.rs
hyperswitch_connectors
struct_definition
BokuAuthType
0
[]
49
null
null
null
null
null
null
null
// Function: get_order_status // File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs // Module: hyperswitch_connectors pub fn get_order_status( item: PaypalOrderStatus, intent: PaypalPaymentIntent, ) -> storage_enums::AttemptStatus
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
hyperswitch_connectors
function_signature
null
null
null
63
get_order_status
null
null
null
null
null
null
// Function: get_basic_auth_header // File: crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs // Module: hyperswitch_connectors pub fn get_basic_auth_header(&self) -> String
crates/hyperswitch_connectors/src/connectors/trustpayments/transformers.rs
hyperswitch_connectors
function_signature
null
null
null
48
get_basic_auth_header
null
null
null
null
null
null
// File: crates/payment_methods/src/configs.rs // Module: payment_methods pub mod payment_connector_required_fields; pub mod settings;
crates/payment_methods/src/configs.rs
payment_methods
full_file
null
null
null
28
null
null
null
null
null
null
null
// File: crates/hyperswitch_connectors/src/connectors/blackhawknetwork.rs // Module: hyperswitch_connectors // Public functions: 1 // Public structs: 1 pub mod transformers; use std::sync::LazyLock; use common_enums::{enums, enums::PaymentMethodType}; 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::{ 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, }, router_response_types::{ ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods, SupportedPaymentMethodsExt, }, types::{ PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsPreProcessingRouterData, PaymentsSyncRouterData, RefreshTokenRouterData, RefundSyncRouterData, RefundsRouterData, }, }; use hyperswitch_interfaces::{ api::{ self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications, ConnectorValidation, }, configs::Connectors, consts::NO_ERROR_MESSAGE, errors, events::connector_api_logs::ConnectorEvent, types::{self, Response}, webhooks, }; use masking::Maskable; use transformers as blackhawknetwork; use crate::{constants::headers, types::ResponseRouterData, utils}; #[derive(Clone)] pub struct Blackhawknetwork { amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync), } impl Blackhawknetwork { pub fn new() -> &'static Self { &Self { amount_converter: &StringMajorUnitForConnector, } } } impl api::Payment for Blackhawknetwork {} impl api::PaymentSession for Blackhawknetwork {} impl api::ConnectorAccessToken for Blackhawknetwork {} impl api::MandateSetup for Blackhawknetwork {} impl api::PaymentAuthorize for Blackhawknetwork {} impl api::PaymentSync for Blackhawknetwork {} impl api::PaymentCapture for Blackhawknetwork {} impl api::PaymentVoid for Blackhawknetwork {} impl api::Refund for Blackhawknetwork {} impl api::RefundExecute for Blackhawknetwork {} impl api::RefundSync for Blackhawknetwork {} impl api::PaymentToken for Blackhawknetwork {} impl api::PaymentsPreProcessing for Blackhawknetwork {} impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Blackhawknetwork { fn get_headers( &self, _req: &RefreshTokenRouterData, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(vec![( headers::CONTENT_TYPE.to_string(), "application/x-www-form-urlencoded".to_string().into(), )]) } 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!( "{}/realms/dev-experience/protocol/openid-connect/token", self.base_url(connectors) )) } fn get_request_body( &self, req: &RefreshTokenRouterData, _connectors: &Connectors, ) -> CustomResult<RequestContent, errors::ConnectorError> { let auth = blackhawknetwork::BlackhawknetworkAuthType::try_from(&req.connector_auth_type)?; let connector_req = blackhawknetwork::BlackhawknetworkAccessTokenRequest { grant_type: "client_credentials".to_string(), client_id: auth.client_id.clone(), client_secret: auth.client_secret.clone(), scope: "openid".to_string(), }; Ok(RequestContent::FormUrlEncoded(Box::new(connector_req))) } fn build_request( &self, req: &RefreshTokenRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { let request = RequestBuilder::new() .method(Method::Post) .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(Some(request)) } fn handle_response( &self, data: &RefreshTokenRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<RefreshTokenRouterData, errors::ConnectorError> { let response: blackhawknetwork::BlackhawknetworkTokenResponse = res .response .parse_struct("BlackhawknetworkTokenResponse") .or_else(|_| res.response.parse_struct("BlackhawknetworkErrorResponse")) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.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<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData> for Blackhawknetwork { // Not Implemented (R) } impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Blackhawknetwork 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 Blackhawknetwork { fn id(&self) -> &'static str { "blackhawknetwork" } 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.blackhawknetwork.base_url.as_ref() } fn get_auth_header( &self, _auth_type: &ConnectorAuthType, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { Ok(vec![]) } fn build_error_response( &self, res: Response, event_builder: Option<&mut ConnectorEvent>, ) -> CustomResult<ErrorResponse, errors::ConnectorError> { let response: blackhawknetwork::BlackhawknetworkErrorResponse = res .response .parse_struct("BlackhawknetworkErrorResponse") .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, message: response .error_description .clone() .unwrap_or(NO_ERROR_MESSAGE.to_owned()), reason: 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 Blackhawknetwork { 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 Blackhawknetwork { //TODO: implement sessions flow } impl ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData> for Blackhawknetwork { fn get_headers( &self, req: &PaymentsPreProcessingRouterData, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let mut headers = vec![( headers::CONTENT_TYPE.to_string(), "application/x-www-form-urlencoded".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: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { let base_url = self.base_url(connectors); let connector_req = blackhawknetwork::BlackhawknetworkVerifyAccountRequest::try_from(req)?; let query = serde_urlencoded::to_string(&connector_req) .change_context(errors::ConnectorError::RequestEncodingFailed)?; Ok(format!( "{base_url}/accountProcessing/v1/verifyAccount?{query}" )) } fn build_request( &self, req: &PaymentsPreProcessingRouterData, connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Ok(Some( RequestBuilder::new() .method(Method::Get) .url(&types::PaymentsPreProcessingType::get_url( self, req, connectors, )?) .attach_default_headers() .headers(types::PaymentsPreProcessingType::get_headers( self, req, connectors, )?) .build(), )) } fn handle_response( &self, data: &PaymentsPreProcessingRouterData, event_builder: Option<&mut ConnectorEvent>, res: Response, ) -> CustomResult<PaymentsPreProcessingRouterData, errors::ConnectorError> { let response: blackhawknetwork::BlackhawknetworkVerifyAccountResponse = res .response .parse_struct("BlackhawknetworkVerifyAccountResponse") .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.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<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Blackhawknetwork { } impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Blackhawknetwork { fn get_headers( &self, req: &PaymentsAuthorizeRouterData, _connectors: &Connectors, ) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> { let mut headers = vec![( headers::CONTENT_TYPE.to_string(), "application/json".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/json" } fn get_url( &self, _req: &PaymentsAuthorizeRouterData, connectors: &Connectors, ) -> CustomResult<String, errors::ConnectorError> { Ok(format!( "{}/accountProcessing/v1/redeem", 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 = blackhawknetwork::BlackhawknetworkRouterData::from((amount, req)); let connector_req = blackhawknetwork::BlackhawknetworkPaymentsRequest::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: blackhawknetwork::BlackhawknetworkRedeemResponse = res .response .parse_struct("BlackhawknetworkRedeemResponse") .or_else(|_| res.response.parse_struct("BlackhawknetworkErrorResponse")) .change_context(errors::ConnectorError::ResponseDeserializationFailed)?; event_builder.map(|i| i.set_response_body(&response)); router_env::logger::info!(connector_response=?response); RouterData::try_from(ResponseRouterData { response, 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: blackhawknetwork::BlackhawknetworkErrorResponse = res .response .parse_struct("BlackhawknetworkErrorResponse") .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, message: response .error_description .unwrap_or(NO_ERROR_MESSAGE.to_owned()), reason: Some("Verify redemption details or contact BHN support".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 Blackhawknetwork { fn build_request( &self, _req: &PaymentsSyncRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Payments Sync".to_string(), connector: "BlackHawkNetwork".to_string(), } .into()) } } impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Blackhawknetwork { fn build_request( &self, _req: &PaymentsCaptureRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Capture".to_string(), connector: "BlackHawkNetwork".to_string(), } .into()) } } impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Blackhawknetwork {} impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Blackhawknetwork { fn build_request( &self, _req: &RefundsRouterData<Execute>, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Refunds".to_string(), connector: "BlackHawkNetwork".to_string(), } .into()) } } impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Blackhawknetwork { fn build_request( &self, _req: &RefundSyncRouterData, _connectors: &Connectors, ) -> CustomResult<Option<Request>, errors::ConnectorError> { Err(errors::ConnectorError::FlowNotSupported { flow: "Refunds Sync".to_string(), connector: "BlackHawkNetwork".to_string(), } .into()) } } #[async_trait::async_trait] impl webhooks::IncomingWebhook for Blackhawknetwork { 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 BLACKHAWKNETWORK_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo { display_name: "Blackhawknetwork", description: "Blackhawknetwork connector", connector_type: enums::HyperswitchConnectorCategory::PaymentGateway, integration_status: enums::ConnectorIntegrationStatus::Alpha, }; static BLACKHAWKNETWORK_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 0] = []; static BLACKHAWKNETWORK_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| { let supported_capture_methods = vec![enums::CaptureMethod::Automatic]; let mut supported_payment_methods = SupportedPaymentMethods::new(); supported_payment_methods.add( enums::PaymentMethod::GiftCard, PaymentMethodType::BhnCardNetwork, PaymentMethodDetails { mandates: enums::FeatureStatus::NotSupported, refunds: enums::FeatureStatus::NotSupported, supported_capture_methods: supported_capture_methods.clone(), specific_features: None, }, ); supported_payment_methods }); impl ConnectorSpecifications for Blackhawknetwork { fn get_connector_about(&self) -> Option<&'static ConnectorInfo> { Some(&BLACKHAWKNETWORK_CONNECTOR_INFO) } fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> { Some(&*BLACKHAWKNETWORK_SUPPORTED_PAYMENT_METHODS) } fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> { Some(&BLACKHAWKNETWORK_SUPPORTED_WEBHOOK_FLOWS) } }
crates/hyperswitch_connectors/src/connectors/blackhawknetwork.rs
hyperswitch_connectors
full_file
null
null
null
4,463
null
null
null
null
null
null
null
// Function: get_profile_routing_events // File: crates/router/src/analytics.rs // Module: router pub fn get_profile_routing_events( state: web::Data<AppState>, req: actix_web::HttpRequest, json_payload: web::Query<api_models::analytics::routing_events::RoutingEventsRequest>, ) -> impl Responder
crates/router/src/analytics.rs
router
function_signature
null
null
null
74
get_profile_routing_events
null
null
null
null
null
null
// Implementation: impl api::PaymentAuthorize for for Payme // File: crates/hyperswitch_connectors/src/connectors/payme.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentAuthorize for for Payme
crates/hyperswitch_connectors/src/connectors/payme.rs
hyperswitch_connectors
impl_block
null
null
null
57
null
Payme
api::PaymentAuthorize for
0
0
null
null
// Function: collect // File: crates/analytics/src/active_payments/accumulator.rs // Module: analytics pub fn collect(self) -> ActivePaymentsMetricsBucketValue
crates/analytics/src/active_payments/accumulator.rs
analytics
function_signature
null
null
null
35
collect
null
null
null
null
null
null
// Struct: GenericLink // File: crates/diesel_models/src/generic_link.rs // Module: diesel_models // Implementations: 0 pub struct GenericLink
crates/diesel_models/src/generic_link.rs
diesel_models
struct_definition
GenericLink
0
[]
36
null
null
null
null
null
null
null
// Module Structure // File: crates/diesel_models/src/query/user.rs // Module: diesel_models // Public submodules: pub mod sample_data; pub mod theme;
crates/diesel_models/src/query/user.rs
diesel_models
module_structure
null
null
null
36
null
null
null
null
null
2
0
// File: crates/api_models/src/open_router.rs // Module: api_models // Public functions: 6 // Public structs: 23 use std::{collections::HashMap, fmt::Debug}; use common_utils::{errors, id_type, types::MinorUnit}; pub use euclid::{ dssa::types::EuclidAnalysable, frontend::{ ast, dir::{DirKeyKind, EuclidDirFilter}, }, }; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::{ enums::{Currency, PaymentMethod}, payment_methods, }; #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct OpenRouterDecideGatewayRequest { pub payment_info: PaymentInfo, #[schema(value_type = String)] pub merchant_id: id_type::ProfileId, pub eligible_gateway_list: Option<Vec<String>>, pub ranking_algorithm: Option<RankingAlgorithm>, pub elimination_enabled: Option<bool>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct DecideGatewayResponse { pub decided_gateway: Option<String>, pub gateway_priority_map: Option<serde_json::Value>, pub filter_wise_gateways: Option<serde_json::Value>, pub priority_logic_tag: Option<String>, pub routing_approach: Option<String>, pub gateway_before_evaluation: Option<String>, pub priority_logic_output: Option<PriorityLogicOutput>, pub reset_approach: Option<String>, pub routing_dimension: Option<String>, pub routing_dimension_level: Option<String>, pub is_scheduled_outage: Option<bool>, pub is_dynamic_mga_enabled: Option<bool>, pub gateway_mga_id_map: Option<serde_json::Value>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct PriorityLogicOutput { pub is_enforcement: Option<bool>, pub gws: Option<Vec<String>>, pub priority_logic_tag: Option<String>, pub gateway_reference_ids: Option<HashMap<String, String>>, pub primary_logic: Option<PriorityLogicData>, pub fallback_logic: Option<PriorityLogicData>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PriorityLogicData { pub name: Option<String>, pub status: Option<String>, pub failure_reason: Option<String>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum RankingAlgorithm { SrBasedRouting, PlBasedRouting, NtwBasedRouting, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct PaymentInfo { #[schema(value_type = String)] pub payment_id: id_type::PaymentId, pub amount: MinorUnit, pub currency: Currency, // customerId: Option<ETCu::CustomerId>, // preferredGateway: Option<ETG::Gateway>, pub payment_type: String, pub metadata: Option<String>, // internalMetadata: Option<String>, // isEmi: Option<bool>, // emiBank: Option<String>, // emiTenure: Option<i32>, pub payment_method_type: String, pub payment_method: PaymentMethod, // paymentSource: Option<String>, // authType: Option<ETCa::txn_card_info::AuthType>, // cardIssuerBankName: Option<String>, pub card_isin: Option<String>, // cardType: Option<ETCa::card_type::CardType>, // cardSwitchProvider: Option<Secret<String>>, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct DecidedGateway { pub gateway_priority_map: Option<HashMap<String, f64>>, pub debit_routing_output: Option<DebitRoutingOutput>, pub routing_approach: String, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct DebitRoutingOutput { pub co_badged_card_networks_info: CoBadgedCardNetworks, pub issuer_country: common_enums::CountryAlpha2, pub is_regulated: bool, pub regulated_name: Option<common_enums::RegulatedName>, pub card_type: common_enums::CardType, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct CoBadgedCardNetworksInfo { pub network: common_enums::CardNetwork, pub saving_percentage: f64, } #[derive(Debug, Serialize, Deserialize, PartialEq, Clone)] pub struct CoBadgedCardNetworks(pub Vec<CoBadgedCardNetworksInfo>); impl CoBadgedCardNetworks { pub fn get_card_networks(&self) -> Vec<common_enums::CardNetwork> { self.0.iter().map(|info| info.network.clone()).collect() } pub fn get_signature_network(&self) -> Option<common_enums::CardNetwork> { self.0 .iter() .find(|info| info.network.is_signature_network()) .map(|info| info.network.clone()) } } impl From<&DebitRoutingOutput> for payment_methods::CoBadgedCardData { fn from(output: &DebitRoutingOutput) -> Self { Self { co_badged_card_networks_info: output.co_badged_card_networks_info.clone(), issuer_country_code: output.issuer_country, is_regulated: output.is_regulated, regulated_name: output.regulated_name.clone(), } } } impl TryFrom<(payment_methods::CoBadgedCardData, String)> for DebitRoutingRequestData { type Error = error_stack::Report<errors::ParsingError>; fn try_from( (output, card_type): (payment_methods::CoBadgedCardData, String), ) -> Result<Self, Self::Error> { let parsed_card_type = card_type.parse::<common_enums::CardType>().map_err(|_| { error_stack::Report::new(errors::ParsingError::EnumParseFailure("CardType")) })?; Ok(Self { co_badged_card_networks_info: output.co_badged_card_networks_info.get_card_networks(), issuer_country: output.issuer_country_code, is_regulated: output.is_regulated, regulated_name: output.regulated_name, card_type: parsed_card_type, }) } } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct CoBadgedCardRequest { pub merchant_category_code: common_enums::DecisionEngineMerchantCategoryCode, pub acquirer_country: common_enums::CountryAlpha2, pub co_badged_card_data: Option<DebitRoutingRequestData>, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq)] pub struct DebitRoutingRequestData { pub co_badged_card_networks_info: Vec<common_enums::CardNetwork>, pub issuer_country: common_enums::CountryAlpha2, pub is_regulated: bool, pub regulated_name: Option<common_enums::RegulatedName>, pub card_type: common_enums::CardType, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct ErrorResponse { pub status: String, pub error_code: String, pub error_message: String, pub priority_logic_tag: Option<String>, pub filter_wise_gateways: Option<serde_json::Value>, pub error_info: UnifiedError, pub is_dynamic_mga_enabled: bool, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct UnifiedError { pub code: String, pub user_message: String, pub developer_message: String, } #[derive(Debug, Clone, Serialize, Deserialize, PartialEq, ToSchema)] #[serde(rename_all = "camelCase")] pub struct UpdateScorePayload { #[schema(value_type = String)] pub merchant_id: id_type::ProfileId, pub gateway: String, pub status: TxnStatus, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] pub struct UpdateScoreResponse { pub message: String, } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum TxnStatus { Started, AuthenticationFailed, JuspayDeclined, PendingVbv, VBVSuccessful, Authorized, AuthorizationFailed, Charged, Authorizing, CODInitiated, Voided, VoidedPostCharge, VoidInitiated, Nop, CaptureInitiated, CaptureFailed, VoidFailed, AutoRefunded, PartialCharged, ToBeCharged, Pending, Failure, Declined, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct DecisionEngineConfigSetupRequest { pub merchant_id: String, pub config: DecisionEngineConfigVariant, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct GetDecisionEngineConfigRequest { pub merchant_id: String, pub algorithm: DecisionEngineDynamicAlgorithmType, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(rename_all = "camelCase")] pub enum DecisionEngineDynamicAlgorithmType { SuccessRate, Elimination, } #[derive(Debug, Serialize, Deserialize, Clone)] #[serde(tag = "type", content = "data")] #[serde(rename_all = "camelCase")] pub enum DecisionEngineConfigVariant { SuccessRate(DecisionEngineSuccessRateData), Elimination(DecisionEngineEliminationData), } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineSuccessRateData { pub default_latency_threshold: Option<f64>, pub default_bucket_size: Option<i32>, pub default_hedging_percent: Option<f64>, pub default_lower_reset_factor: Option<f64>, pub default_upper_reset_factor: Option<f64>, pub default_gateway_extra_score: Option<Vec<DecisionEngineGatewayWiseExtraScore>>, pub sub_level_input_config: Option<Vec<DecisionEngineSRSubLevelInputConfig>>, } impl DecisionEngineSuccessRateData { pub fn update(&mut self, new_config: Self) { if let Some(threshold) = new_config.default_latency_threshold { self.default_latency_threshold = Some(threshold); } if let Some(bucket_size) = new_config.default_bucket_size { self.default_bucket_size = Some(bucket_size); } if let Some(hedging_percent) = new_config.default_hedging_percent { self.default_hedging_percent = Some(hedging_percent); } if let Some(lower_reset_factor) = new_config.default_lower_reset_factor { self.default_lower_reset_factor = Some(lower_reset_factor); } if let Some(upper_reset_factor) = new_config.default_upper_reset_factor { self.default_upper_reset_factor = Some(upper_reset_factor); } if let Some(gateway_extra_score) = new_config.default_gateway_extra_score { self.default_gateway_extra_score .as_mut() .map(|score| score.extend(gateway_extra_score)); } if let Some(sub_level_input_config) = new_config.sub_level_input_config { self.sub_level_input_config.as_mut().map(|config| { config.extend(sub_level_input_config); }); } } } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineSRSubLevelInputConfig { pub payment_method_type: Option<String>, pub payment_method: Option<String>, pub latency_threshold: Option<f64>, pub bucket_size: Option<i32>, pub hedging_percent: Option<f64>, pub lower_reset_factor: Option<f64>, pub upper_reset_factor: Option<f64>, pub gateway_extra_score: Option<Vec<DecisionEngineGatewayWiseExtraScore>>, } impl DecisionEngineSRSubLevelInputConfig { pub fn update(&mut self, new_config: Self) { if let Some(payment_method_type) = new_config.payment_method_type { self.payment_method_type = Some(payment_method_type); } if let Some(payment_method) = new_config.payment_method { self.payment_method = Some(payment_method); } if let Some(latency_threshold) = new_config.latency_threshold { self.latency_threshold = Some(latency_threshold); } if let Some(bucket_size) = new_config.bucket_size { self.bucket_size = Some(bucket_size); } if let Some(hedging_percent) = new_config.hedging_percent { self.hedging_percent = Some(hedging_percent); } if let Some(lower_reset_factor) = new_config.lower_reset_factor { self.lower_reset_factor = Some(lower_reset_factor); } if let Some(upper_reset_factor) = new_config.upper_reset_factor { self.upper_reset_factor = Some(upper_reset_factor); } if let Some(gateway_extra_score) = new_config.gateway_extra_score { self.gateway_extra_score .as_mut() .map(|score| score.extend(gateway_extra_score)); } } } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineGatewayWiseExtraScore { pub gateway_name: String, pub gateway_sigma_factor: f64, } impl DecisionEngineGatewayWiseExtraScore { pub fn update(&mut self, new_config: Self) { self.gateway_name = new_config.gateway_name; self.gateway_sigma_factor = new_config.gateway_sigma_factor; } } #[derive(Debug, Serialize, Deserialize, Clone, ToSchema)] #[serde(rename_all = "camelCase")] pub struct DecisionEngineEliminationData { pub threshold: f64, } impl DecisionEngineEliminationData { pub fn update(&mut self, new_config: Self) { self.threshold = new_config.threshold; } } #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] pub struct MerchantAccount { pub merchant_id: String, pub gateway_success_rate_based_decider_input: Option<String>, } #[derive(Debug, Serialize, Deserialize, Clone)] pub struct FetchRoutingConfig { pub merchant_id: String, pub algorithm: AlgorithmType, } #[derive(Debug, Serialize, Deserialize, Clone, Copy)] #[serde(rename_all = "camelCase")] pub enum AlgorithmType { SuccessRate, Elimination, DebitRouting, }
crates/api_models/src/open_router.rs
api_models
full_file
null
null
null
3,088
null
null
null
null
null
null
null
// Struct: PaymentsDslInput // File: crates/router/src/core/routing.rs // Module: router // Implementations: 1 pub struct PaymentsDslInput<'a>
crates/router/src/core/routing.rs
router
struct_definition
PaymentsDslInput
1
[]
40
null
null
null
null
null
null
null
// File: crates/router_derive/src/macros/api_error/helpers.rs // Module: router_derive use proc_macro2::TokenStream; use quote::ToTokens; use syn::{ parse::Parse, spanned::Spanned, DeriveInput, Field, Fields, LitStr, Token, TypePath, Variant, }; use crate::macros::helpers::{get_metadata_inner, occurrence_error}; mod keyword { use syn::custom_keyword; // Enum metadata custom_keyword!(error_type_enum); // Variant metadata custom_keyword!(error_type); custom_keyword!(code); custom_keyword!(message); custom_keyword!(ignore); } enum EnumMeta { ErrorTypeEnum { keyword: keyword::error_type_enum, value: TypePath, }, } impl Parse for EnumMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(keyword::error_type_enum) { let keyword = input.parse()?; input.parse::<Token![=]>()?; let value = input.parse()?; Ok(Self::ErrorTypeEnum { keyword, value }) } else { Err(lookahead.error()) } } } impl ToTokens for EnumMeta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::ErrorTypeEnum { keyword, .. } => keyword.to_tokens(tokens), } } } trait DeriveInputExt { /// Get all the error metadata associated with an enum. fn get_metadata(&self) -> syn::Result<Vec<EnumMeta>>; } impl DeriveInputExt for DeriveInput { fn get_metadata(&self) -> syn::Result<Vec<EnumMeta>> { get_metadata_inner("error", &self.attrs) } } pub(super) trait HasErrorTypeProperties { fn get_type_properties(&self) -> syn::Result<ErrorTypeProperties>; } #[derive(Clone, Debug, Default)] pub(super) struct ErrorTypeProperties { pub error_type_enum: Option<TypePath>, } impl HasErrorTypeProperties for DeriveInput { fn get_type_properties(&self) -> syn::Result<ErrorTypeProperties> { let mut output = ErrorTypeProperties::default(); let mut error_type_enum_keyword = None; for meta in self.get_metadata()? { match meta { EnumMeta::ErrorTypeEnum { keyword, value } => { if let Some(first_keyword) = error_type_enum_keyword { return Err(occurrence_error(first_keyword, keyword, "error_type_enum")); } error_type_enum_keyword = Some(keyword); output.error_type_enum = Some(value); } } } if output.error_type_enum.is_none() { return Err(syn::Error::new( self.span(), "error(error_type_enum) attribute not found", )); } Ok(output) } } enum VariantMeta { ErrorType { keyword: keyword::error_type, value: TypePath, }, Code { keyword: keyword::code, value: LitStr, }, Message { keyword: keyword::message, value: LitStr, }, Ignore { keyword: keyword::ignore, value: LitStr, }, } impl Parse for VariantMeta { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(keyword::error_type) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::ErrorType { keyword, value }) } else if lookahead.peek(keyword::code) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::Code { keyword, value }) } else if lookahead.peek(keyword::message) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::Message { keyword, value }) } else if lookahead.peek(keyword::ignore) { let keyword = input.parse()?; let _: Token![=] = input.parse()?; let value = input.parse()?; Ok(Self::Ignore { keyword, value }) } else { Err(lookahead.error()) } } } impl ToTokens for VariantMeta { fn to_tokens(&self, tokens: &mut TokenStream) { match self { Self::ErrorType { keyword, .. } => keyword.to_tokens(tokens), Self::Code { keyword, .. } => keyword.to_tokens(tokens), Self::Message { keyword, .. } => keyword.to_tokens(tokens), Self::Ignore { keyword, .. } => keyword.to_tokens(tokens), } } } trait VariantExt { /// Get all the error metadata associated with an enum variant. fn get_metadata(&self) -> syn::Result<Vec<VariantMeta>>; } impl VariantExt for Variant { fn get_metadata(&self) -> syn::Result<Vec<VariantMeta>> { get_metadata_inner("error", &self.attrs) } } pub(super) trait HasErrorVariantProperties { fn get_variant_properties(&self) -> syn::Result<ErrorVariantProperties>; } #[derive(Clone, Debug, Default, Eq, PartialEq)] pub(super) struct ErrorVariantProperties { pub error_type: Option<TypePath>, pub code: Option<LitStr>, pub message: Option<LitStr>, pub ignore: std::collections::HashSet<String>, } impl HasErrorVariantProperties for Variant { fn get_variant_properties(&self) -> syn::Result<ErrorVariantProperties> { let mut output = ErrorVariantProperties::default(); let mut error_type_keyword = None; let mut code_keyword = None; let mut message_keyword = None; let mut ignore_keyword = None; for meta in self.get_metadata()? { match meta { VariantMeta::ErrorType { keyword, value } => { if let Some(first_keyword) = error_type_keyword { return Err(occurrence_error(first_keyword, keyword, "error_type")); } error_type_keyword = Some(keyword); output.error_type = Some(value); } VariantMeta::Code { keyword, value } => { if let Some(first_keyword) = code_keyword { return Err(occurrence_error(first_keyword, keyword, "code")); } code_keyword = Some(keyword); output.code = Some(value); } VariantMeta::Message { keyword, value } => { if let Some(first_keyword) = message_keyword { return Err(occurrence_error(first_keyword, keyword, "message")); } message_keyword = Some(keyword); output.message = Some(value); } VariantMeta::Ignore { keyword, value } => { if let Some(first_keyword) = ignore_keyword { return Err(occurrence_error(first_keyword, keyword, "ignore")); } ignore_keyword = Some(keyword); output.ignore = value .value() .replace(' ', "") .split(',') .map(ToString::to_string) .collect(); } } } Ok(output) } } fn missing_attribute_error(variant: &Variant, attr: &str) -> syn::Error { syn::Error::new_spanned(variant, format!("{attr} must be specified")) } pub(super) fn check_missing_attributes( variant: &Variant, variant_properties: &ErrorVariantProperties, ) -> syn::Result<()> { if variant_properties.error_type.is_none() { return Err(missing_attribute_error(variant, "error_type")); } if variant_properties.code.is_none() { return Err(missing_attribute_error(variant, "code")); } if variant_properties.message.is_none() { return Err(missing_attribute_error(variant, "message")); } Ok(()) } /// Get all the fields not used in the error message. pub(super) fn get_unused_fields( fields: &Fields, message: &str, ignore: &std::collections::HashSet<String>, ) -> Vec<Field> { let fields = match fields { Fields::Unit => Vec::new(), Fields::Unnamed(_) => Vec::new(), Fields::Named(fields) => fields.named.iter().cloned().collect(), }; fields .iter() .filter(|&field| { // Safety: Named fields are guaranteed to have an identifier. #[allow(clippy::unwrap_used)] let field_name = format!("{}", field.ident.as_ref().unwrap()); !message.contains(&field_name) && !ignore.contains(&field_name) }) .cloned() .collect() }
crates/router_derive/src/macros/api_error/helpers.rs
router_derive
full_file
null
null
null
1,848
null
null
null
null
null
null
null
// Implementation: impl api::PaymentAuthorize for for Itaubank // File: crates/hyperswitch_connectors/src/connectors/itaubank.rs // Module: hyperswitch_connectors // Methods: 0 total (0 public) impl api::PaymentAuthorize for for Itaubank
crates/hyperswitch_connectors/src/connectors/itaubank.rs
hyperswitch_connectors
impl_block
null
null
null
61
null
Itaubank
api::PaymentAuthorize for
0
0
null
null
// Function: call_update_gateway_score_open_router // File: crates/router/src/routes/routing.rs // Module: router pub fn call_update_gateway_score_open_router( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<api_models::open_router::UpdateScorePayload>, ) -> impl Responder
crates/router/src/routes/routing.rs
router
function_signature
null
null
null
71
call_update_gateway_score_open_router
null
null
null
null
null
null
// Struct: BillingAddress // File: crates/hyperswitch_connectors/src/connectors/payload/requests.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BillingAddress
crates/hyperswitch_connectors/src/connectors/payload/requests.rs
hyperswitch_connectors
struct_definition
BillingAddress
0
[]
44
null
null
null
null
null
null
null
// Function: refunds_manual_update // File: crates/router/src/routes/refunds.rs // Module: router pub fn refunds_manual_update( state: web::Data<AppState>, req: HttpRequest, payload: web::Json<api_models::refunds::RefundManualUpdateRequest>, path: web::Path<String>, ) -> HttpResponse
crates/router/src/routes/refunds.rs
router
function_signature
null
null
null
73
refunds_manual_update
null
null
null
null
null
null
// File: crates/connector_configs/src/transformer.rs // Module: connector_configs // Public functions: 4 use std::str::FromStr; use api_models::{ enums::{ Connector, PaymentMethod, PaymentMethodType::{self, AliPay, ApplePay, GooglePay, Klarna, Paypal, WeChatPay}, }, payment_methods, refunds::MinorUnit, }; use crate::common_config::{ ConnectorApiIntegrationPayload, DashboardRequestPayload, PaymentMethodsEnabled, Provider, }; impl DashboardRequestPayload { pub fn transform_card( payment_method_type: PaymentMethodType, card_provider: Vec<api_models::enums::CardNetwork>, ) -> payment_methods::RequestPaymentMethodTypes { payment_methods::RequestPaymentMethodTypes { payment_method_type, card_networks: Some(card_provider), minimum_amount: Some(MinorUnit::zero()), maximum_amount: Some(MinorUnit::new(68607706)), recurring_enabled: Some(true), installment_payment_enabled: Some(false), accepted_currencies: None, accepted_countries: None, payment_experience: None, } } pub fn get_payment_experience( connector: Connector, payment_method_type: PaymentMethodType, payment_method: PaymentMethod, payment_experience: Option<api_models::enums::PaymentExperience>, ) -> Option<api_models::enums::PaymentExperience> { match payment_method { PaymentMethod::BankRedirect => None, _ => match (connector, payment_method_type) { #[cfg(feature = "dummy_connector")] (Connector::DummyConnector4, _) | (Connector::DummyConnector7, _) => { Some(api_models::enums::PaymentExperience::RedirectToUrl) } (Connector::Paypal, Paypal) => payment_experience, (Connector::Klarna, Klarna) => payment_experience, (Connector::Zen, GooglePay) | (Connector::Zen, ApplePay) => { Some(api_models::enums::PaymentExperience::RedirectToUrl) } (Connector::Braintree, Paypal) => { Some(api_models::enums::PaymentExperience::InvokeSdkClient) } (Connector::Globepay, AliPay) | (Connector::Globepay, WeChatPay) | (Connector::Stripe, WeChatPay) => { Some(api_models::enums::PaymentExperience::DisplayQrCode) } (_, GooglePay) | (_, ApplePay) | (_, PaymentMethodType::SamsungPay) | (_, PaymentMethodType::Paze) | (_, PaymentMethodType::AmazonPay) => { Some(api_models::enums::PaymentExperience::InvokeSdkClient) } (_, PaymentMethodType::DirectCarrierBilling) => { Some(api_models::enums::PaymentExperience::CollectOtp) } (_, PaymentMethodType::Cashapp) | (_, PaymentMethodType::Swish) => { Some(api_models::enums::PaymentExperience::DisplayQrCode) } _ => Some(api_models::enums::PaymentExperience::RedirectToUrl), }, } } pub fn transform_payment_method( connector: Connector, provider: Vec<Provider>, payment_method: PaymentMethod, ) -> Vec<payment_methods::RequestPaymentMethodTypes> { let mut payment_method_types = Vec::new(); for method_type in provider { let data = payment_methods::RequestPaymentMethodTypes { payment_method_type: method_type.payment_method_type, card_networks: None, minimum_amount: Some(MinorUnit::zero()), maximum_amount: Some(MinorUnit::new(68607706)), recurring_enabled: Some(true), installment_payment_enabled: Some(false), accepted_currencies: method_type.accepted_currencies, accepted_countries: method_type.accepted_countries, payment_experience: Self::get_payment_experience( connector, method_type.payment_method_type, payment_method, method_type.payment_experience, ), }; payment_method_types.push(data) } payment_method_types } pub fn create_connector_request( request: Self, api_response: ConnectorApiIntegrationPayload, ) -> ConnectorApiIntegrationPayload { let mut card_payment_method_types = Vec::new(); let mut payment_method_enabled = Vec::new(); if let Some(payment_methods_enabled) = request.payment_methods_enabled.clone() { for payload in payment_methods_enabled { match payload.payment_method { PaymentMethod::Card => { if let Some(card_provider) = payload.card_provider { let payment_type = PaymentMethodType::from_str(&payload.payment_method_type) .map_err(|_| "Invalid key received".to_string()); if let Ok(payment_type) = payment_type { for method in card_provider { let data = payment_methods::RequestPaymentMethodTypes { payment_method_type: payment_type, card_networks: Some(vec![method.payment_method_type]), minimum_amount: Some(MinorUnit::zero()), maximum_amount: Some(MinorUnit::new(68607706)), recurring_enabled: Some(true), installment_payment_enabled: Some(false), accepted_currencies: method.accepted_currencies, accepted_countries: method.accepted_countries, payment_experience: None, }; card_payment_method_types.push(data) } } } } PaymentMethod::BankRedirect | PaymentMethod::Wallet | PaymentMethod::PayLater | PaymentMethod::BankTransfer | PaymentMethod::Crypto | PaymentMethod::BankDebit | PaymentMethod::Reward | PaymentMethod::RealTimePayment | PaymentMethod::Upi | PaymentMethod::Voucher | PaymentMethod::GiftCard | PaymentMethod::OpenBanking | PaymentMethod::CardRedirect | PaymentMethod::MobilePayment => { if let Some(provider) = payload.provider { let val = Self::transform_payment_method( request.connector, provider, payload.payment_method, ); if !val.is_empty() { let methods = PaymentMethodsEnabled { payment_method: payload.payment_method, payment_method_types: Some(val), }; payment_method_enabled.push(methods); } } } }; } if !card_payment_method_types.is_empty() { let card = PaymentMethodsEnabled { payment_method: PaymentMethod::Card, payment_method_types: Some(card_payment_method_types), }; payment_method_enabled.push(card); } } ConnectorApiIntegrationPayload { connector_type: api_response.connector_type, profile_id: api_response.profile_id, connector_name: api_response.connector_name, connector_label: api_response.connector_label, merchant_connector_id: api_response.merchant_connector_id, disabled: api_response.disabled, test_mode: api_response.test_mode, payment_methods_enabled: Some(payment_method_enabled), connector_webhook_details: api_response.connector_webhook_details, metadata: request.metadata, } } }
crates/connector_configs/src/transformer.rs
connector_configs
full_file
null
null
null
1,506
null
null
null
null
null
null
null
// Implementation: impl Barclaycard // File: crates/hyperswitch_connectors/src/connectors/barclaycard.rs // Module: hyperswitch_connectors // Methods: 1 total (1 public) impl Barclaycard
crates/hyperswitch_connectors/src/connectors/barclaycard.rs
hyperswitch_connectors
impl_block
null
null
null
49
null
Barclaycard
null
1
1
null
null
// Struct: FiservemeaError // File: crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct FiservemeaError
crates/hyperswitch_connectors/src/connectors/fiservemea/transformers.rs
hyperswitch_connectors
struct_definition
FiservemeaError
0
[]
56
null
null
null
null
null
null
null
// Struct: Hipay // File: crates/hyperswitch_connectors/src/connectors/hipay.rs // Module: hyperswitch_connectors // Implementations: 17 // Traits: api::Payment, api::PaymentSession, api::ConnectorAccessToken, api::MandateSetup, api::PaymentAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, api::PaymentToken, ConnectorCommon, ConnectorValidation, webhooks::IncomingWebhook, ConnectorSpecifications pub struct Hipay
crates/hyperswitch_connectors/src/connectors/hipay.rs
hyperswitch_connectors
struct_definition
Hipay
17
[ "api::Payment", "api::PaymentSession", "api::ConnectorAccessToken", "api::MandateSetup", "api::PaymentAuthorize", "api::PaymentSync", "api::PaymentCapture", "api::PaymentVoid", "api::Refund", "api::RefundExecute", "api::RefundSync", "api::PaymentToken", "ConnectorCommon", "ConnectorValidation", "webhooks::IncomingWebhook", "ConnectorSpecifications" ]
126
null
null
null
null
null
null
null
// Struct: PaymentWebhooksLink // File: crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct PaymentWebhooksLink
crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
hyperswitch_connectors
struct_definition
PaymentWebhooksLink
0
[]
50
null
null
null
null
null
null
null
// File: crates/router/src/services/kafka/payment_intent_event.rs // Module: router // Public functions: 4 // Public structs: 2 #[cfg(feature = "v2")] use ::common_types::{ payments, primitive_wrappers::{EnablePartialAuthorizationBool, RequestExtendedAuthorizationBool}, }; #[cfg(feature = "v2")] use common_enums::{self, RequestIncrementalAuthorization}; use common_utils::{ crypto::Encryptable, hashing::HashedString, id_type, pii, types as common_types, }; use diesel_models::enums as storage_enums; #[cfg(feature = "v2")] use diesel_models::{types as diesel_types, PaymentLinkConfigRequestForPayments}; #[cfg(feature = "v2")] use diesel_models::{types::OrderDetailsWithAmount, TaxDetails}; use hyperswitch_domain_models::payments::PaymentIntent; #[cfg(feature = "v2")] use hyperswitch_domain_models::{address, routing}; use masking::{PeekInterface, Secret}; use serde_json::Value; use time::OffsetDateTime; #[cfg(feature = "v1")] #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentIntentEvent<'a> { pub payment_id: &'a id_type::PaymentId, pub merchant_id: &'a id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: common_types::MinorUnit, pub currency: Option<storage_enums::Currency>, pub amount_captured: Option<common_types::MinorUnit>, pub customer_id: Option<&'a id_type::CustomerId>, pub description: Option<&'a String>, pub return_url: Option<&'a String>, pub metadata: Option<String>, pub connector_id: Option<&'a String>, pub statement_descriptor_name: Option<&'a String>, pub statement_descriptor_suffix: Option<&'a String>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub setup_future_usage: Option<storage_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<&'a String>, pub active_attempt_id: String, pub business_country: Option<storage_enums::CountryAlpha2>, pub business_label: Option<&'a String>, pub attempt_count: i16, pub profile_id: Option<&'a id_type::ProfileId>, pub payment_confirm_source: Option<storage_enums::PaymentSource>, pub billing_details: Option<Encryptable<Secret<Value>>>, pub shipping_details: Option<Encryptable<Secret<Value>>>, pub customer_email: Option<HashedString<pii::EmailStrategy>>, pub feature_metadata: Option<&'a Value>, pub merchant_order_reference_id: Option<&'a String>, pub organization_id: &'a id_type::OrganizationId, #[serde(flatten)] pub infra_values: Option<Value>, } #[cfg(feature = "v2")] #[serde_with::skip_serializing_none] #[derive(serde::Serialize, Debug)] pub struct KafkaPaymentIntentEvent<'a> { pub payment_id: &'a id_type::GlobalPaymentId, pub merchant_id: &'a id_type::MerchantId, pub status: storage_enums::IntentStatus, pub amount: common_types::MinorUnit, pub currency: storage_enums::Currency, pub amount_captured: Option<common_types::MinorUnit>, pub customer_id: Option<&'a id_type::GlobalCustomerId>, pub description: Option<&'a common_types::Description>, pub return_url: Option<&'a common_types::Url>, pub metadata: Option<&'a Secret<Value>>, pub statement_descriptor: Option<&'a common_types::StatementDescriptor>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub created_at: OffsetDateTime, #[serde(with = "time::serde::timestamp::nanoseconds")] pub modified_at: OffsetDateTime, #[serde(default, with = "time::serde::timestamp::nanoseconds::option")] pub last_synced: Option<OffsetDateTime>, pub setup_future_usage: storage_enums::FutureUsage, pub off_session: bool, pub active_attempt_id: Option<&'a id_type::GlobalAttemptId>, pub active_attempt_id_type: common_enums::ActiveAttemptIDType, pub active_attempts_group_id: Option<&'a String>, pub attempt_count: i16, pub profile_id: &'a id_type::ProfileId, pub customer_email: Option<HashedString<pii::EmailStrategy>>, pub feature_metadata: Option<&'a diesel_types::FeatureMetadata>, pub organization_id: &'a id_type::OrganizationId, pub order_details: Option<&'a Vec<Secret<OrderDetailsWithAmount>>>, pub allowed_payment_method_types: Option<&'a Vec<common_enums::PaymentMethodType>>, pub connector_metadata: Option<&'a Secret<Value>>, pub payment_link_id: Option<&'a String>, pub updated_by: &'a String, pub surcharge_applicable: Option<bool>, pub request_incremental_authorization: RequestIncrementalAuthorization, pub split_txns_enabled: common_enums::SplitTxnsEnabled, pub authorization_count: Option<i32>, #[serde(with = "time::serde::timestamp::nanoseconds")] pub session_expiry: OffsetDateTime, pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, pub frm_metadata: Option<Secret<&'a Value>>, pub customer_details: Option<Secret<&'a Value>>, pub shipping_cost: Option<common_types::MinorUnit>, pub tax_details: Option<TaxDetails>, pub skip_external_tax_calculation: bool, pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, pub psd2_sca_exemption_type: Option<storage_enums::ScaExemptionType>, pub split_payments: Option<&'a payments::SplitPaymentsRequest>, pub platform_merchant_id: Option<&'a id_type::MerchantId>, pub force_3ds_challenge: Option<bool>, pub force_3ds_challenge_trigger: Option<bool>, pub processor_merchant_id: &'a id_type::MerchantId, pub created_by: Option<&'a common_types::CreatedBy>, pub is_iframe_redirection_enabled: Option<bool>, pub merchant_reference_id: Option<&'a id_type::PaymentReferenceId>, pub capture_method: storage_enums::CaptureMethod, pub authentication_type: Option<common_enums::AuthenticationType>, pub prerouting_algorithm: Option<&'a routing::PaymentRoutingInfo>, pub surcharge_amount: Option<common_types::MinorUnit>, pub billing_address: Option<Secret<&'a address::Address>>, pub shipping_address: Option<Secret<&'a address::Address>>, pub tax_on_surcharge: Option<common_types::MinorUnit>, pub frm_merchant_decision: Option<common_enums::MerchantDecision>, pub enable_payment_link: common_enums::EnablePaymentLinkRequest, pub apply_mit_exemption: common_enums::MitExemptionRequest, pub customer_present: common_enums::PresenceOfCustomerDuringPayment, pub routing_algorithm_id: Option<&'a id_type::RoutingId>, pub payment_link_config: Option<&'a PaymentLinkConfigRequestForPayments>, pub enable_partial_authorization: Option<EnablePartialAuthorizationBool>, #[serde(flatten)] infra_values: Option<Value>, } impl KafkaPaymentIntentEvent<'_> { #[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.payment_id } } #[cfg(feature = "v1")] impl<'a> KafkaPaymentIntentEvent<'a> { pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self { Self { payment_id: &intent.payment_id, merchant_id: &intent.merchant_id, status: intent.status, amount: intent.amount, currency: intent.currency, amount_captured: intent.amount_captured, customer_id: intent.customer_id.as_ref(), description: intent.description.as_ref(), return_url: intent.return_url.as_ref(), metadata: intent.metadata.as_ref().map(|x| x.to_string()), connector_id: intent.connector_id.as_ref(), statement_descriptor_name: intent.statement_descriptor_name.as_ref(), statement_descriptor_suffix: intent.statement_descriptor_suffix.as_ref(), created_at: intent.created_at.assume_utc(), modified_at: intent.modified_at.assume_utc(), last_synced: intent.last_synced.map(|i| i.assume_utc()), setup_future_usage: intent.setup_future_usage, off_session: intent.off_session, client_secret: intent.client_secret.as_ref(), active_attempt_id: intent.active_attempt.get_id(), business_country: intent.business_country, business_label: intent.business_label.as_ref(), attempt_count: intent.attempt_count, profile_id: intent.profile_id.as_ref(), payment_confirm_source: intent.payment_confirm_source, // TODO: use typed information here to avoid PII logging billing_details: None, shipping_details: None, customer_email: intent .customer_details .as_ref() .and_then(|value| value.get_inner().peek().as_object()) .and_then(|obj| obj.get("email")) .and_then(|email| email.as_str()) .map(|email| HashedString::from(Secret::new(email.to_string()))), feature_metadata: intent.feature_metadata.as_ref(), merchant_order_reference_id: intent.merchant_order_reference_id.as_ref(), organization_id: &intent.organization_id, infra_values: infra_values.clone(), } } } #[cfg(feature = "v2")] impl<'a> KafkaPaymentIntentEvent<'a> { pub fn from_storage(intent: &'a PaymentIntent, infra_values: Option<Value>) -> Self { let PaymentIntent { id, merchant_id, status, amount_details, amount_captured, customer_id, description, return_url, metadata, statement_descriptor, created_at, modified_at, last_synced, setup_future_usage, active_attempt_id, active_attempt_id_type, active_attempts_group_id, order_details, allowed_payment_method_types, connector_metadata, feature_metadata, attempt_count, profile_id, payment_link_id, frm_merchant_decision, updated_by, request_incremental_authorization, split_txns_enabled, authorization_count, session_expiry, request_external_three_ds_authentication, frm_metadata, customer_details, merchant_reference_id, billing_address, shipping_address, capture_method, authentication_type, prerouting_algorithm, organization_id, enable_payment_link, apply_mit_exemption, customer_present, payment_link_config, routing_algorithm_id, split_payments, force_3ds_challenge, force_3ds_challenge_trigger, processor_merchant_id, created_by, is_iframe_redirection_enabled, is_payment_id_from_merchant, enable_partial_authorization, } = intent; Self { payment_id: id, merchant_id, status: *status, amount: amount_details.order_amount, currency: amount_details.currency, amount_captured: *amount_captured, customer_id: customer_id.as_ref(), description: description.as_ref(), return_url: return_url.as_ref(), metadata: metadata.as_ref(), statement_descriptor: statement_descriptor.as_ref(), created_at: created_at.assume_utc(), modified_at: modified_at.assume_utc(), last_synced: last_synced.map(|t| t.assume_utc()), setup_future_usage: *setup_future_usage, off_session: setup_future_usage.is_off_session(), active_attempt_id: active_attempt_id.as_ref(), active_attempt_id_type: *active_attempt_id_type, active_attempts_group_id: active_attempts_group_id.as_ref(), attempt_count: *attempt_count, profile_id, customer_email: None, feature_metadata: feature_metadata.as_ref(), organization_id, order_details: order_details.as_ref(), allowed_payment_method_types: allowed_payment_method_types.as_ref(), connector_metadata: connector_metadata.as_ref(), payment_link_id: payment_link_id.as_ref(), updated_by, surcharge_applicable: None, request_incremental_authorization: *request_incremental_authorization, split_txns_enabled: *split_txns_enabled, authorization_count: *authorization_count, session_expiry: session_expiry.assume_utc(), request_external_three_ds_authentication: *request_external_three_ds_authentication, frm_metadata: frm_metadata .as_ref() .map(|frm_metadata| frm_metadata.as_ref()), customer_details: customer_details .as_ref() .map(|customer_details| customer_details.get_inner().as_ref()), shipping_cost: amount_details.shipping_cost, tax_details: amount_details.tax_details.clone(), skip_external_tax_calculation: amount_details.get_external_tax_action_as_bool(), request_extended_authorization: None, psd2_sca_exemption_type: None, split_payments: split_payments.as_ref(), platform_merchant_id: None, force_3ds_challenge: *force_3ds_challenge, force_3ds_challenge_trigger: *force_3ds_challenge_trigger, processor_merchant_id, created_by: created_by.as_ref(), is_iframe_redirection_enabled: *is_iframe_redirection_enabled, merchant_reference_id: merchant_reference_id.as_ref(), billing_address: billing_address .as_ref() .map(|billing_address| Secret::new(billing_address.get_inner())), shipping_address: shipping_address .as_ref() .map(|shipping_address| Secret::new(shipping_address.get_inner())), capture_method: *capture_method, authentication_type: *authentication_type, prerouting_algorithm: prerouting_algorithm.as_ref(), surcharge_amount: amount_details.surcharge_amount, tax_on_surcharge: amount_details.tax_on_surcharge, frm_merchant_decision: *frm_merchant_decision, enable_payment_link: *enable_payment_link, apply_mit_exemption: *apply_mit_exemption, customer_present: *customer_present, routing_algorithm_id: routing_algorithm_id.as_ref(), payment_link_config: payment_link_config.as_ref(), infra_values, enable_partial_authorization: *enable_partial_authorization, } } } impl super::KafkaMessage for KafkaPaymentIntentEvent<'_> { fn key(&self) -> String { format!( "{}_{}", self.merchant_id.get_string_repr(), self.get_id().get_string_repr(), ) } fn event_type(&self) -> crate::events::EventType { crate::events::EventType::PaymentIntent } }
crates/router/src/services/kafka/payment_intent_event.rs
router
full_file
null
null
null
3,283
null
null
null
null
null
null
null
// Struct: Noon // File: crates/hyperswitch_connectors/src/connectors/noon.rs // Module: hyperswitch_connectors // Implementations: 19 // Traits: api::Payment, api::PaymentSession, api::ConnectorAccessToken, api::MandateSetup, api::PaymentAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, api::PaymentToken, api::ConnectorMandateRevoke, ConnectorCommon, ConnectorValidation, api::ConnectorRedirectResponse, webhooks::IncomingWebhook, ConnectorSpecifications pub struct Noon
crates/hyperswitch_connectors/src/connectors/noon.rs
hyperswitch_connectors
struct_definition
Noon
19
[ "api::Payment", "api::PaymentSession", "api::ConnectorAccessToken", "api::MandateSetup", "api::PaymentAuthorize", "api::PaymentSync", "api::PaymentCapture", "api::PaymentVoid", "api::Refund", "api::RefundExecute", "api::RefundSync", "api::PaymentToken", "api::ConnectorMandateRevoke", "ConnectorCommon", "ConnectorValidation", "api::ConnectorRedirectResponse", "webhooks::IncomingWebhook", "ConnectorSpecifications" ]
138
null
null
null
null
null
null
null
// Implementation: impl webhooks::IncomingWebhook for for Katapult // File: crates/hyperswitch_connectors/src/connectors/katapult.rs // Module: hyperswitch_connectors // Methods: 3 total (0 public) impl webhooks::IncomingWebhook for for Katapult
crates/hyperswitch_connectors/src/connectors/katapult.rs
hyperswitch_connectors
impl_block
null
null
null
62
null
Katapult
webhooks::IncomingWebhook for
3
0
null
null
// Struct: OrderInformationWithBill // File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct OrderInformationWithBill
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
hyperswitch_connectors
struct_definition
OrderInformationWithBill
0
[]
51
null
null
null
null
null
null
null
// Trait: FieldExt // File: crates/router_derive/src/macros/schema/helpers.rs // Module: router_derive pub trait FieldExt
crates/router_derive/src/macros/schema/helpers.rs
router_derive
trait_definition
null
null
null
31
null
null
FieldExt
null
null
null
null
// Function: add_random_delay_to_schedule_time // File: crates/router/src/workflows/revenue_recovery.rs // Module: router pub fn add_random_delay_to_schedule_time( state: &SessionState, schedule_time: time::PrimitiveDateTime, ) -> time::PrimitiveDateTime
crates/router/src/workflows/revenue_recovery.rs
router
function_signature
null
null
null
59
add_random_delay_to_schedule_time
null
null
null
null
null
null
// Struct: ChargebeeSubscriptionData // File: crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct ChargebeeSubscriptionData
crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
hyperswitch_connectors
struct_definition
ChargebeeSubscriptionData
0
[]
50
null
null
null
null
null
null
null
// Implementation: impl PaymentLink // File: crates/router/src/routes/app.rs // Module: router // Methods: 1 total (1 public) impl PaymentLink
crates/router/src/routes/app.rs
router
impl_block
null
null
null
35
null
PaymentLink
null
1
1
null
null
// File: crates/router/src/core/payments/operations/payment_complete_authorize.rs // Module: router // Public structs: 1 use std::marker::PhantomData; use api_models::enums::FrmSuggestion; use async_trait::async_trait; use error_stack::{report, ResultExt}; use router_derive::PaymentOperation; use router_env::{instrument, tracing}; use super::{BoxedOperation, Domain, GetTracker, Operation, UpdateTracker, ValidateRequest}; use crate::{ core::{ errors::{self, CustomResult, RouterResult, StorageErrorExt}, mandate::helpers as m_helpers, payments::{self, helpers, operations, CustomerDetails, PaymentAddress, PaymentData}, }, events::audit_events::{AuditEvent, AuditEventType}, routes::{app::ReqState, SessionState}, services, types::{ api::{self, CustomerAcceptance, PaymentIdTypeExt}, domain, storage::{self, enums as storage_enums}, }, utils::{self, OptionExt}, }; #[derive(Debug, Clone, Copy, PaymentOperation)] #[operation(operations = "all", flow = "authorize")] pub struct CompleteAuthorize; type CompleteAuthorizeOperation<'b, F> = BoxedOperation<'b, F, api::PaymentsRequest, PaymentData<F>>; #[async_trait] impl<F: Send + Clone + Sync> GetTracker<F, PaymentData<F>, api::PaymentsRequest> for CompleteAuthorize { #[instrument(skip_all)] async fn get_trackers<'a>( &'a self, state: &'a SessionState, payment_id: &api::PaymentIdType, request: &api::PaymentsRequest, merchant_context: &domain::MerchantContext, _auth_flow: services::AuthFlow, _header_payload: &hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<operations::GetTrackerResponse<'a, F, api::PaymentsRequest, PaymentData<F>>> { let db = &*state.store; let key_manager_state = &state.into(); let merchant_id = merchant_context.get_merchant_account().get_id(); let storage_scheme = merchant_context.get_merchant_account().storage_scheme; let (mut payment_intent, mut payment_attempt, currency, amount); let payment_id = payment_id .get_payment_intent_id() .change_context(errors::ApiErrorResponse::PaymentNotFound)?; payment_intent = db .find_payment_intent_by_payment_id_merchant_id( key_manager_state, &payment_id, merchant_id, merchant_context.get_merchant_key_store(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; // TODO (#7195): Add platform merchant account validation once client_secret auth is solved payment_intent.setup_future_usage = request .setup_future_usage .or(payment_intent.setup_future_usage); helpers::authenticate_client_secret(request.client_secret.as_ref(), &payment_intent)?; helpers::validate_payment_status_against_not_allowed_statuses( payment_intent.status, &[ storage_enums::IntentStatus::Failed, storage_enums::IntentStatus::Succeeded, ], "confirm", )?; let browser_info = request .browser_info .clone() .as_ref() .map(utils::Encode::encode_to_value) .transpose() .change_context(errors::ApiErrorResponse::InvalidDataValue { field_name: "browser_info", })?; let recurring_details = request.recurring_details.clone(); payment_attempt = db .find_payment_attempt_by_payment_id_merchant_id_attempt_id( &payment_intent.payment_id, merchant_id, &payment_intent.active_attempt.get_id(), storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; let mandate_type = m_helpers::get_mandate_type( request.mandate_data.clone(), request.off_session, payment_intent.setup_future_usage, request.customer_acceptance.clone(), request.payment_token.clone(), payment_attempt.payment_method, ) .change_context(errors::ApiErrorResponse::MandateValidationFailed { reason: "Expected one out of recurring_details and mandate_data but got both".into(), })?; let m_helpers::MandateGenericData { token, payment_method, payment_method_type, mandate_data, recurring_mandate_payment_data, mandate_connector, payment_method_info, } = Box::pin(helpers::get_token_pm_type_mandate_details( state, request, mandate_type.to_owned(), merchant_context, payment_attempt.payment_method_id.clone(), payment_intent.customer_id.as_ref(), )) .await?; let customer_acceptance: Option<CustomerAcceptance> = request.customer_acceptance.clone().or(payment_method_info .clone() .map(|pm| { pm.customer_acceptance .parse_value::<CustomerAcceptance>("CustomerAcceptance") }) .transpose() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Failed to deserialize to CustomerAcceptance")?); let token = token.or_else(|| payment_attempt.payment_token.clone()); if let Some(payment_method) = payment_method { let should_validate_pm_or_token_given = //this validation should happen if data was stored in the vault helpers::should_store_payment_method_data_in_vault( &state.conf.temp_locker_enable_config, payment_attempt.connector.clone(), payment_method, ); if should_validate_pm_or_token_given { helpers::validate_pm_or_token_given( &request.payment_method, &request .payment_method_data .as_ref() .and_then(|pmd| pmd.payment_method_data.clone()), &request.payment_method_type, &mandate_type, &token, &request.ctp_service_details, )?; } } let token_data = if let Some((token, payment_method)) = token .as_ref() .zip(payment_method.or(payment_attempt.payment_method)) { Some( helpers::retrieve_payment_token_data(state, token.clone(), Some(payment_method)) .await?, ) } else { None }; payment_attempt.payment_method = payment_method.or(payment_attempt.payment_method); payment_attempt.browser_info = browser_info.or(payment_attempt.browser_info); payment_attempt.payment_method_type = payment_method_type.or(payment_attempt.payment_method_type); payment_attempt.payment_experience = request .payment_experience .or(payment_attempt.payment_experience); currency = payment_attempt.currency.get_required_value("currency")?; amount = payment_attempt.get_total_amount().into(); let customer_id = payment_intent .customer_id .as_ref() .or(request.customer_id.as_ref()) .cloned(); helpers::validate_customer_id_mandatory_cases( request.setup_future_usage.is_some(), customer_id.as_ref(), )?; let shipping_address = helpers::create_or_update_address_for_payment_by_request( state, request.shipping.as_ref(), payment_intent.shipping_address_id.clone().as_deref(), merchant_id, payment_intent.customer_id.as_ref(), merchant_context.get_merchant_key_store(), &payment_id, storage_scheme, ) .await?; payment_intent.shipping_address_id = shipping_address .as_ref() .map(|shipping_address| shipping_address.address_id.clone()); let billing_address = helpers::get_address_by_id( state, payment_intent.billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let payment_method_billing = helpers::get_address_by_id( state, payment_attempt.payment_method_billing_address_id.clone(), merchant_context.get_merchant_key_store(), &payment_intent.payment_id, merchant_id, merchant_context.get_merchant_account().storage_scheme, ) .await?; let redirect_response = request .feature_metadata .as_ref() .and_then(|fm| fm.redirect_response.clone()); payment_intent.shipping_address_id = shipping_address.clone().map(|i| i.address_id); payment_intent.billing_address_id = billing_address.clone().map(|i| i.address_id); payment_intent.return_url = request .return_url .as_ref() .map(|a| a.to_string()) .or(payment_intent.return_url); payment_intent.allowed_payment_method_types = request .get_allowed_payment_method_types_as_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error converting allowed_payment_types to Value")? .or(payment_intent.allowed_payment_method_types); payment_intent.connector_metadata = request .get_connector_metadata_as_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error converting connector_metadata to Value")? .or(payment_intent.connector_metadata); payment_intent.feature_metadata = request .get_feature_metadata_as_value() .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("Error converting feature_metadata to Value")? .or(payment_intent.feature_metadata); payment_intent.metadata = request.metadata.clone().or(payment_intent.metadata); // The operation merges mandate data from both request and payment_attempt let setup_mandate = mandate_data; let mandate_details_present = payment_attempt.mandate_details.is_some() || request.mandate_data.is_some(); helpers::validate_mandate_data_and_future_usage( payment_intent.setup_future_usage, mandate_details_present, )?; let profile_id = payment_intent .profile_id .as_ref() .get_required_value("profile_id") .change_context(errors::ApiErrorResponse::InternalServerError) .attach_printable("'profile_id' not set in payment intent")?; let business_profile = db .find_business_profile_by_profile_id( key_manager_state, merchant_context.get_merchant_key_store(), profile_id, ) .await .to_not_found_response(errors::ApiErrorResponse::ProfileNotFound { id: profile_id.get_string_repr().to_owned(), })?; let creds_identifier = request .merchant_connector_details .as_ref() .map(|merchant_connector_details| { merchant_connector_details.creds_identifier.to_owned() }); let payment_data = PaymentData { flow: PhantomData, payment_intent, payment_attempt, currency, amount, email: request.email.clone(), mandate_id: None, mandate_connector, setup_mandate, customer_acceptance, token, token_data, address: PaymentAddress::new( shipping_address.as_ref().map(From::from), billing_address.as_ref().map(From::from), payment_method_billing.as_ref().map(From::from), business_profile.use_billing_as_payment_method_billing, ), confirm: request.confirm, payment_method_data: request .payment_method_data .as_ref() .and_then(|pmd| pmd.payment_method_data.clone().map(Into::into)), payment_method_token: None, payment_method_info, force_sync: None, all_keys_required: None, refunds: vec![], disputes: vec![], attempts: None, sessions_token: vec![], card_cvc: request.card_cvc.clone(), creds_identifier, pm_token: None, connector_customer_id: None, recurring_mandate_payment_data, ephemeral_key: None, multiple_capture_data: None, redirect_response, surcharge_details: None, frm_message: None, payment_link_data: None, incremental_authorization_details: None, authorizations: vec![], authentication: None, recurring_details, poll_config: None, tax_data: None, session_id: None, service_details: None, card_testing_guard_data: None, vault_operation: None, threeds_method_comp_ind: request.threeds_method_comp_ind.clone(), whole_connector_response: None, is_manual_retry_enabled: None, }; let customer_details = Some(CustomerDetails { customer_id, name: request.name.clone(), email: request.email.clone(), phone: request.phone.clone(), phone_country_code: request.phone_country_code.clone(), tax_registration_id: None, }); let get_trackers_response = operations::GetTrackerResponse { operation: Box::new(self), customer_details, payment_data, business_profile, mandate_type, }; Ok(get_trackers_response) } } #[async_trait] impl<F: Clone + Send + Sync> Domain<F, api::PaymentsRequest, PaymentData<F>> for CompleteAuthorize { #[instrument(skip_all)] async fn get_or_create_customer_details<'a>( &'a self, state: &SessionState, payment_data: &mut PaymentData<F>, request: Option<CustomerDetails>, key_store: &domain::MerchantKeyStore, storage_scheme: common_enums::enums::MerchantStorageScheme, ) -> CustomResult< (CompleteAuthorizeOperation<'a, F>, Option<domain::Customer>), errors::StorageError, > { helpers::create_customer_if_not_exist( state, Box::new(self), payment_data, request, &key_store.merchant_id, key_store, storage_scheme, ) .await } #[instrument(skip_all)] async fn make_pm_data<'a>( &'a self, state: &'a SessionState, payment_data: &mut PaymentData<F>, storage_scheme: storage_enums::MerchantStorageScheme, merchant_key_store: &domain::MerchantKeyStore, customer: &Option<domain::Customer>, business_profile: &domain::Profile, should_retry_with_pan: bool, ) -> RouterResult<( CompleteAuthorizeOperation<'a, F>, Option<domain::PaymentMethodData>, Option<String>, )> { let (op, payment_method_data, pm_id) = Box::pin(helpers::make_pm_data( Box::new(self), state, payment_data, merchant_key_store, customer, storage_scheme, business_profile, should_retry_with_pan, )) .await?; Ok((op, payment_method_data, pm_id)) } #[instrument(skip_all)] async fn add_task_to_process_tracker<'a>( &'a self, _state: &'a SessionState, _payment_attempt: &storage::PaymentAttempt, _requeue: bool, _schedule_time: Option<time::PrimitiveDateTime>, ) -> CustomResult<(), errors::ApiErrorResponse> { Ok(()) } async fn get_connector<'a>( &'a self, _merchant_context: &domain::MerchantContext, state: &SessionState, request: &api::PaymentsRequest, _payment_intent: &storage::PaymentIntent, ) -> CustomResult<api::ConnectorChoice, errors::ApiErrorResponse> { // Use a new connector in the confirm call or use the same one which was passed when // creating the payment or if none is passed then use the routing algorithm helpers::get_connector_default(state, request.routing.clone()).await } #[instrument(skip_all)] async fn guard_payment_against_blocklist<'a>( &'a self, _state: &SessionState, _merchant_context: &domain::MerchantContext, _payment_data: &mut PaymentData<F>, ) -> CustomResult<bool, errors::ApiErrorResponse> { Ok(false) } } #[async_trait] impl<F: Clone + Sync> UpdateTracker<F, PaymentData<F>, api::PaymentsRequest> for CompleteAuthorize { #[instrument(skip_all)] async fn update_trackers<'b>( &'b self, state: &'b SessionState, req_state: ReqState, mut payment_data: PaymentData<F>, _customer: Option<domain::Customer>, storage_scheme: storage_enums::MerchantStorageScheme, _updated_customer: Option<storage::CustomerUpdate>, key_store: &domain::MerchantKeyStore, _frm_suggestion: Option<FrmSuggestion>, _header_payload: hyperswitch_domain_models::payments::HeaderPayload, ) -> RouterResult<(CompleteAuthorizeOperation<'b, F>, PaymentData<F>)> where F: 'b + Send, { let payment_intent_update = hyperswitch_domain_models::payments::payment_intent::PaymentIntentUpdate::CompleteAuthorizeUpdate { shipping_address_id: payment_data.payment_intent.shipping_address_id.clone() }; let db = &*state.store; let payment_intent = payment_data.payment_intent.clone(); let updated_payment_intent = db .update_payment_intent( &state.into(), payment_intent, payment_intent_update, key_store, storage_scheme, ) .await .to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?; req_state .event_context .event(AuditEvent::new(AuditEventType::PaymentCompleteAuthorize)) .with(payment_data.to_event()) .emit(); payment_data.payment_intent = updated_payment_intent; Ok((Box::new(self), payment_data)) } } impl<F: Send + Clone + Sync> ValidateRequest<F, api::PaymentsRequest, PaymentData<F>> for CompleteAuthorize { #[instrument(skip_all)] fn validate_request<'a, 'b>( &'b self, request: &api::PaymentsRequest, merchant_context: &'a domain::MerchantContext, ) -> RouterResult<( CompleteAuthorizeOperation<'b, F>, operations::ValidateResult, )> { let payment_id = request .payment_id .clone() .ok_or(report!(errors::ApiErrorResponse::PaymentNotFound))?; let request_merchant_id = request.merchant_id.as_ref(); helpers::validate_merchant_id( merchant_context.get_merchant_account().get_id(), request_merchant_id, ) .change_context(errors::ApiErrorResponse::InvalidDataFormat { field_name: "merchant_id".to_string(), expected_format: "merchant_id from merchant account".to_string(), })?; helpers::validate_payment_method_fields_present(request)?; let _mandate_type = helpers::validate_mandate(request, payments::is_operation_confirm(self))?; helpers::validate_recurring_details_and_token( &request.recurring_details, &request.payment_token, &request.mandate_id, )?; Ok(( Box::new(self), operations::ValidateResult { merchant_id: merchant_context.get_merchant_account().get_id().to_owned(), payment_id, storage_scheme: merchant_context.get_merchant_account().storage_scheme, requeue: matches!( request.retry_action, Some(api_models::enums::RetryAction::Requeue) ), }, )) } }
crates/router/src/core/payments/operations/payment_complete_authorize.rs
router
full_file
null
null
null
4,081
null
null
null
null
null
null
null
// Struct: BitpayErrorResponse // File: crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct BitpayErrorResponse
crates/hyperswitch_connectors/src/connectors/bitpay/transformers.rs
hyperswitch_connectors
struct_definition
BitpayErrorResponse
0
[]
47
null
null
null
null
null
null
null
// Struct: ReInviteUserRequest // File: crates/api_models/src/user.rs // Module: api_models // Implementations: 0 pub struct ReInviteUserRequest
crates/api_models/src/user.rs
api_models
struct_definition
ReInviteUserRequest
0
[]
37
null
null
null
null
null
null
null
// Struct: CheckoutWebhookObjectResource // File: crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct CheckoutWebhookObjectResource
crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
hyperswitch_connectors
struct_definition
CheckoutWebhookObjectResource
0
[]
51
null
null
null
null
null
null
null
// Struct: OrderInformationWithBill // File: crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct OrderInformationWithBill
crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
hyperswitch_connectors
struct_definition
OrderInformationWithBill
0
[]
51
null
null
null
null
null
null
null
// Function: get_billing_required_fields // File: crates/payment_methods/src/configs/payment_connector_required_fields.rs // Module: payment_methods pub fn get_billing_required_fields() -> HashMap<String, RequiredFieldInfo>
crates/payment_methods/src/configs/payment_connector_required_fields.rs
payment_methods
function_signature
null
null
null
44
get_billing_required_fields
null
null
null
null
null
null
// Implementation: impl RoleNew // File: crates/diesel_models/src/query/role.rs // Module: diesel_models // Methods: 1 total (0 public) impl RoleNew
crates/diesel_models/src/query/role.rs
diesel_models
impl_block
null
null
null
39
null
RoleNew
null
1
0
null
null
// Struct: SignifydPaymentsRecordReturnResponse // File: crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs // Module: hyperswitch_connectors // Implementations: 0 pub struct SignifydPaymentsRecordReturnResponse
crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
hyperswitch_connectors
struct_definition
SignifydPaymentsRecordReturnResponse
0
[]
57
null
null
null
null
null
null
null
// Implementation: impl ConnectorCommon for for Worldpayvantiv // File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs // Module: hyperswitch_connectors // Methods: 6 total (0 public) impl ConnectorCommon for for Worldpayvantiv
crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
hyperswitch_connectors
impl_block
null
null
null
59
null
Worldpayvantiv
ConnectorCommon for
6
0
null
null
// Struct: Encryption // File: crates/common_utils/src/encryption.rs // Module: common_utils // Implementations: 1 pub struct Encryption
crates/common_utils/src/encryption.rs
common_utils
struct_definition
Encryption
1
[]
32
null
null
null
null
null
null
null
// Struct: Nmi // File: crates/hyperswitch_connectors/src/connectors/nmi.rs // Module: hyperswitch_connectors // Implementations: 20 // Traits: api::Payment, api::PaymentSession, api::ConnectorAccessToken, api::MandateSetup, api::PaymentAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, api::PaymentToken, ConnectorCommon, ConnectorValidation, api::PaymentsPreProcessing, api::PaymentsCompleteAuthorize, IncomingWebhook, ConnectorRedirectResponse, ConnectorSpecifications pub struct Nmi
crates/hyperswitch_connectors/src/connectors/nmi.rs
hyperswitch_connectors
struct_definition
Nmi
20
[ "api::Payment", "api::PaymentSession", "api::ConnectorAccessToken", "api::MandateSetup", "api::PaymentAuthorize", "api::PaymentSync", "api::PaymentCapture", "api::PaymentVoid", "api::Refund", "api::RefundExecute", "api::RefundSync", "api::PaymentToken", "ConnectorCommon", "ConnectorValidation", "api::PaymentsPreProcessing", "api::PaymentsCompleteAuthorize", "IncomingWebhook", "ConnectorRedirectResponse", "ConnectorSpecifications" ]
138
null
null
null
null
null
null
null
// Struct: PayoutLinkResponse // File: crates/api_models/src/payouts.rs // Module: api_models // Implementations: 0 pub struct PayoutLinkResponse
crates/api_models/src/payouts.rs
api_models
struct_definition
PayoutLinkResponse
0
[]
39
null
null
null
null
null
null
null