text
string | file_path
string | module
string | type
string | tokens
int64 | language
string | struct_name
string | type_name
string | trait_name
string | impl_type
string | function_name
string | source
string | section
string | keys
list | macro_type
string | url
string | title
string | chunk_index
int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
File: crates/router/src/core/refunds_v2.rs
Public functions: 18
use std::{fmt::Debug, str::FromStr};
use api_models::{enums::Connector, refunds::RefundErrorDetails};
use common_utils::{id_type, types as common_utils_types};
use diesel_models::refund as diesel_refund;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
refunds::RefundListConstraints,
router_data::{ErrorResponse, RouterData},
router_data_v2::RefundFlowData,
};
use hyperswitch_interfaces::{
api::{Connector as ConnectorTrait, ConnectorIntegration},
connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2},
integrity::{CheckIntegrity, FlowIntegrity, GetIntegrityObject},
};
use router_env::{instrument, tracing};
use crate::{
consts,
core::{
errors::{self, ConnectorErrorExt, StorageErrorExt},
payments::{self, access_token, helpers},
utils::{self as core_utils, refunds_validator},
},
db, logger,
routes::{metrics, SessionState},
services,
types::{
self,
api::{self, refunds},
domain,
storage::{self, enums},
transformers::{ForeignFrom, ForeignTryFrom},
},
utils,
};
#[instrument(skip_all)]
pub async fn refund_create_core(
state: SessionState,
merchant_context: domain::MerchantContext,
req: refunds::RefundsCreateRequest,
global_refund_id: id_type::GlobalRefundId,
) -> errors::RouterResponse<refunds::RefundResponse> {
let db = &*state.store;
let (payment_intent, payment_attempt, amount);
payment_intent = db
.find_payment_intent_by_id(
&(&state).into(),
&req.payment_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
utils::when(
!(payment_intent.status == enums::IntentStatus::Succeeded
|| payment_intent.status == enums::IntentStatus::PartiallyCaptured),
|| {
Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState {
current_flow: "refund".into(),
field_name: "status".into(),
current_value: payment_intent.status.to_string(),
states: "succeeded, partially_captured".to_string()
})
.attach_printable("unable to refund for a unsuccessful payment intent"))
},
)?;
let captured_amount = payment_intent
.amount_captured
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("amount captured is none in a successful payment")?;
// Amount is not passed in request refer from payment intent.
amount = req.amount.unwrap_or(captured_amount);
utils::when(amount <= common_utils_types::MinorUnit::new(0), || {
Err(report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "amount".to_string(),
expected_format: "positive integer".to_string()
})
.attach_printable("amount less than or equal to zero"))
})?;
payment_attempt = db
.find_payment_attempt_last_successful_or_partially_captured_attempt_by_payment_id(
&(&state).into(),
merchant_context.get_merchant_key_store(),
&req.payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::SuccessfulPaymentNotFound)?;
tracing::Span::current().record("global_refund_id", global_refund_id.get_string_repr());
let merchant_connector_details = req.merchant_connector_details.clone();
Box::pin(validate_and_create_refund(
&state,
&merchant_context,
&payment_attempt,
&payment_intent,
amount,
req,
global_refund_id,
merchant_connector_details,
))
.await
.map(services::ApplicationResponse::Json)
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn trigger_refund_to_gateway(
state: &SessionState,
refund: &diesel_refund::Refund,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
) -> errors::RouterResult<diesel_refund::Refund> {
let db = &*state.store;
let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?;
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let mca = db
.find_merchant_connector_account_by_id(
&state.into(),
&mca_id,
merchant_context.get_merchant_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch merchant connector account")?;
metrics::REFUND_COUNT.add(
1,
router_env::metric_attributes!(("connector", mca_id.get_string_repr().to_string())),
);
let connector_enum = mca.connector_name;
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_enum.to_string(),
api::GetToken::Connector,
Some(mca_id.clone()),
)?;
refunds_validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?;
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(mca));
let mut router_data = core_utils::construct_refund_router_data(
state,
connector_enum,
merchant_context,
payment_intent,
payment_attempt,
refund,
&merchant_connector_account,
)
.await?;
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
merchant_context,
&router_data,
None,
))
.await?;
logger::debug!(refund_router_data=?router_data);
access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&payments::CallConnectorAction::Trigger,
);
let connector_response = Box::pin(call_connector_service(
state,
&connector,
add_access_token_result,
router_data,
))
.await;
let refund_update = get_refund_update_object(
state,
&connector,
&storage_scheme,
merchant_context,
&connector_response,
)
.await;
let response = match refund_update {
Some(refund_update) => state
.store
.update_refund(
refund.to_owned(),
refund_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating refund: refund_id: {}",
refund.id.get_string_repr()
)
})?,
None => refund.to_owned(),
};
// Implement outgoing webhooks here
connector_response.to_refund_failed_response()?;
Ok(response)
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn internal_trigger_refund_to_gateway(
state: &SessionState,
refund: &diesel_refund::Refund,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
merchant_connector_details: common_types::domain::MerchantConnectorAuthDetails,
) -> errors::RouterResult<diesel_refund::Refund> {
let storage_scheme = merchant_context.get_merchant_account().storage_scheme;
let routed_through = payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve connector from payment attempt")?;
metrics::REFUND_COUNT.add(
1,
router_env::metric_attributes!(("connector", routed_through.clone())),
);
let connector_enum = merchant_connector_details.connector_name;
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_enum.to_string(),
api::GetToken::Connector,
None,
)?;
refunds_validator::validate_for_valid_refunds(payment_attempt, connector.connector_name)?;
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(
merchant_connector_details,
);
let mut router_data = core_utils::construct_refund_router_data(
state,
connector_enum,
merchant_context,
payment_intent,
payment_attempt,
refund,
&merchant_connector_account,
)
.await?;
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
merchant_context,
&router_data,
None,
))
.await?;
access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&payments::CallConnectorAction::Trigger,
);
let connector_response = Box::pin(call_connector_service(
state,
&connector,
add_access_token_result,
router_data,
))
.await;
let refund_update = get_refund_update_object(
state,
&connector,
&storage_scheme,
merchant_context,
&connector_response,
)
.await;
let response = match refund_update {
Some(refund_update) => state
.store
.update_refund(
refund.to_owned(),
refund_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Failed while updating refund: refund_id: {}",
refund.id.get_string_repr()
)
})?,
None => refund.to_owned(),
};
// Implement outgoing webhooks here
connector_response.to_refund_failed_response()?;
Ok(response)
}
async fn call_connector_service<F>(
state: &SessionState,
connector: &api::ConnectorData,
add_access_token_result: types::AddAccessTokenResult,
router_data: RouterData<F, types::RefundsData, types::RefundsResponseData>,
) -> Result<
RouterData<F, types::RefundsData, types::RefundsResponseData>,
error_stack::Report<errors::ConnectorError>,
>
where
F: Debug + Clone + 'static,
dyn ConnectorTrait + Sync:
ConnectorIntegration<F, types::RefundsData, types::RefundsResponseData>,
dyn ConnectorV2 + Sync:
ConnectorIntegrationV2<F, RefundFlowData, types::RefundsData, types::RefundsResponseData>,
{
if !(add_access_token_result.connector_supports_access_token
&& router_data.access_token.is_none())
{
let connector_integration: services::BoxedRefundConnectorIntegrationInterface<
F,
types::RefundsData,
types::RefundsResponseData,
> = connector.connector.get_connector_integration();
services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
} else {
Ok(router_data)
}
}
async fn get_refund_update_object(
state: &SessionState,
connector: &api::ConnectorData,
storage_scheme: &enums::MerchantStorageScheme,
merchant_context: &domain::MerchantContext,
router_data_response: &Result<
RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>,
error_stack::Report<errors::ConnectorError>,
>,
) -> Option<diesel_refund::RefundUpdate> {
match router_data_response {
// This error is related to connector implementation i.e if no implementation for refunds for that specific connector in HS or the connector does not support refund itself.
Err(err) => get_connector_implementation_error_refund_update(err, *storage_scheme),
Ok(response) => {
let response = perform_integrity_check(response.clone());
match response.response.clone() {
Err(err) => Some(
get_connector_error_refund_update(state, err, connector, storage_scheme).await,
),
Ok(refund_response_data) => Some(get_refund_update_for_refund_response_data(
response,
connector,
refund_response_data,
storage_scheme,
merchant_context,
)),
}
}
}
}
fn get_connector_implementation_error_refund_update(
error: &error_stack::Report<errors::ConnectorError>,
storage_scheme: enums::MerchantStorageScheme,
) -> Option<diesel_refund::RefundUpdate> {
Option::<diesel_refund::RefundUpdate>::foreign_from((error.current_context(), storage_scheme))
}
async fn get_connector_error_refund_update(
state: &SessionState,
err: ErrorResponse,
connector: &api::ConnectorData,
storage_scheme: &enums::MerchantStorageScheme,
) -> diesel_refund::RefundUpdate {
let unified_error_object = get_unified_error_and_message(state, &err, connector).await;
diesel_refund::RefundUpdate::build_error_update_for_unified_error_and_message(
unified_error_object,
err.reason.or(Some(err.message)),
Some(err.code),
storage_scheme,
)
}
async fn get_unified_error_and_message(
state: &SessionState,
err: &ErrorResponse,
connector: &api::ConnectorData,
) -> (String, String) {
let option_gsm = helpers::get_gsm_record(
state,
Some(err.code.clone()),
Some(err.message.clone()),
connector.connector_name.to_string(),
consts::REFUND_FLOW_STR.to_string(),
)
.await;
// Note: Some connectors do not have a separate list of refund errors
// In such cases, the error codes and messages are stored under "Authorize" flow in GSM table
// So we will have to fetch the GSM using Authorize flow in case GSM is not found using "refund_flow"
let option_gsm = if option_gsm.is_none() {
helpers::get_gsm_record(
state,
Some(err.code.clone()),
Some(err.message.clone()),
connector.connector_name.to_string(),
consts::AUTHORIZE_FLOW_STR.to_string(),
)
.await
} else {
option_gsm
};
let gsm_unified_code = option_gsm.as_ref().and_then(|gsm| gsm.unified_code.clone());
let gsm_unified_message = option_gsm.and_then(|gsm| gsm.unified_message);
match gsm_unified_code.as_ref().zip(gsm_unified_message.as_ref()) {
Some((code, message)) => (code.to_owned(), message.to_owned()),
None => (
consts::DEFAULT_UNIFIED_ERROR_CODE.to_owned(),
consts::DEFAULT_UNIFIED_ERROR_MESSAGE.to_owned(),
),
}
}
pub fn get_refund_update_for_refund_response_data(
router_data: RouterData<api::Execute, types::RefundsData, types::RefundsResponseData>,
connector: &api::ConnectorData,
refund_response_data: types::RefundsResponseData,
storage_scheme: &enums::MerchantStorageScheme,
merchant_context: &domain::MerchantContext,
) -> diesel_refund::RefundUpdate {
// match on connector integrity checks
match router_data.integrity_check.clone() {
Err(err) => {
let connector_refund_id = err
.connector_transaction_id
.map(common_utils_types::ConnectorTransactionId::from);
metrics::INTEGRITY_CHECK_FAILED.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
(
"merchant_id",
merchant_context.get_merchant_account().get_id().clone()
),
),
);
diesel_refund::RefundUpdate::build_error_update_for_integrity_check_failure(
err.field_names,
connector_refund_id,
storage_scheme,
)
}
Ok(()) => {
if refund_response_data.refund_status == diesel_models::enums::RefundStatus::Success {
metrics::SUCCESSFUL_REFUND.add(
1,
router_env::metric_attributes!((
"connector",
connector.connector_name.to_string(),
)),
)
}
let connector_refund_id = common_utils_types::ConnectorTransactionId::from(
refund_response_data.connector_refund_id,
);
diesel_refund::RefundUpdate::build_refund_update(
connector_refund_id,
refund_response_data.refund_status,
storage_scheme,
)
}
}
}
pub fn perform_integrity_check<F>(
mut router_data: RouterData<F, types::RefundsData, types::RefundsResponseData>,
) -> RouterData<F, types::RefundsData, types::RefundsResponseData>
where
F: Debug + Clone + 'static,
{
// Initiating Integrity check
let integrity_result = check_refund_integrity(&router_data.request, &router_data.response);
router_data.integrity_check = integrity_result;
router_data
}
impl ForeignFrom<(&errors::ConnectorError, enums::MerchantStorageScheme)>
for Option<diesel_refund::RefundUpdate>
{
fn foreign_from(
(from, storage_scheme): (&errors::ConnectorError, enums::MerchantStorageScheme),
) -> Self {
match from {
errors::ConnectorError::NotImplemented(message) => {
Some(diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: Some(
errors::ConnectorError::NotImplemented(message.to_owned()).to_string(),
),
refund_error_code: Some("NOT_IMPLEMENTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
})
}
errors::ConnectorError::NotSupported { message, connector } => {
Some(diesel_refund::RefundUpdate::ErrorUpdate {
refund_status: Some(enums::RefundStatus::Failure),
refund_error_message: Some(format!(
"{message} is not supported by {connector}"
)),
refund_error_code: Some("NOT_SUPPORTED".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
})
}
_ => None,
}
}
}
pub fn check_refund_integrity<T, Request>(
request: &Request,
refund_response_data: &Result<types::RefundsResponseData, ErrorResponse>,
) -> Result<(), common_utils::errors::IntegrityCheckError>
where
T: FlowIntegrity,
Request: GetIntegrityObject<T> + CheckIntegrity<Request, T>,
{
let connector_refund_id = refund_response_data
.as_ref()
.map(|resp_data| resp_data.connector_refund_id.clone())
.ok();
request.check_integrity(request, connector_refund_id.to_owned())
}
// ********************************************** REFUND UPDATE **********************************************
pub async fn refund_metadata_update_core(
state: SessionState,
merchant_account: domain::MerchantAccount,
req: refunds::RefundMetadataUpdateRequest,
global_refund_id: id_type::GlobalRefundId,
) -> errors::RouterResponse<refunds::RefundResponse> {
let db = state.store.as_ref();
let refund = db
.find_refund_by_id(&global_refund_id, merchant_account.storage_scheme)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let response = db
.update_refund(
refund,
diesel_refund::RefundUpdate::MetadataAndReasonUpdate {
metadata: req.metadata,
reason: req.reason,
updated_by: merchant_account.storage_scheme.to_string(),
},
merchant_account.storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| {
format!(
"Unable to update refund with refund_id: {}",
global_refund_id.get_string_repr()
)
})?;
refunds::RefundResponse::foreign_try_from(response).map(services::ApplicationResponse::Json)
}
// ********************************************** REFUND SYNC **********************************************
#[instrument(skip_all)]
pub async fn refund_retrieve_core_with_refund_id(
state: SessionState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
request: refunds::RefundsRetrieveRequest,
) -> errors::RouterResponse<refunds::RefundResponse> {
let refund_id = request.refund_id.clone();
let db = &*state.store;
let profile_id = profile.get_id().to_owned();
let refund = db
.find_refund_by_id(
&refund_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let response = Box::pin(refund_retrieve_core(
state.clone(),
merchant_context,
Some(profile_id),
request,
refund,
))
.await?;
api::RefundResponse::foreign_try_from(response).map(services::ApplicationResponse::Json)
}
#[instrument(skip_all)]
pub async fn refund_retrieve_core(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: Option<id_type::ProfileId>,
request: refunds::RefundsRetrieveRequest,
refund: diesel_refund::Refund,
) -> errors::RouterResult<diesel_refund::Refund> {
let db = &*state.store;
let key_manager_state = &(&state).into();
core_utils::validate_profile_id_from_auth_layer(profile_id, &refund)?;
let payment_id = &refund.payment_id;
let payment_intent = db
.find_payment_intent_by_id(
key_manager_state,
payment_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
let active_attempt_id = payment_intent
.active_attempt_id
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Active attempt id not found")?;
let payment_attempt = db
.find_payment_attempt_by_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
&active_attempt_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
let unified_translated_message = if let (Some(unified_code), Some(unified_message)) =
(refund.unified_code.clone(), refund.unified_message.clone())
{
helpers::get_unified_translation(
&state,
unified_code,
unified_message.clone(),
state.locale.to_string(),
)
.await
.or(Some(unified_message))
} else {
refund.unified_message
};
let refund = diesel_refund::Refund {
unified_message: unified_translated_message,
..refund
};
let response = if should_call_refund(&refund, request.force_sync.unwrap_or(false)) {
if state.conf.merchant_id_auth.merchant_id_auth_enabled {
let merchant_connector_details = match request.merchant_connector_details {
Some(details) => details,
None => {
return Err(report!(errors::ApiErrorResponse::MissingRequiredField {
field_name: "merchant_connector_details"
}));
}
};
Box::pin(internal_sync_refund_with_gateway(
&state,
&merchant_context,
&payment_attempt,
&payment_intent,
&refund,
merchant_connector_details,
))
.await
} else {
Box::pin(sync_refund_with_gateway(
&state,
&merchant_context,
&payment_attempt,
&payment_intent,
&refund,
))
.await
}
} else {
Ok(refund)
}?;
Ok(response)
}
fn should_call_refund(refund: &diesel_models::refund::Refund, force_sync: bool) -> bool {
// This implies, we cannot perform a refund sync & `the connector_refund_id`
// doesn't exist
let predicate1 = refund.connector_refund_id.is_some();
// This allows refund sync at connector level if force_sync is enabled, or
// checks if the refund has failed
let predicate2 = force_sync
|| !matches!(
refund.refund_status,
diesel_models::enums::RefundStatus::Failure
| diesel_models::enums::RefundStatus::Success
);
predicate1 && predicate2
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn sync_refund_with_gateway(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund: &diesel_refund::Refund,
) -> errors::RouterResult<diesel_refund::Refund> {
let db = &*state.store;
let connector_id = refund.connector.to_string();
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_id,
api::GetToken::Connector,
payment_attempt.merchant_connector_id.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector")?;
let mca_id = payment_attempt.get_attempt_merchant_connector_account_id()?;
let mca = db
.find_merchant_connector_account_by_id(
&state.into(),
&mca_id,
merchant_context.get_merchant_key_store(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch merchant connector account")?;
let connector_enum = mca.connector_name;
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(mca));
let mut router_data = core_utils::construct_refund_router_data::<api::RSync>(
state,
connector_enum,
merchant_context,
payment_intent,
payment_attempt,
refund,
&merchant_connector_account,
)
.await?;
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
merchant_context,
&router_data,
None,
))
.await?;
logger::debug!(refund_retrieve_router_data=?router_data);
access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&payments::CallConnectorAction::Trigger,
);
let connector_response = Box::pin(call_connector_service(
state,
&connector,
add_access_token_result,
router_data,
))
.await
.to_refund_failed_response()?;
let connector_response = perform_integrity_check(connector_response);
let refund_update =
build_refund_update_for_rsync(&connector, merchant_context, connector_response);
let response = state
.store
.update_refund(
refund.to_owned(),
refund_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)
.attach_printable_lazy(|| {
format!(
"Unable to update refund with refund_id: {}",
refund.id.get_string_repr()
)
})?;
// Implement outgoing webhook here
Ok(response)
}
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn internal_sync_refund_with_gateway(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund: &diesel_refund::Refund,
merchant_connector_details: common_types::domain::MerchantConnectorAuthDetails,
) -> errors::RouterResult<diesel_refund::Refund> {
let connector_enum = merchant_connector_details.connector_name;
let connector: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_enum.to_string(),
api::GetToken::Connector,
None,
)?;
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(
merchant_connector_details,
);
let mut router_data = core_utils::construct_refund_router_data::<api::RSync>(
state,
connector_enum,
merchant_context,
payment_intent,
payment_attempt,
refund,
&merchant_connector_account,
)
.await?;
let add_access_token_result = Box::pin(access_token::add_access_token(
state,
&connector,
merchant_context,
&router_data,
None,
))
.await?;
access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&payments::CallConnectorAction::Trigger,
);
let connector_response = Box::pin(call_connector_service(
state,
&connector,
add_access_token_result,
router_data,
))
.await
.to_refund_failed_response()?;
let connector_response = perform_integrity_check(connector_response);
let refund_update =
build_refund_update_for_rsync(&connector, merchant_context, connector_response);
let response = state
.store
.update_refund(
refund.to_owned(),
refund_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)
.attach_printable_lazy(|| {
format!(
"Unable to update refund with refund_id: {}",
refund.id.get_string_repr()
)
})?;
// Implement outgoing webhook here
Ok(response)
}
pub fn build_refund_update_for_rsync(
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
router_data_response: RouterData<api::RSync, types::RefundsData, types::RefundsResponseData>,
) -> diesel_refund::RefundUpdate {
let merchant_account = merchant_context.get_merchant_account();
let storage_scheme = &merchant_context.get_merchant_account().storage_scheme;
match router_data_response.response {
Err(error_message) => {
let refund_status = match error_message.status_code {
// marking failure for 2xx because this is genuine refund failure
200..=299 => Some(enums::RefundStatus::Failure),
_ => None,
};
let refund_error_message = error_message.reason.or(Some(error_message.message));
let refund_error_code = Some(error_message.code);
diesel_refund::RefundUpdate::build_error_update_for_refund_failure(
refund_status,
refund_error_message,
refund_error_code,
storage_scheme,
)
}
Ok(response) => match router_data_response.integrity_check.clone() {
Err(err) => {
metrics::INTEGRITY_CHECK_FAILED.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("merchant_id", merchant_account.get_id().clone()),
),
);
let connector_refund_id = err
.connector_transaction_id
.map(common_utils_types::ConnectorTransactionId::from);
diesel_refund::RefundUpdate::build_error_update_for_integrity_check_failure(
err.field_names,
connector_refund_id,
storage_scheme,
)
}
Ok(()) => {
let connector_refund_id =
common_utils_types::ConnectorTransactionId::from(response.connector_refund_id);
diesel_refund::RefundUpdate::build_refund_update(
connector_refund_id,
response.refund_status,
storage_scheme,
)
}
},
}
}
// ********************************************** Refund list **********************************************
/// If payment_id is provided, lists all the refunds associated with that particular payment_id
/// If payment_id is not provided, lists the refunds associated with that particular merchant - to the limit specified,if no limits given, it is 10 by default
#[instrument(skip_all)]
#[cfg(feature = "olap")]
pub async fn refund_list(
state: SessionState,
merchant_account: domain::MerchantAccount,
profile: domain::Profile,
req: refunds::RefundListRequest,
) -> errors::RouterResponse<refunds::RefundListResponse> {
let db = state.store;
let limit = refunds_validator::validate_refund_list(req.limit)?;
let offset = req.offset.unwrap_or_default();
let refund_list = db
.filter_refund_by_constraints(
merchant_account.get_id(),
RefundListConstraints::from((req.clone(), profile.clone())),
merchant_account.storage_scheme,
limit,
offset,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let data: Vec<refunds::RefundResponse> = refund_list
.into_iter()
.map(refunds::RefundResponse::foreign_try_from)
.collect::<Result<_, _>>()?;
let total_count = db
.get_total_count_of_refunds(
merchant_account.get_id(),
RefundListConstraints::from((req, profile)),
merchant_account.storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)?;
Ok(services::ApplicationResponse::Json(
api_models::refunds::RefundListResponse {
count: data.len(),
total_count,
data,
},
))
}
// ********************************************** VALIDATIONS **********************************************
#[instrument(skip_all)]
#[allow(clippy::too_many_arguments)]
pub async fn validate_and_create_refund(
state: &SessionState,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
refund_amount: common_utils_types::MinorUnit,
req: refunds::RefundsCreateRequest,
global_refund_id: id_type::GlobalRefundId,
merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>,
) -> errors::RouterResult<refunds::RefundResponse> {
let db = &*state.store;
let refund_type = req.refund_type.unwrap_or_default();
let merchant_reference_id = req.merchant_reference_id;
let predicate = req
.merchant_id
.as_ref()
.map(|merchant_id| merchant_id != merchant_context.get_merchant_account().get_id());
utils::when(predicate.unwrap_or(false), || {
Err(report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "merchant_id".to_string(),
expected_format: "merchant_id from merchant account".to_string()
})
.attach_printable("invalid merchant_id in request"))
})?;
let connector_payment_id = payment_attempt.clone().connector_payment_id.ok_or_else(|| {
report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Transaction in invalid. Missing field \"connector_transaction_id\" in payment_attempt.")
})?;
let all_refunds = db
.find_refund_by_merchant_id_connector_transaction_id(
merchant_context.get_merchant_account().get_id(),
&connector_payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::RefundNotFound)?;
let currency = payment_intent.amount_details.currency;
refunds_validator::validate_payment_order_age(
&payment_intent.created_at,
state.conf.refund.max_age,
)
.change_context(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "created_at".to_string(),
expected_format: format!(
"created_at not older than {} days",
state.conf.refund.max_age,
),
})?;
let total_amount_captured = payment_intent
.amount_captured
.unwrap_or(payment_attempt.get_total_amount());
refunds_validator::validate_refund_amount(
total_amount_captured.get_amount_as_i64(),
&all_refunds,
refund_amount.get_amount_as_i64(),
)
.change_context(errors::ApiErrorResponse::RefundAmountExceedsPaymentAmount)?;
refunds_validator::validate_maximum_refund_against_payment_attempt(
&all_refunds,
state.conf.refund.max_attempts,
)
.change_context(errors::ApiErrorResponse::MaximumRefundCount)?;
let connector = payment_attempt
.connector
.clone()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("No connector populated in payment attempt")?;
let (connector_transaction_id, processor_transaction_data) =
common_utils_types::ConnectorTransactionId::form_id_and_data(connector_payment_id);
let refund_create_req = diesel_refund::RefundNew {
id: global_refund_id,
merchant_reference_id: merchant_reference_id.clone(),
external_reference_id: Some(merchant_reference_id.get_string_repr().to_string()),
payment_id: req.payment_id,
merchant_id: merchant_context.get_merchant_account().get_id().clone(),
connector_transaction_id,
connector,
refund_type: enums::RefundType::foreign_from(req.refund_type.unwrap_or_default()),
total_amount: payment_attempt.get_total_amount(),
refund_amount,
currency,
|
crates/router/src/core/refunds_v2.rs#chunk0
|
router
|
chunk
| 8,190
| null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/api_models/src/routing.rs
Public functions: 40
Public structs: 64
use std::fmt::Debug;
use common_types::three_ds_decision_rule_engine::{ThreeDSDecision, ThreeDSDecisionRule};
use common_utils::{
errors::{ParsingError, ValidationError},
ext_traits::ValueExt,
pii,
};
use euclid::frontend::ast::Program;
pub use euclid::{
dssa::types::EuclidAnalysable,
frontend::{
ast,
dir::{DirKeyKind, EuclidDirFilter},
},
};
use serde::{Deserialize, Serialize};
use utoipa::ToSchema;
use crate::{
enums::{RoutableConnectors, TransactionType},
open_router,
};
// Define constants for default values
const DEFAULT_LATENCY_THRESHOLD: f64 = 90.0;
const DEFAULT_BUCKET_SIZE: i32 = 200;
const DEFAULT_HEDGING_PERCENT: f64 = 5.0;
const DEFAULT_ELIMINATION_THRESHOLD: f64 = 0.35;
const DEFAULT_PAYMENT_METHOD: &str = "CARD";
#[derive(Debug, Clone, Serialize, Deserialize, ToSchema)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum ConnectorSelection {
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
}
impl ConnectorSelection {
pub fn get_connector_list(&self) -> Vec<RoutableConnectorChoice> {
match self {
Self::Priority(list) => list.clone(),
Self::VolumeSplit(splits) => {
splits.iter().map(|split| split.connector.clone()).collect()
}
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct RoutingConfigRequest {
pub name: String,
pub description: String,
pub algorithm: StaticRoutingAlgorithm,
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct RoutingConfigRequest {
pub name: Option<String>,
pub description: Option<String>,
pub algorithm: Option<StaticRoutingAlgorithm>,
#[schema(value_type = Option<String>)]
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub transaction_type: Option<TransactionType>,
}
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct ProfileDefaultRoutingConfig {
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
pub connectors: Vec<RoutableConnectorChoice>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingRetrieveQuery {
pub limit: Option<u16>,
pub offset: Option<u8>,
pub transaction_type: Option<TransactionType>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingActivatePayload {
pub transaction_type: Option<TransactionType>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingRetrieveLinkQuery {
pub profile_id: Option<common_utils::id_type::ProfileId>,
pub transaction_type: Option<TransactionType>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct RoutingRetrieveLinkQueryWrapper {
pub routing_query: RoutingRetrieveQuery,
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
/// Response of the retrieved routing configs for a merchant account
pub struct RoutingRetrieveResponse {
pub algorithm: Option<MerchantRoutingAlgorithm>,
}
#[derive(Debug, serde::Serialize, ToSchema)]
#[serde(untagged)]
pub enum LinkedRoutingConfigRetrieveResponse {
MerchantAccountBased(Box<RoutingRetrieveResponse>),
ProfileBased(Vec<RoutingDictionaryRecord>),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
/// Routing Algorithm specific to merchants
pub struct MerchantRoutingAlgorithm {
#[schema(value_type = String)]
pub id: common_utils::id_type::RoutingId,
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
pub name: String,
pub description: String,
pub algorithm: RoutingAlgorithmWrapper,
pub created_at: i64,
pub modified_at: i64,
pub algorithm_for: TransactionType,
}
impl EuclidDirFilter for ConnectorSelection {
const ALLOWED: &'static [DirKeyKind] = &[
DirKeyKind::PaymentMethod,
DirKeyKind::CardBin,
DirKeyKind::CardType,
DirKeyKind::CardNetwork,
DirKeyKind::PayLaterType,
DirKeyKind::WalletType,
DirKeyKind::UpiType,
DirKeyKind::BankRedirectType,
DirKeyKind::BankDebitType,
DirKeyKind::CryptoType,
DirKeyKind::MetaData,
DirKeyKind::PaymentAmount,
DirKeyKind::PaymentCurrency,
DirKeyKind::AuthenticationType,
DirKeyKind::MandateAcceptanceType,
DirKeyKind::MandateType,
DirKeyKind::PaymentType,
DirKeyKind::SetupFutureUsage,
DirKeyKind::CaptureMethod,
DirKeyKind::BillingCountry,
DirKeyKind::BusinessCountry,
DirKeyKind::BusinessLabel,
DirKeyKind::MetaData,
DirKeyKind::RewardType,
DirKeyKind::VoucherType,
DirKeyKind::CardRedirectType,
DirKeyKind::BankTransferType,
DirKeyKind::RealTimePaymentType,
];
}
impl EuclidAnalysable for ConnectorSelection {
fn get_dir_value_for_analysis(
&self,
rule_name: String,
) -> Vec<(euclid::frontend::dir::DirValue, euclid::types::Metadata)> {
self.get_connector_list()
.into_iter()
.map(|connector_choice| {
let connector_name = connector_choice.connector.to_string();
let mca_id = connector_choice.merchant_connector_id.clone();
(
euclid::frontend::dir::DirValue::Connector(Box::new(connector_choice.into())),
std::collections::HashMap::from_iter([(
"CONNECTOR_SELECTION".to_string(),
serde_json::json!({
"rule_name": rule_name,
"connector_name": connector_name,
"mca_id": mca_id,
}),
)]),
)
})
.collect()
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq)]
pub struct ConnectorVolumeSplit {
pub connector: RoutableConnectorChoice,
pub split: u8,
}
/// Routable Connector chosen for a payment
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(from = "RoutableChoiceSerde", into = "RoutableChoiceSerde")]
pub struct RoutableConnectorChoice {
#[serde(skip)]
pub choice_kind: RoutableChoiceKind,
pub connector: RoutableConnectors,
#[schema(value_type = Option<String>)]
pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
}
#[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, PartialEq)]
pub enum RoutableChoiceKind {
OnlyConnector,
FullStruct,
}
#[derive(Debug, serde::Deserialize, serde::Serialize)]
#[serde(untagged)]
pub enum RoutableChoiceSerde {
OnlyConnector(Box<RoutableConnectors>),
FullStruct {
connector: RoutableConnectors,
merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>,
},
}
impl std::fmt::Display for RoutableConnectorChoice {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let base = self.connector.to_string();
if let Some(mca_id) = &self.merchant_connector_id {
return write!(f, "{}:{}", base, mca_id.get_string_repr());
}
write!(f, "{base}")
}
}
impl From<RoutableConnectorChoice> for ast::ConnectorChoice {
fn from(value: RoutableConnectorChoice) -> Self {
Self {
connector: value.connector,
}
}
}
impl PartialEq for RoutableConnectorChoice {
fn eq(&self, other: &Self) -> bool {
self.connector.eq(&other.connector)
&& self.merchant_connector_id.eq(&other.merchant_connector_id)
}
}
impl Eq for RoutableConnectorChoice {}
impl From<RoutableChoiceSerde> for RoutableConnectorChoice {
fn from(value: RoutableChoiceSerde) -> Self {
match value {
RoutableChoiceSerde::OnlyConnector(connector) => Self {
choice_kind: RoutableChoiceKind::OnlyConnector,
connector: *connector,
merchant_connector_id: None,
},
RoutableChoiceSerde::FullStruct {
connector,
merchant_connector_id,
} => Self {
choice_kind: RoutableChoiceKind::FullStruct,
connector,
merchant_connector_id,
},
}
}
}
impl From<RoutableConnectorChoice> for RoutableChoiceSerde {
fn from(value: RoutableConnectorChoice) -> Self {
match value.choice_kind {
RoutableChoiceKind::OnlyConnector => Self::OnlyConnector(Box::new(value.connector)),
RoutableChoiceKind::FullStruct => Self::FullStruct {
connector: value.connector,
merchant_connector_id: value.merchant_connector_id,
},
}
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
pub struct RoutableConnectorChoiceWithStatus {
pub routable_connector_choice: RoutableConnectorChoice,
pub status: bool,
}
impl RoutableConnectorChoiceWithStatus {
pub fn new(routable_connector_choice: RoutableConnectorChoice, status: bool) -> Self {
Self {
routable_connector_choice,
status,
}
}
}
#[derive(
Debug, Copy, Clone, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, ToSchema,
)]
#[serde(rename_all = "snake_case")]
#[strum(serialize_all = "snake_case")]
pub enum RoutingAlgorithmKind {
Single,
Priority,
VolumeSplit,
Advanced,
Dynamic,
ThreeDsDecisionRule,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingPayloadWrapper {
pub updated_config: Vec<RoutableConnectorChoice>,
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(untagged)]
pub enum RoutingAlgorithmWrapper {
Static(StaticRoutingAlgorithm),
Dynamic(DynamicRoutingAlgorithm),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(untagged)]
pub enum DynamicRoutingAlgorithm {
EliminationBasedAlgorithm(EliminationRoutingConfig),
SuccessBasedAlgorithm(SuccessBasedRoutingConfig),
ContractBasedAlgorithm(ContractBasedRoutingConfig),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(
tag = "type",
content = "data",
rename_all = "snake_case",
try_from = "RoutingAlgorithmSerde"
)]
pub enum StaticRoutingAlgorithm {
Single(Box<RoutableConnectorChoice>),
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
#[schema(value_type=ProgramConnectorSelection)]
Advanced(Program<ConnectorSelection>),
#[schema(value_type=ProgramThreeDsDecisionRule)]
ThreeDsDecisionRule(Program<ThreeDSDecisionRule>),
}
#[derive(Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct ProgramThreeDsDecisionRule {
pub default_selection: ThreeDSDecisionRule,
#[schema(value_type = RuleThreeDsDecisionRule)]
pub rules: Vec<ast::Rule<ThreeDSDecisionRule>>,
#[schema(value_type = HashMap<String, serde_json::Value>)]
pub metadata: std::collections::HashMap<String, serde_json::Value>,
}
#[derive(Clone, Debug, Serialize, Deserialize, ToSchema)]
#[serde(rename_all = "camelCase")]
pub struct RuleThreeDsDecisionRule {
pub name: String,
pub connector_selection: ThreeDSDecision,
#[schema(value_type = Vec<IfStatement>)]
pub statements: Vec<ast::IfStatement>,
}
impl StaticRoutingAlgorithm {
pub fn should_validate_connectors_in_routing_config(&self) -> bool {
match self {
Self::Single(_) | Self::Priority(_) | Self::VolumeSplit(_) | Self::Advanced(_) => true,
Self::ThreeDsDecisionRule(_) => false,
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum RoutingAlgorithmSerde {
Single(Box<RoutableConnectorChoice>),
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
Advanced(Program<ConnectorSelection>),
ThreeDsDecisionRule(Program<ThreeDSDecisionRule>),
}
impl TryFrom<RoutingAlgorithmSerde> for StaticRoutingAlgorithm {
type Error = error_stack::Report<ParsingError>;
fn try_from(value: RoutingAlgorithmSerde) -> Result<Self, Self::Error> {
match &value {
RoutingAlgorithmSerde::Priority(i) if i.is_empty() => {
Err(ParsingError::StructParseFailure(
"Connectors list can't be empty for Priority Algorithm",
))?
}
RoutingAlgorithmSerde::VolumeSplit(i) if i.is_empty() => {
Err(ParsingError::StructParseFailure(
"Connectors list can't be empty for Volume split Algorithm",
))?
}
_ => {}
};
Ok(match value {
RoutingAlgorithmSerde::Single(i) => Self::Single(i),
RoutingAlgorithmSerde::Priority(i) => Self::Priority(i),
RoutingAlgorithmSerde::VolumeSplit(i) => Self::VolumeSplit(i),
RoutingAlgorithmSerde::Advanced(i) => Self::Advanced(i),
RoutingAlgorithmSerde::ThreeDsDecisionRule(i) => Self::ThreeDsDecisionRule(i),
})
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq)]
#[serde(
tag = "type",
content = "data",
rename_all = "snake_case",
try_from = "StraightThroughAlgorithmSerde",
into = "StraightThroughAlgorithmSerde"
)]
pub enum StraightThroughAlgorithm {
#[schema(title = "Single")]
Single(Box<RoutableConnectorChoice>),
#[schema(title = "Priority")]
Priority(Vec<RoutableConnectorChoice>),
#[schema(title = "VolumeSplit")]
VolumeSplit(Vec<ConnectorVolumeSplit>),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum StraightThroughAlgorithmInner {
Single(Box<RoutableConnectorChoice>),
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplit>),
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(untagged)]
pub enum StraightThroughAlgorithmSerde {
Direct(StraightThroughAlgorithmInner),
Nested {
algorithm: StraightThroughAlgorithmInner,
},
}
impl TryFrom<StraightThroughAlgorithmSerde> for StraightThroughAlgorithm {
type Error = error_stack::Report<ParsingError>;
fn try_from(value: StraightThroughAlgorithmSerde) -> Result<Self, Self::Error> {
let inner = match value {
StraightThroughAlgorithmSerde::Direct(algorithm) => algorithm,
StraightThroughAlgorithmSerde::Nested { algorithm } => algorithm,
};
match &inner {
StraightThroughAlgorithmInner::Priority(i) if i.is_empty() => {
Err(ParsingError::StructParseFailure(
"Connectors list can't be empty for Priority Algorithm",
))?
}
StraightThroughAlgorithmInner::VolumeSplit(i) if i.is_empty() => {
Err(ParsingError::StructParseFailure(
"Connectors list can't be empty for Volume split Algorithm",
))?
}
_ => {}
};
Ok(match inner {
StraightThroughAlgorithmInner::Single(single) => Self::Single(single),
StraightThroughAlgorithmInner::Priority(plist) => Self::Priority(plist),
StraightThroughAlgorithmInner::VolumeSplit(vsplit) => Self::VolumeSplit(vsplit),
})
}
}
impl From<StraightThroughAlgorithm> for StraightThroughAlgorithmSerde {
fn from(value: StraightThroughAlgorithm) -> Self {
let inner = match value {
StraightThroughAlgorithm::Single(conn) => StraightThroughAlgorithmInner::Single(conn),
StraightThroughAlgorithm::Priority(plist) => {
StraightThroughAlgorithmInner::Priority(plist)
}
StraightThroughAlgorithm::VolumeSplit(vsplit) => {
StraightThroughAlgorithmInner::VolumeSplit(vsplit)
}
};
Self::Nested { algorithm: inner }
}
}
impl From<StraightThroughAlgorithm> for StaticRoutingAlgorithm {
fn from(value: StraightThroughAlgorithm) -> Self {
match value {
StraightThroughAlgorithm::Single(conn) => Self::Single(conn),
StraightThroughAlgorithm::Priority(conns) => Self::Priority(conns),
StraightThroughAlgorithm::VolumeSplit(splits) => Self::VolumeSplit(splits),
}
}
}
impl StaticRoutingAlgorithm {
pub fn get_kind(&self) -> RoutingAlgorithmKind {
match self {
Self::Single(_) => RoutingAlgorithmKind::Single,
Self::Priority(_) => RoutingAlgorithmKind::Priority,
Self::VolumeSplit(_) => RoutingAlgorithmKind::VolumeSplit,
Self::Advanced(_) => RoutingAlgorithmKind::Advanced,
Self::ThreeDsDecisionRule(_) => RoutingAlgorithmKind::ThreeDsDecisionRule,
}
}
}
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingAlgorithmRef {
pub algorithm_id: Option<common_utils::id_type::RoutingId>,
pub timestamp: i64,
pub config_algo_id: Option<String>,
pub surcharge_config_algo_id: Option<String>,
}
impl RoutingAlgorithmRef {
pub fn update_algorithm_id(&mut self, new_id: common_utils::id_type::RoutingId) {
self.algorithm_id = Some(new_id);
self.timestamp = common_utils::date_time::now_unix_timestamp();
}
pub fn update_conditional_config_id(&mut self, ids: String) {
self.config_algo_id = Some(ids);
self.timestamp = common_utils::date_time::now_unix_timestamp();
}
pub fn update_surcharge_config_id(&mut self, ids: String) {
self.surcharge_config_algo_id = Some(ids);
self.timestamp = common_utils::date_time::now_unix_timestamp();
}
pub fn parse_routing_algorithm(
value: Option<pii::SecretSerdeValue>,
) -> Result<Option<Self>, error_stack::Report<ParsingError>> {
value
.map(|val| val.parse_value::<Self>("RoutingAlgorithmRef"))
.transpose()
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct RoutingDictionaryRecord {
#[schema(value_type = String)]
pub id: common_utils::id_type::RoutingId,
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
pub name: String,
pub kind: RoutingAlgorithmKind,
pub description: String,
pub created_at: i64,
pub modified_at: i64,
pub algorithm_for: Option<TransactionType>,
pub decision_engine_routing_id: Option<String>,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct RoutingDictionary {
#[schema(value_type = String)]
pub merchant_id: common_utils::id_type::MerchantId,
pub active_id: Option<String>,
pub records: Vec<RoutingDictionaryRecord>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)]
#[serde(untagged)]
pub enum RoutingKind {
Config(RoutingDictionary),
RoutingAlgorithm(Vec<RoutingDictionaryRecord>),
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
pub struct RoutingAlgorithmId {
#[schema(value_type = String)]
pub routing_algorithm_id: common_utils::id_type::RoutingId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingLinkWrapper {
pub profile_id: common_utils::id_type::ProfileId,
pub algorithm_id: RoutingAlgorithmId,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct DynamicAlgorithmWithTimestamp<T> {
pub algorithm_id: Option<T>,
pub timestamp: i64,
}
impl<T> DynamicAlgorithmWithTimestamp<T> {
pub fn new(algorithm_id: Option<T>) -> Self {
Self {
algorithm_id,
timestamp: common_utils::date_time::now_unix_timestamp(),
}
}
}
#[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)]
pub struct DynamicRoutingAlgorithmRef {
pub success_based_algorithm: Option<SuccessBasedAlgorithm>,
pub dynamic_routing_volume_split: Option<u8>,
pub elimination_routing_algorithm: Option<EliminationRoutingAlgorithm>,
pub contract_based_routing: Option<ContractRoutingAlgorithm>,
#[serde(default)]
pub is_merchant_created_in_decision_engine: bool,
}
pub trait DynamicRoutingAlgoAccessor {
fn get_algorithm_id_with_timestamp(
self,
) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>;
fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures;
}
impl DynamicRoutingAlgoAccessor for SuccessBasedAlgorithm {
fn get_algorithm_id_with_timestamp(
self,
) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> {
self.algorithm_id_with_timestamp
}
fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures {
&mut self.enabled_feature
}
}
impl DynamicRoutingAlgoAccessor for EliminationRoutingAlgorithm {
fn get_algorithm_id_with_timestamp(
self,
) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> {
self.algorithm_id_with_timestamp
}
fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures {
&mut self.enabled_feature
}
}
impl DynamicRoutingAlgoAccessor for ContractRoutingAlgorithm {
fn get_algorithm_id_with_timestamp(
self,
) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> {
self.algorithm_id_with_timestamp
}
fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures {
&mut self.enabled_feature
}
}
impl EliminationRoutingAlgorithm {
pub fn new(
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
common_utils::id_type::RoutingId,
>,
) -> Self {
Self {
algorithm_id_with_timestamp,
enabled_feature: DynamicRoutingFeatures::None,
}
}
}
impl SuccessBasedAlgorithm {
pub fn new(
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<
common_utils::id_type::RoutingId,
>,
) -> Self {
Self {
algorithm_id_with_timestamp,
enabled_feature: DynamicRoutingFeatures::None,
}
}
}
impl DynamicRoutingAlgorithmRef {
pub fn update(&mut self, new: Self) {
if let Some(elimination_routing_algorithm) = new.elimination_routing_algorithm {
self.elimination_routing_algorithm = Some(elimination_routing_algorithm)
}
if let Some(success_based_algorithm) = new.success_based_algorithm {
self.success_based_algorithm = Some(success_based_algorithm)
}
if let Some(contract_based_routing) = new.contract_based_routing {
self.contract_based_routing = Some(contract_based_routing)
}
}
pub fn update_enabled_features(
&mut self,
algo_type: DynamicRoutingType,
feature_to_enable: DynamicRoutingFeatures,
) {
match algo_type {
DynamicRoutingType::SuccessRateBasedRouting => {
self.success_based_algorithm
.as_mut()
.map(|algo| algo.enabled_feature = feature_to_enable);
}
DynamicRoutingType::EliminationRouting => {
self.elimination_routing_algorithm
.as_mut()
.map(|algo| algo.enabled_feature = feature_to_enable);
}
DynamicRoutingType::ContractBasedRouting => {
self.contract_based_routing
.as_mut()
.map(|algo| algo.enabled_feature = feature_to_enable);
}
}
}
pub fn update_volume_split(&mut self, volume: Option<u8>) {
self.dynamic_routing_volume_split = volume
}
pub fn update_merchant_creation_status_in_decision_engine(&mut self, is_created: bool) {
self.is_merchant_created_in_decision_engine = is_created;
}
pub fn is_success_rate_routing_enabled(&self) -> bool {
self.success_based_algorithm
.as_ref()
.map(|success_based_routing| {
success_based_routing.enabled_feature
== DynamicRoutingFeatures::DynamicConnectorSelection
|| success_based_routing.enabled_feature == DynamicRoutingFeatures::Metrics
})
.unwrap_or_default()
}
pub fn is_elimination_enabled(&self) -> bool {
self.elimination_routing_algorithm
.as_ref()
.map(|elimination_routing| {
elimination_routing.enabled_feature
== DynamicRoutingFeatures::DynamicConnectorSelection
|| elimination_routing.enabled_feature == DynamicRoutingFeatures::Metrics
})
.unwrap_or_default()
}
}
#[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize)]
pub struct RoutingVolumeSplit {
pub routing_type: RoutingType,
pub split: u8,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct RoutingVolumeSplitWrapper {
pub routing_info: RoutingVolumeSplit,
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, Eq, PartialEq)]
#[serde(rename_all = "snake_case")]
pub enum RoutingType {
#[default]
Static,
Dynamic,
}
impl RoutingType {
pub fn is_dynamic_routing(self) -> bool {
self == Self::Dynamic
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct SuccessBasedAlgorithm {
pub algorithm_id_with_timestamp:
DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>,
#[serde(default)]
pub enabled_feature: DynamicRoutingFeatures,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ContractRoutingAlgorithm {
pub algorithm_id_with_timestamp:
DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>,
#[serde(default)]
pub enabled_feature: DynamicRoutingFeatures,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct EliminationRoutingAlgorithm {
pub algorithm_id_with_timestamp:
DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>,
#[serde(default)]
pub enabled_feature: DynamicRoutingFeatures,
}
impl EliminationRoutingAlgorithm {
pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) {
self.enabled_feature = feature_to_enable
}
}
impl SuccessBasedAlgorithm {
pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) {
self.enabled_feature = feature_to_enable
}
}
impl DynamicRoutingAlgorithmRef {
pub fn update_algorithm_id(
&mut self,
new_id: common_utils::id_type::RoutingId,
enabled_feature: DynamicRoutingFeatures,
dynamic_routing_type: DynamicRoutingType,
) {
match dynamic_routing_type {
DynamicRoutingType::SuccessRateBasedRouting => {
self.success_based_algorithm = Some(SuccessBasedAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)),
enabled_feature,
})
}
DynamicRoutingType::EliminationRouting => {
self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)),
enabled_feature,
})
}
DynamicRoutingType::ContractBasedRouting => {
self.contract_based_routing = Some(ContractRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)),
enabled_feature,
})
}
};
}
pub fn update_feature(
&mut self,
enabled_feature: DynamicRoutingFeatures,
dynamic_routing_type: DynamicRoutingType,
) {
match dynamic_routing_type {
DynamicRoutingType::SuccessRateBasedRouting => {
self.success_based_algorithm = Some(SuccessBasedAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature,
})
}
DynamicRoutingType::EliminationRouting => {
self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature,
})
}
DynamicRoutingType::ContractBasedRouting => {
self.contract_based_routing = Some(ContractRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature,
})
}
};
}
pub fn disable_algorithm_id(&mut self, dynamic_routing_type: DynamicRoutingType) {
match dynamic_routing_type {
DynamicRoutingType::SuccessRateBasedRouting => {
if let Some(success_based_algo) = &self.success_based_algorithm {
self.success_based_algorithm = Some(SuccessBasedAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: success_based_algo.enabled_feature,
});
}
}
DynamicRoutingType::EliminationRouting => {
if let Some(elimination_based_algo) = &self.elimination_routing_algorithm {
self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: elimination_based_algo.enabled_feature,
});
}
}
DynamicRoutingType::ContractBasedRouting => {
if let Some(contract_based_algo) = &self.contract_based_routing {
self.contract_based_routing = Some(ContractRoutingAlgorithm {
algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None),
enabled_feature: contract_based_algo.enabled_feature,
});
}
}
}
}
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct ToggleDynamicRoutingQuery {
pub enable: DynamicRoutingFeatures,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct CreateDynamicRoutingQuery {
pub enable: DynamicRoutingFeatures,
}
#[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct DynamicRoutingVolumeSplitQuery {
pub split: u8,
}
#[derive(
Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema,
)]
#[serde(rename_all = "snake_case")]
pub enum DynamicRoutingFeatures {
Metrics,
DynamicConnectorSelection,
#[default]
None,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
pub struct DynamicRoutingUpdateConfigQuery {
#[schema(value_type = String)]
pub algorithm_id: common_utils::id_type::RoutingId,
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct ToggleDynamicRoutingWrapper {
pub profile_id: common_utils::id_type::ProfileId,
pub feature_to_enable: DynamicRoutingFeatures,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct ToggleDynamicRoutingPath {
#[schema(value_type = String)]
pub profile_id: common_utils::id_type::ProfileId,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct CreateDynamicRoutingWrapper {
pub profile_id: common_utils::id_type::ProfileId,
pub feature_to_enable: DynamicRoutingFeatures,
pub payload: DynamicRoutingPayload,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum DynamicRoutingPayload {
SuccessBasedRoutingPayload(SuccessBasedRoutingConfig),
EliminationRoutingPayload(EliminationRoutingConfig),
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct RoutingVolumeSplitResponse {
pub split: u8,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct EliminationRoutingConfig {
pub params: Option<Vec<DynamicRoutingConfigParams>>,
pub elimination_analyser_config: Option<EliminationAnalyserConfig>,
#[schema(value_type = DecisionEngineEliminationData)]
pub decision_engine_configs: Option<open_router::DecisionEngineEliminationData>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct EliminationAnalyserConfig {
pub bucket_size: Option<u64>,
pub bucket_leak_interval_in_secs: Option<u64>,
}
impl EliminationAnalyserConfig {
pub fn update(&mut self, new: Self) {
if let Some(bucket_size) = new.bucket_size {
self.bucket_size = Some(bucket_size)
}
if let Some(bucket_leak_interval_in_secs) = new.bucket_leak_interval_in_secs {
self.bucket_leak_interval_in_secs = Some(bucket_leak_interval_in_secs)
}
}
}
impl Default for EliminationRoutingConfig {
fn default() -> Self {
Self {
params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]),
elimination_analyser_config: Some(EliminationAnalyserConfig {
bucket_size: Some(5),
bucket_leak_interval_in_secs: Some(60),
}),
decision_engine_configs: None,
}
}
}
impl EliminationRoutingConfig {
pub fn update(&mut self, new: Self) {
if let Some(params) = new.params {
self.params = Some(params)
}
if let Some(new_config) = new.elimination_analyser_config {
self.elimination_analyser_config
.as_mut()
.map(|config| config.update(new_config));
}
if let Some(new_config) = new.decision_engine_configs {
self.decision_engine_configs
.as_mut()
.map(|config| config.update(new_config));
}
}
pub fn open_router_config_default() -> Self {
Self {
elimination_analyser_config: None,
params: None,
decision_engine_configs: Some(open_router::DecisionEngineEliminationData {
threshold: DEFAULT_ELIMINATION_THRESHOLD,
}),
}
}
pub fn get_decision_engine_configs(
&self,
) -> Result<open_router::DecisionEngineEliminationData, error_stack::Report<ValidationError>>
{
self.decision_engine_configs
.clone()
.ok_or(error_stack::Report::new(
ValidationError::MissingRequiredField {
field_name: "decision_engine_configs".to_string(),
},
))
}
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
#[serde(deny_unknown_fields)]
pub struct SuccessBasedRoutingConfig {
pub params: Option<Vec<DynamicRoutingConfigParams>>,
pub config: Option<SuccessBasedRoutingConfigBody>,
#[schema(value_type = DecisionEngineSuccessRateData)]
pub decision_engine_configs: Option<open_router::DecisionEngineSuccessRateData>,
}
impl Default for SuccessBasedRoutingConfig {
fn default() -> Self {
Self {
params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]),
config: Some(SuccessBasedRoutingConfigBody {
min_aggregates_size: Some(5),
default_success_rate: Some(100.0),
max_aggregates_size: Some(8),
current_block_threshold: Some(CurrentBlockThreshold {
duration_in_mins: None,
max_total_count: Some(5),
}),
specificity_level: SuccessRateSpecificityLevel::default(),
exploration_percent: Some(20.0),
shuffle_on_tie_during_exploitation: Some(false),
}),
decision_engine_configs: None,
}
}
}
#[derive(
serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, PartialEq, strum::Display,
)]
pub enum DynamicRoutingConfigParams {
PaymentMethod,
PaymentMethodType,
AuthenticationType,
Currency,
Country,
CardNetwork,
CardBin,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
pub struct SuccessBasedRoutingConfigBody {
pub min_aggregates_size: Option<u32>,
pub default_success_rate: Option<f64>,
pub max_aggregates_size: Option<u32>,
pub current_block_threshold: Option<CurrentBlockThreshold>,
#[serde(default)]
pub specificity_level: SuccessRateSpecificityLevel,
pub exploration_percent: Option<f64>,
pub shuffle_on_tie_during_exploitation: Option<bool>,
}
#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)]
pub struct CurrentBlockThreshold {
pub duration_in_mins: Option<u64>,
pub max_total_count: Option<u64>,
}
|
crates/api_models/src/routing.rs#chunk0
|
api_models
|
chunk
| 8,188
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn fetch_consumer_tasks(
db: &dyn ProcessTrackerInterface,
redis_conn: &RedisConnectionPool,
stream_name: &str,
group_name: &str,
consumer_name: &str,
) -> CustomResult<Vec<storage::ProcessTracker>, errors::ProcessTrackerError> {
let batches = pt_utils::get_batches(redis_conn, stream_name, group_name, consumer_name).await?;
// Returning early to avoid execution of database queries when `batches` is empty
if batches.is_empty() {
return Ok(Vec::new());
}
let mut tasks = batches.into_iter().fold(Vec::new(), |mut acc, batch| {
acc.extend_from_slice(
batch
.trackers
.into_iter()
.filter(|task| task.is_valid_business_status(&valid_business_statuses()))
.collect::<Vec<_>>()
.as_slice(),
);
acc
});
let task_ids = tasks
.iter()
.map(|task| task.id.to_owned())
.collect::<Vec<_>>();
db.process_tracker_update_process_status_by_ids(
task_ids,
storage::ProcessTrackerUpdate::StatusUpdate {
status: enums::ProcessTrackerStatus::ProcessStarted,
business_status: None,
},
)
.await
.change_context(errors::ProcessTrackerError::ProcessFetchingFailed)?;
tasks
.iter_mut()
.for_each(|x| x.status = enums::ProcessTrackerStatus::ProcessStarted);
Ok(tasks)
}
|
crates/scheduler/src/consumer.rs
|
scheduler
|
function_signature
| 322
|
rust
| null | null | null | null |
fetch_consumer_tasks
| null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.MerchantRecipientData
{
"oneOf": [
{
"type": "object",
"required": [
"connector_recipient_id"
],
"properties": {
"connector_recipient_id": {
"type": "string",
"nullable": true
}
}
},
{
"type": "object",
"required": [
"wallet_id"
],
"properties": {
"wallet_id": {
"type": "string",
"nullable": true
}
}
},
{
"type": "object",
"required": [
"account_data"
],
"properties": {
"account_data": {
"$ref": "#/components/schemas/MerchantAccountData"
}
}
}
]
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 181
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"MerchantRecipientData"
] | null | null | null | null |
**Full Changelog:** [`2024.03.13.0...2024.03.13.1`](https://github.com/juspay/hyperswitch/compare/2024.03.13.0...2024.03.13.1)
- - -
## 2024.03.13.0
### Features
- **connector:** [AUTHORIZEDOTNET] Audit Connector ([#4035](https://github.com/juspay/hyperswitch/pull/4035)) ([`7840bdb`](https://github.com/juspay/hyperswitch/commit/7840bdb95f90065f3f6d671b07c3044e77740ed2))
- **core:** Confirm flow and authorization api changes for external authentication ([#4015](https://github.com/juspay/hyperswitch/pull/4015)) ([`ce3625c`](https://github.com/juspay/hyperswitch/commit/ce3625cb0cdccc750a073c012f0e541b014c3190))
- **global-search:** Dashboard globalsearch apis ([#3831](https://github.com/juspay/hyperswitch/pull/3831)) ([`ac8ddd4`](https://github.com/juspay/hyperswitch/commit/ac8ddd40208f3da5f65ca97bf5033cea5ca3ebe3))
### Bug Fixes
- **connector:** [Adyen] update config and add required fields ([#4046](https://github.com/juspay/hyperswitch/pull/4046)) ([`16d73cb`](https://github.com/juspay/hyperswitch/commit/16d73cb5f9f469d791f8880f3a2fd79135c821cd))
- **core:** [REFUNDS] Fix Not Supported Connector Error ([#4045](https://github.com/juspay/hyperswitch/pull/4045)) ([`7513423`](https://github.com/juspay/hyperswitch/commit/7513423631ddf0fe86ef656ec6cad76d82c807bc))
### Refactors
- **address:** Pass payment method billing to the connector module ([#3828](https://github.com/juspay/hyperswitch/pull/3828)) ([`195c700`](https://github.com/juspay/hyperswitch/commit/195c700e6c88e457cecc0722a7e5990db1379f22))
- **connector:** [Checkout] remove Paypal from wasm ([#4044](https://github.com/juspay/hyperswitch/pull/4044)) ([`3eff4eb`](https://github.com/juspay/hyperswitch/commit/3eff4ebd3a60b5831cbec0158527475c8f7d7eb4))
- **openai:** Update open-api spec to have payment changes ([#4043](https://github.com/juspay/hyperswitch/pull/4043)) ([`708cce9`](https://github.com/juspay/hyperswitch/commit/708cce926125a29b406db48cf0ebd35b217927d4))
- **payment_methods:**
- Filter wallet payment method from mca based on customer pm ([#4038](https://github.com/juspay/hyperswitch/pull/4038)) ([`abe9c2a`](https://github.com/juspay/hyperswitch/commit/abe9c2ac17a0783f3625dd7fde5d28e285012ec3))
- Allow deletion of default payment method for a customer if only one pm exists ([#4027](https://github.com/juspay/hyperswitch/pull/4027)) ([`45ed56f`](https://github.com/juspay/hyperswitch/commit/45ed56f16516c44acbe75b75c0621b78ccdb9894))
- [Checkout] change payment and webhooks API contract ([#4023](https://github.com/juspay/hyperswitch/pull/4023)) ([`733a560`](https://github.com/juspay/hyperswitch/commit/733a560146bb06e51fa4ee7ed9b6d1d3d9eddf12))
**Full Changelog:** [`2024.03.12.0...2024.03.13.0`](https://github.com/juspay/hyperswitch/compare/2024.03.12.0...2024.03.13.0)
- - -
## 2024.03.12.0
### Refactors
- **core:** Status handling for payment_method_status ([#3965](https://github.com/juspay/hyperswitch/pull/3965)) ([`e87f2ea`](https://github.com/juspay/hyperswitch/commit/e87f2ea8c5669473940df8bc2f5c61fdf3f218ff))
### Miscellaneous Tasks
- Add threedsecureio base url in deployment config files ([#4039](https://github.com/juspay/hyperswitch/pull/4039)) ([`d9f8423`](https://github.com/juspay/hyperswitch/commit/d9f84232a4a29814a1f9a792ebc74923862a1da6))
**Full Changelog:** [`2024.03.11.1...2024.03.12.0`](https://github.com/juspay/hyperswitch/compare/2024.03.11.1...2024.03.12.0)
- - -
## 2024.03.11.1
### Features
- **router:** Add routing support for token-based mit payments ([#4012](https://github.com/juspay/hyperswitch/pull/4012)) ([`43ebfbc`](https://github.com/juspay/hyperswitch/commit/43ebfbc47f03eaaaf274847290861dcb00db26a5))
- **users:** Implemented Set-Cookie ([#3865](https://github.com/juspay/hyperswitch/pull/3865)) ([`44eef46`](https://github.com/juspay/hyperswitch/commit/44eef46e5d7f0a198be80602ceae1c843449319c))
### Refactors
- **connector:**
- [Multisafepay] Mask PII data ([#3869](https://github.com/juspay/hyperswitch/pull/3869)) ([`c2b1561`](https://github.com/juspay/hyperswitch/commit/c2b15615e3c61e6f497180be8fa66d008ed150bb))
- [Globalpay] Mask PII data ([#3840](https://github.com/juspay/hyperswitch/pull/3840)) ([`13f6d6c`](https://github.com/juspay/hyperswitch/commit/13f6d6c10ce421329a7eb8b494fbb3bd31aed91f))
- [Iatapay] Mask PII data ([#3850](https://github.com/juspay/hyperswitch/pull/3850)) ([`bd7accb`](https://github.com/juspay/hyperswitch/commit/bd7accb2c250b5f330b6bbb87f6f6edf4a479a61))
- [Payme][Payeezy] Mask PII data ([#3926](https://github.com/juspay/hyperswitch/pull/3926)) ([`ffcb2bc`](https://github.com/juspay/hyperswitch/commit/ffcb2bcf2b7a26d8fc7fc45f9878d41ba74d2fe0))
- [Nexinets] Mask PII data ([#3874](https://github.com/juspay/hyperswitch/pull/3874)) ([`9ea5310`](https://github.com/juspay/hyperswitch/commit/9ea531068d87b76e8f41ee7d9e9d26fd755bced4))
- [Noon] Mask PII data ([#3879](https://github.com/juspay/hyperswitch/pull/3879)) ([`96efc2a`](https://github.com/juspay/hyperswitch/commit/96efc2abf94e3e9174f625bee2270236bad50278))
- [stripe] capture error_code and error_message for psync ([#3771](https://github.com/juspay/hyperswitch/pull/3771)) ([`614182a`](https://github.com/juspay/hyperswitch/commit/614182ae4cdc7a762e0ce90d1336b1ff16fc9fa3))
- [Trustpay][Volt] Mask PII data ([#3932](https://github.com/juspay/hyperswitch/pull/3932)) ([`a179b9c`](https://github.com/juspay/hyperswitch/commit/a179b9c90c2b9a419f1ce394d06158f80c29ee45))
- [Nuvie] Mask PII data ([#3924](https://github.com/juspay/hyperswitch/pull/3924)) ([`6b2f71c`](https://github.com/juspay/hyperswitch/commit/6b2f71c850ff2ea36365375a81a7026fd8c87ebc))
- [adyen] add more fields in the payments request ([#4010](https://github.com/juspay/hyperswitch/pull/4010)) ([`5584f11`](https://github.com/juspay/hyperswitch/commit/5584f1131ae4180020be23d4c735b8356482c22d))
- **core:** Updated payments response with payment_method_id & payment_method_status ([#3883](https://github.com/juspay/hyperswitch/pull/3883)) ([`7391416`](https://github.com/juspay/hyperswitch/commit/7391416e2473eab0474bd01bb155a9ecc96da263))
**Full Changelog:** [`2024.03.11.0...2024.03.11.1`](https://github.com/juspay/hyperswitch/compare/2024.03.11.0...2024.03.11.1)
- - -
## 2024.03.11.0
### Features
- **connector:**
- Add threedsecureio three_ds authentication connector ([#4004](https://github.com/juspay/hyperswitch/pull/4004)) ([`06c3096`](https://github.com/juspay/hyperswitch/commit/06c30967cf626e7406aa9be8643fb73288aae383))
- [Checkout] add support for external authentication for checkout connector ([#4006](https://github.com/juspay/hyperswitch/pull/4006)) ([`142a22c`](https://github.com/juspay/hyperswitch/commit/142a22c752a7c623cee62a6d552e6ffda73df777))
- **router:** Add payments authentication api flow ([#3996](https://github.com/juspay/hyperswitch/pull/3996)) ([`41556ba`](https://github.com/juspay/hyperswitch/commit/41556baed98c59373e0a053c023c32f2f7346b51))
**Full Changelog:** [`2024.03.09.0...2024.03.11.0`](https://github.com/juspay/hyperswitch/compare/2024.03.09.0...2024.03.11.0)
- - -
## 2024.03.09.0
### Features
- **core:** Add core functions for external authentication ([#3969](https://github.com/juspay/hyperswitch/pull/3969)) ([`897e264`](https://github.com/juspay/hyperswitch/commit/897e264ad9e26df9877a18eef26a24e05de78528))
- **payment_link:** Add shimmer page before payment_link loads starts ([#4014](https://github.com/juspay/hyperswitch/pull/4014)) ([`ba9d465`](https://github.com/juspay/hyperswitch/commit/ba9d465483edcefeacc7ace0fc8efc86ca0f813c))
### Bug Fixes
- **deserialization:** Error message is different when invalid data is passed for payment method data ([#4022](https://github.com/juspay/hyperswitch/pull/4022)) ([`f1fe295`](https://github.com/juspay/hyperswitch/commit/f1fe295475adb0e827bd713be036687da662b361))
### Miscellaneous Tasks
- **postman:** Update Postman collection files ([`a7d0487`](https://github.com/juspay/hyperswitch/commit/a7d04873d63c1f007d0081f02ba9a373e24ae882))
**Full Changelog:** [`2024.03.08.0...2024.03.09.0`](https://github.com/juspay/hyperswitch/compare/2024.03.08.0...2024.03.09.0)
- - -
## 2024.03.08.0
### Features
- **router:** Add domain types, admin core changes and other prerequisites for 3ds external authentication flow ([#3962](https://github.com/juspay/hyperswitch/pull/3962)) ([`4902c40`](https://github.com/juspay/hyperswitch/commit/4902c403452500847f0395babc5fb940f4e2b755))
### Bug Fixes
- **deserialization:** Deserialize reward payment method data ([#4011](https://github.com/juspay/hyperswitch/pull/4011)) ([`f6b44f3`](https://github.com/juspay/hyperswitch/commit/f6b44f3860147a2ddc7b37123bfe064e50b7182a))
- **postman:** Fix postman collections for saving cards with customer_acceptance ([#4008](https://github.com/juspay/hyperswitch/pull/4008)) ([`deac899`](https://github.com/juspay/hyperswitch/commit/deac8991f78bd29d081088b0cf75a254eb358a2e))
- **webhooks:** Abort outgoing webhook retry task if webhook URL is not available in business profile ([#3997](https://github.com/juspay/hyperswitch/pull/3997)) ([`ce0ac3d`](https://github.com/juspay/hyperswitch/commit/ce0ac3d0297da5372772efe19167f0d2f62e82eb))
### Refactors
- **core:** Add OnSession as default for setup_future_usage ([#3990](https://github.com/juspay/hyperswitch/pull/3990)) ([`f9b6f5d`](https://github.com/juspay/hyperswitch/commit/f9b6f5da36c3a57da4b89db3151996403e2f3dfd))
### Miscellaneous Tasks
- **postman:** Update Postman collection files ([`d36702d`](https://github.com/juspay/hyperswitch/commit/d36702d270be2b7e3816954fbac4a320d8224f31))
**Full Changelog:** [`2024.03.07.1...2024.03.08.0`](https://github.com/juspay/hyperswitch/compare/2024.03.07.1...2024.03.08.0)
- - -
## 2024.03.07.1
### Features
- **users:** Add new API get the user and role details of specific user ([#3988](https://github.com/juspay/hyperswitch/pull/3988)) ([`ba42fba`](https://github.com/juspay/hyperswitch/commit/ba42fbaed0adb2a3e4d9f2d07a4f0d99ba227241))
### Bug Fixes
- **users:** Revert using mget in authorization ([#3999](https://github.com/juspay/hyperswitch/pull/3999)) ([`7375b86`](https://github.com/juspay/hyperswitch/commit/7375b866a2a2767df2f213bc9eb61268392fb60d))
### Refactors
- **router:** Store `ApplepayPaymentMethod` in `payment_method_data` column of `payment_attempt` table ([#3940](https://github.com/juspay/hyperswitch/pull/3940)) ([`6671bff`](https://github.com/juspay/hyperswitch/commit/6671bff3b11e9548a0085046d2594cad9f2571e2))
**Full Changelog:** [`2024.03.07.0...2024.03.07.1`](https://github.com/juspay/hyperswitch/compare/2024.03.07.0...2024.03.07.1)
- - -
## 2024.03.07.0
### Features
- **connector:** [AUTHORIZEDOTNET] Add billing address in payments request ([#3981](https://github.com/juspay/hyperswitch/pull/3981)) ([`3806cd3`](https://github.com/juspay/hyperswitch/commit/3806cd35c763cc4517b761b4e3b0e736c60fac9f))
- **core:** Store customer_acceptance in the payment_methods table ([#3885](https://github.com/juspay/hyperswitch/pull/3885)) ([`a1fd36a`](https://github.com/juspay/hyperswitch/commit/a1fd36a1abea4d400386a00ccf182dfe9da5bcda))
- **payment_method:** Set the initial payment method as default until its explicitly set ([#3970](https://github.com/juspay/hyperswitch/pull/3970)) ([`34c1b90`](https://github.com/juspay/hyperswitch/commit/34c1b905b178973d2611bab14c7d85582ed225f0))
- **payment_methods:** Store connector_mandate_details in PaymentMethods table ([#3907](https://github.com/juspay/hyperswitch/pull/3907)) ([`d220e81`](https://github.com/juspay/hyperswitch/commit/d220e815dc81925b205fb57d5d4f05883c1a7cde))
### Bug Fixes
- **connector:**
- [Trustpay] Add mapping to error code `100.390.105` ([#3968](https://github.com/juspay/hyperswitch/pull/3968)) ([`bf67587`](https://github.com/juspay/hyperswitch/commit/bf675878a2e36f7005468e91eefadc111ccba6b2))
- [adyen] handle Webhook reference and object ([#3976](https://github.com/juspay/hyperswitch/pull/3976)) ([`0aa40cb`](https://github.com/juspay/hyperswitch/commit/0aa40cbae75fd4cf5b13cfc518ff761b2b673246))
- **tests/postman/adyen:** Remove enabled payment methods for payouts processor ([#3913](https://github.com/juspay/hyperswitch/pull/3913)) ([`289b20a`](https://github.com/juspay/hyperswitch/commit/289b20a82e5ee32aae6eb4e5766f9c757d26345d))
- **user:**
- Use mget to check in blocklist ([#3945](https://github.com/juspay/hyperswitch/pull/3945)) ([`8154a61`](https://github.com/juspay/hyperswitch/commit/8154a611efcfa4bef3d5674db0574b065b55e9cd))
- Improve role validation to prevent duplicate groups ([#3949](https://github.com/juspay/hyperswitch/pull/3949)) ([`05a4752`](https://github.com/juspay/hyperswitch/commit/05a475271a2c37ba6ced90b85e53015c47d573bc))
### Refactors
- **connector:** [Checkout] handle default cases for dispute status mapping ([#3966](https://github.com/juspay/hyperswitch/pull/3966)) ([`2cda3dd`](https://github.com/juspay/hyperswitch/commit/2cda3dd794e51f84537a89e1015ee975322a2081))
- **payment_methods:**
- Filter applepay payment method from mca based on customer pm ([#3953](https://github.com/juspay/hyperswitch/pull/3953)) ([`2db39e8`](https://github.com/juspay/hyperswitch/commit/2db39e8bb9af3d55e3d075d77ff8616ee2e15f0a))
- Prevent deletion of default payment method for a customer ([#3964](https://github.com/juspay/hyperswitch/pull/3964)) ([`db39bb0`](https://github.com/juspay/hyperswitch/commit/db39bb0a3cf350e8399a7f17842d9af9b2de440e))
- Insert payment_method_id in redis for wallet tokens ([#3989](https://github.com/juspay/hyperswitch/pull/3989)) ([`d997e29`](https://github.com/juspay/hyperswitch/commit/d997e298f2614079a72a773493cd98ba4507b35a))
- Kms decrypt analytics config ([#3984](https://github.com/juspay/hyperswitch/pull/3984)) ([`cfade55`](https://github.com/juspay/hyperswitch/commit/cfade55e693594a772c18eee2c35d7b3dc03f84d))
### Miscellaneous Tasks
- **doc:** Add API ref for KV toggle ([#3784](https://github.com/juspay/hyperswitch/pull/3784)) ([`5e8fcda`](https://github.com/juspay/hyperswitch/commit/5e8fcda7d12f482e47be9ed672093cb45fac9e29))
- **postman:** Update Postman collection files ([`2db4a59`](https://github.com/juspay/hyperswitch/commit/2db4a599eae2560bfef327231f2381af74145e39))
**Full Changelog:** [`2024.03.06.0...2024.03.07.0`](https://github.com/juspay/hyperswitch/compare/2024.03.06.0...2024.03.07.0)
- - -
## 2024.03.06.0
### Features
- **api_models:** Add api_models for external 3ds authentication flow ([#3858](https://github.com/juspay/hyperswitch/pull/3858)) ([`0a43ceb`](https://github.com/juspay/hyperswitch/commit/0a43ceb14e27d998794941ecb7605b9e7175c757))
- **connector:** [Checkout] accept connector_transaction_id in 2xx and 4xx error_response of connector flows ([#3959](https://github.com/juspay/hyperswitch/pull/3959)) ([`f6f6a0c`](https://github.com/juspay/hyperswitch/commit/f6f6a0c0f727a6f367c6bafb4db9a89cb46f667a))
- **core:** External authentication related schema changes for existing tables ([#3904](https://github.com/juspay/hyperswitch/pull/3904)) ([`c09b2b3`](https://github.com/juspay/hyperswitch/commit/c09b2b3a2ae9a71d4a73063faf4796e0c8732bb4))
- **payouts:** Implement Single Connector Retry for Payouts ([#3908](https://github.com/juspay/hyperswitch/pull/3908)) ([`0cb95a4`](https://github.com/juspay/hyperswitch/commit/0cb95a4911054e089e6ed3c528645ee1b881ebc6))
- **roles:** Add caching for custom roles ([#3946](https://github.com/juspay/hyperswitch/pull/3946)) ([`19c5023`](https://github.com/juspay/hyperswitch/commit/19c502398f980d20b9e0a4fe98c33a2239c90c5b))
- **router:** Add incoming header request logs ([#3939](https://github.com/juspay/hyperswitch/pull/3939)) ([`050df50`](https://github.com/juspay/hyperswitch/commit/050df5022cd3d44db23ca75f81158fb7c2429f86))
### Bug Fixes
- **core:** Fix metadata validation for update payment connector ([#3834](https://github.com/juspay/hyperswitch/pull/3834)) ([`54938ad`](https://github.com/juspay/hyperswitch/commit/54938ad345a2b899360b608d8845fd7f885f82ba))
- **router:** [nuvei] Nuvei error handling for payment declined status and included tests ([#3832](https://github.com/juspay/hyperswitch/pull/3832)) ([`087932f`](https://github.com/juspay/hyperswitch/commit/087932f06044454570c971def0e82dc3d838598c))
### Refactors
- **connector:**
- [Fiserv] Mask PII data ([#3821](https://github.com/juspay/hyperswitch/pull/3821)) ([`03cfb73`](https://github.com/juspay/hyperswitch/commit/03cfb735af29f00bccf729013e7e06684611b30d))
- Remove default cases for Authorizedotnet, Braintree and Fiserv Connector ([#2796](https://github.com/juspay/hyperswitch/pull/2796)) ([`dbac556`](https://github.com/juspay/hyperswitch/commit/dbac55683a8f95e0efdbac43f8c2ae793063a032))
### Miscellaneous Tasks
- **configs:** [BOA] Add USD Currency Filter Configuration ([#3961](https://github.com/juspay/hyperswitch/pull/3961)) ([`8a0e468`](https://github.com/juspay/hyperswitch/commit/8a0e468e6a574717b29ccbdd143908727c251dfb))
- **postman:** Update Postman collection files ([`6305bb5`](https://github.com/juspay/hyperswitch/commit/6305bb57269fb5f6803edbad58d6e574ad4f6509))
- **tests:** Add unit tests for backwards compatibility ([#3822](https://github.com/juspay/hyperswitch/pull/3822)) ([`c65729a`](https://github.com/juspay/hyperswitch/commit/c65729adc9009f046398312a16841532fdc177da))
**Full Changelog:** [`2024.03.05.0...2024.03.06.0`](https://github.com/juspay/hyperswitch/compare/2024.03.05.0...2024.03.06.0)
- - -
## 2024.03.05.0
### Features
- **connector:** [PLACETOPAY] Fix refund request and status mapping ([#3894](https://github.com/juspay/hyperswitch/pull/3894)) ([`5eff9d4`](https://github.com/juspay/hyperswitch/commit/5eff9d47d3e53d380ef792a8fbdf06ecf78d3d16))
- **webhooks:** Implement automatic retries for failed webhook deliveries using scheduler ([#3842](https://github.com/juspay/hyperswitch/pull/3842)) ([`5bb67c7`](https://github.com/juspay/hyperswitch/commit/5bb67c7dcc22f9cee51adf501bdd8455b41548db))
### Bug Fixes
|
CHANGELOG.md#chunk37
| null |
doc_chunk
| 8,172
|
doc
| null | null | null | null | null | null | null | null | null | null | null | null |
pub struct ThreedsecureioPreAuthenticationRequest {
acct_number: cards::CardNumber,
ds: Option<DirectoryServer>,
}
|
crates/hyperswitch_connectors/src/connectors/threedsecureio/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 28
|
rust
|
ThreedsecureioPreAuthenticationRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub fn get_captures_count(&self) -> RouterResult<i16> {
i16::try_from(self.all_captures.len())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error while converting from usize to i16")
}
|
crates/router/src/core/payments/types.rs
|
router
|
function_signature
| 61
|
rust
| null | null | null | null |
get_captures_count
| null | null | null | null | null | null | null |
pub struct CybersourceErrorInformationResponse {
id: String,
error_information: CybersourceErrorInformation,
}
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 25
|
rust
|
CybersourceErrorInformationResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn generate_jwt(
self,
state: &SessionState,
next_flow: &NextFlow,
user_role: &UserRole,
) -> UserResult<Secret<String>> {
let user_id = next_flow.user.get_user_id();
// Fetch lineage context from DB
let lineage_context_from_db = state
.global_store
.find_user_by_id(user_id)
.await
.inspect_err(|e| {
logger::error!(
"Failed to fetch lineage context from DB for user {}: {:?}",
user_id,
e
)
})
.ok()
.and_then(|user| user.lineage_context);
let new_lineage_context = match lineage_context_from_db {
Some(ctx) => {
let tenant_id = ctx.tenant_id.clone();
let user_role_match_v2 = state
.global_store
.find_user_role_by_user_id_and_lineage(
&ctx.user_id,
&tenant_id,
&ctx.org_id,
&ctx.merchant_id,
&ctx.profile_id,
UserRoleVersion::V2,
)
.await
.inspect_err(|e| {
logger::error!("Failed to validate V2 role: {e:?}");
})
.map(|role| role.role_id == ctx.role_id)
.unwrap_or_default();
if user_role_match_v2 {
ctx
} else {
let user_role_match_v1 = state
.global_store
.find_user_role_by_user_id_and_lineage(
&ctx.user_id,
&tenant_id,
&ctx.org_id,
&ctx.merchant_id,
&ctx.profile_id,
UserRoleVersion::V1,
)
.await
.inspect_err(|e| {
logger::error!("Failed to validate V1 role: {e:?}");
})
.map(|role| role.role_id == ctx.role_id)
.unwrap_or_default();
if user_role_match_v1 {
ctx
} else {
// fallback to default lineage if cached context is invalid
Self::resolve_lineage_from_user_role(state, user_role, user_id).await?
}
}
}
None =>
// no cached context found
{
Self::resolve_lineage_from_user_role(state, user_role, user_id).await?
}
};
utils::user::spawn_async_lineage_context_update_to_db(
state,
user_id,
new_lineage_context.clone(),
);
auth::AuthToken::new_token(
new_lineage_context.user_id,
new_lineage_context.merchant_id,
new_lineage_context.role_id,
&state.conf,
new_lineage_context.org_id,
new_lineage_context.profile_id,
Some(new_lineage_context.tenant_id),
)
.await
.map(|token| token.into())
}
|
crates/router/src/types/domain/user/decision_manager.rs
|
router
|
function_signature
| 618
|
rust
| null | null | null | null |
generate_jwt
| null | null | null | null | null | null | null |
pub struct TwoFactorStatus {
pub status: Option<TwoFactorAuthStatusResponseWithAttempts>,
pub is_skippable: bool,
}
|
crates/api_models/src/user.rs
|
api_models
|
struct_definition
| 30
|
rust
|
TwoFactorStatus
| null | null | null | null | null | null | null | null | null | null | null |
impl RedisConnInterface for RedisStore {
fn get_redis_conn(
&self,
) -> error_stack::Result<
Arc<redis_interface::RedisConnectionPool>,
redis_interface::errors::RedisError,
> {
if self
.redis_conn
.is_redis_available
.load(atomic::Ordering::SeqCst)
{
Ok(self.redis_conn.clone())
} else {
Err(redis_interface::errors::RedisError::RedisConnectionError.into())
}
}
}
|
crates/storage_impl/src/redis.rs
|
storage_impl
|
impl_block
| 109
|
rust
| null |
RedisStore
|
RedisConnInterface for
|
impl RedisConnInterface for for RedisStore
| null | null | null | null | null | null | null | null |
impl NewUserRole<NoLevel> {
pub fn add_entity<T>(self, entity: T) -> NewUserRole<T>
where
T: Clone,
{
NewUserRole {
entity,
user_id: self.user_id,
role_id: self.role_id,
status: self.status,
created_by: self.created_by,
last_modified_by: self.last_modified_by,
created_at: self.created_at,
last_modified: self.last_modified,
}
}
}
|
crates/router/src/types/domain/user.rs
|
router
|
impl_block
| 104
|
rust
| null |
NewUserRole
| null |
impl NewUserRole
| null | null | null | null | null | null | null | null |
pub struct TotpSecret {
pub secret: Secret<String>,
pub totp_url: Secret<String>,
}
|
crates/api_models/src/user.rs
|
api_models
|
struct_definition
| 23
|
rust
|
TotpSecret
| null | null | null | null | null | null | null | null | null | null | null |
pub fn resource(&self) -> Resource {
match self {
#(#resource_impl_per),*
}
}
|
crates/router_derive/src/macros/generate_permissions.rs
|
router_derive
|
function_signature
| 25
|
rust
| null | null | null | null |
resource
| null | null | null | null | null | null | null |
pub struct Card {
card_holder_name: Secret<String>,
card_number: CardNumber,
expiry_date: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/payone/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 27
|
rust
|
Card
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/diesel_models/src/query/business_profile.rs
Public functions: 7
use diesel::{associations::HasTable, BoolExpressionMethods, ExpressionMethods, Table};
use super::generics;
#[cfg(feature = "v1")]
use crate::schema::business_profile::dsl::{self, profile_id as dsl_identifier};
#[cfg(feature = "v2")]
use crate::schema_v2::business_profile::dsl::{self, id as dsl_identifier};
use crate::{
business_profile::{Profile, ProfileNew, ProfileUpdateInternal},
errors, PgPooledConn, StorageResult,
};
impl ProfileNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<Profile> {
generics::generic_insert(conn, self).await
}
}
impl Profile {
pub async fn update_by_profile_id(
self,
conn: &PgPooledConn,
business_profile: ProfileUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_by_id::<<Self as HasTable>::Table, _, _, _>(
conn,
self.get_id().to_owned(),
business_profile,
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
pub async fn find_by_profile_id(
conn: &PgPooledConn,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl_identifier.eq(profile_id.to_owned()),
)
.await
}
pub async fn find_by_merchant_id_profile_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
profile_id: &common_utils::id_type::ProfileId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl_identifier.eq(profile_id.to_owned())),
)
.await
}
pub async fn find_by_profile_name_merchant_id(
conn: &PgPooledConn,
profile_name: &str,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::profile_name
.eq(profile_name.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
)
.await
}
pub async fn list_profile_by_merchant_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()),
None,
None,
None,
)
.await
}
pub async fn delete_by_profile_id_merchant_id(
conn: &PgPooledConn,
profile_id: &common_utils::id_type::ProfileId,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<bool> {
generics::generic_delete::<<Self as HasTable>::Table, _>(
conn,
dsl_identifier
.eq(profile_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
)
.await
}
}
|
crates/diesel_models/src/query/business_profile.rs
|
diesel_models
|
full_file
| 819
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct PaymentAttemptUpdateMems {
pub orig: PaymentAttempt,
pub update_data: PaymentAttemptUpdateInternal,
}
|
crates/diesel_models/src/kv.rs
|
diesel_models
|
struct_definition
| 26
|
rust
|
PaymentAttemptUpdateMems
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
Public structs: 40
use std::collections::HashMap;
use api_models::{
payments::{
AmountInfo, ApplePayPaymentRequest, ApplePaySessionResponse,
ApplepayCombinedSessionTokenData, ApplepaySessionTokenData, ApplepaySessionTokenMetadata,
ApplepaySessionTokenResponse, NextActionCall, NoThirdPartySdkSessionResponse,
SdkNextAction, SessionToken,
},
webhooks::IncomingWebhookEvent,
};
use base64::Engine;
use common_enums::{enums, CountryAlpha2};
use common_utils::{
consts::{APPLEPAY_VALIDATION_URL, BASE64_ENGINE},
errors::CustomResult,
ext_traits::{ByteSliceExt, Encode, OptionExt, StringExt, ValueExt},
pii::Email,
types::{FloatMajorUnit, StringMajorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
address::AddressDetails,
payment_method_data::{self, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{PaymentsResponseData, RefundsResponseData},
types,
};
use hyperswitch_interfaces::errors;
use masking::{ExposeInterface, PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use serde_json::Value;
use crate::{
types::{PaymentsSessionResponseRouterData, RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, ApplePay, CardData as _, ForeignTryFrom,
PaymentsAuthorizeRequestData, PaymentsCompleteAuthorizeRequestData, RouterData as _,
},
};
const DISPLAY_METADATA: &str = "Y";
#[derive(Debug, Serialize)]
pub struct BluesnapRouterData<T> {
pub amount: StringMajorUnit,
pub router_data: T,
}
impl<T> TryFrom<(StringMajorUnit, T)> for BluesnapRouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (StringMajorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapPaymentsRequest {
amount: StringMajorUnit,
#[serde(flatten)]
payment_method: PaymentMethodDetails,
currency: enums::Currency,
card_transaction_type: BluesnapTxnType,
transaction_fraud_info: Option<TransactionFraudInfo>,
card_holder_info: Option<BluesnapCardHolderInfo>,
merchant_transaction_id: Option<String>,
transaction_meta_data: Option<BluesnapMetadata>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapMetadata {
meta_data: Vec<RequestMetadata>,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RequestMetadata {
meta_key: Option<String>,
meta_value: Option<String>,
is_visible: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapCardHolderInfo {
first_name: Secret<String>,
last_name: Secret<String>,
email: Email,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TransactionFraudInfo {
fraud_session_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapCreateWalletToken {
wallet_type: String,
validation_url: Secret<String>,
domain_name: String,
display_name: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapThreeDSecureInfo {
three_d_secure_reference_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub enum PaymentMethodDetails {
CreditCard(Card),
Wallet(BluesnapWallet),
}
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
card_number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
security_code: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapWallet {
wallet_type: BluesnapWalletTypes,
encoded_payment_token: Secret<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapGooglePayObject {
payment_method_data: utils::GooglePayWalletData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BluesnapWalletTypes {
GooglePay,
ApplePay,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct EncodedPaymentToken {
billing_contact: BillingDetails,
token: ApplepayPaymentData,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BillingDetails {
country_code: Option<CountryAlpha2>,
address_lines: Option<Vec<Secret<String>>>,
family_name: Option<Secret<String>>,
given_name: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ApplepayPaymentData {
payment_data: ApplePayEncodedPaymentData,
payment_method: ApplepayPaymentMethod,
transaction_identifier: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ApplepayPaymentMethod {
display_name: String,
network: String,
#[serde(rename = "type")]
pm_type: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct ApplePayEncodedPaymentData {
data: String,
header: Option<ApplepayHeader>,
signature: String,
version: String,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ApplepayHeader {
ephemeral_public_key: Secret<String>,
public_key_hash: Secret<String>,
transaction_id: Secret<String>,
}
#[derive(Debug, Serialize, Deserialize, Clone)]
pub struct BluesnapConnectorMetaData {
pub merchant_id: common_utils::id_type::MerchantId,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapPaymentsTokenRequest {
cc_number: cards::CardNumber,
exp_date: Secret<String>,
}
impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>>
for BluesnapPaymentsTokenRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BluesnapRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => Ok(Self {
cc_number: ccard.card_number.clone(),
exp_date: ccard.get_expiry_date_as_mmyyyy("/"),
}),
PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
"Selected payment method via Token flow through bluesnap".to_string(),
)
.into())
}
}
}
}
impl TryFrom<&BluesnapRouterData<&types::PaymentsAuthorizeRouterData>> for BluesnapPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BluesnapRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let auth_mode = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => BluesnapTxnType::AuthOnly,
_ => BluesnapTxnType::AuthCapture,
};
let transaction_meta_data =
item.router_data
.request
.metadata
.as_ref()
.map(|metadata| BluesnapMetadata {
meta_data: convert_metadata_to_request_metadata(metadata.to_owned()),
});
let (payment_method, card_holder_info) = match item
.router_data
.request
.payment_method_data
.clone()
{
PaymentMethodData::Card(ref ccard) => Ok((
PaymentMethodDetails::CreditCard(Card {
card_number: ccard.card_number.clone(),
expiration_month: ccard.card_exp_month.clone(),
expiration_year: ccard.get_expiry_year_4_digit(),
security_code: ccard.card_cvc.clone(),
}),
get_card_holder_info(
item.router_data.get_billing_address()?,
item.router_data.request.get_email()?,
)?,
)),
PaymentMethodData::Wallet(wallet_data) => match wallet_data {
WalletData::GooglePay(payment_method_data) => {
let gpay_ecrypted_object = BluesnapGooglePayObject {
payment_method_data: utils::GooglePayWalletData::try_from(
payment_method_data,
)
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
}
.encode_to_string_of_json()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok((
PaymentMethodDetails::Wallet(BluesnapWallet {
wallet_type: BluesnapWalletTypes::GooglePay,
encoded_payment_token: Secret::new(
BASE64_ENGINE.encode(gpay_ecrypted_object),
),
}),
None,
))
}
WalletData::ApplePay(payment_method_data) => {
let apple_pay_payment_data =
payment_method_data.get_applepay_decoded_payment_data()?;
let apple_pay_payment_data: ApplePayEncodedPaymentData = apple_pay_payment_data
.expose()
.as_bytes()
.parse_struct("ApplePayEncodedPaymentData")
.change_context(errors::ConnectorError::InvalidWalletToken {
wallet_name: "Apple Pay".to_string(),
})?;
let billing = item.router_data.get_billing()?.to_owned();
let billing_address = billing
.address
.get_required_value("billing_address")
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "billing",
})?;
let mut address = Vec::new();
if let Some(add) = billing_address.line1.to_owned() {
address.push(add)
}
if let Some(add) = billing_address.line2.to_owned() {
address.push(add)
}
if let Some(add) = billing_address.line3.to_owned() {
address.push(add)
}
let apple_pay_object = EncodedPaymentToken {
token: ApplepayPaymentData {
payment_data: apple_pay_payment_data,
payment_method: payment_method_data.payment_method.to_owned().into(),
transaction_identifier: payment_method_data.transaction_identifier,
},
billing_contact: BillingDetails {
country_code: billing_address.country,
address_lines: Some(address),
family_name: billing_address.last_name.to_owned(),
given_name: billing_address.first_name.to_owned(),
postal_code: billing_address.zip,
},
}
.encode_to_string_of_json()
.change_context(errors::ConnectorError::RequestEncodingFailed)?;
Ok((
PaymentMethodDetails::Wallet(BluesnapWallet {
wallet_type: BluesnapWalletTypes::ApplePay,
encoded_payment_token: Secret::new(
BASE64_ENGINE.encode(apple_pay_object),
),
}),
get_card_holder_info(
item.router_data.get_billing_address()?,
item.router_data.request.get_email()?,
)?,
))
}
WalletData::AliPayQr(_)
| WalletData::AliPayRedirect(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayRedirect(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::WeChatPayQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("bluesnap"),
)),
},
PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("bluesnap"),
))
}
}?;
Ok(Self {
amount: item.amount.to_owned(),
payment_method,
currency: item.router_data.request.currency,
card_transaction_type: auth_mode,
transaction_fraud_info: Some(TransactionFraudInfo {
fraud_session_id: item.router_data.payment_id.clone(),
}),
card_holder_info,
merchant_transaction_id: Some(item.router_data.connector_request_reference_id.clone()),
transaction_meta_data,
})
}
}
impl From<payment_method_data::ApplepayPaymentMethod> for ApplepayPaymentMethod {
fn from(item: payment_method_data::ApplepayPaymentMethod) -> Self {
Self {
display_name: item.display_name,
network: item.network,
pm_type: item.pm_type,
}
}
}
impl TryFrom<&types::PaymentsSessionRouterData> for BluesnapCreateWalletToken {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsSessionRouterData) -> Result<Self, Self::Error> {
let apple_pay_metadata = item.get_connector_meta()?.expose();
let applepay_metadata = apple_pay_metadata
.clone()
.parse_value::<ApplepayCombinedSessionTokenData>("ApplepayCombinedSessionTokenData")
.map(|combined_metadata| {
ApplepaySessionTokenMetadata::ApplePayCombined(combined_metadata.apple_pay_combined)
})
.or_else(|_| {
apple_pay_metadata
.parse_value::<ApplepaySessionTokenData>("ApplepaySessionTokenData")
.map(|old_metadata| {
ApplepaySessionTokenMetadata::ApplePay(old_metadata.apple_pay)
})
})
.change_context(errors::ConnectorError::ParsingFailed)?;
let session_token_data = match applepay_metadata {
ApplepaySessionTokenMetadata::ApplePay(apple_pay_data) => {
Ok(apple_pay_data.session_token_data)
}
ApplepaySessionTokenMetadata::ApplePayCombined(_apple_pay_combined_data) => {
Err(errors::ConnectorError::FlowNotSupported {
flow: "apple pay combined".to_string(),
connector: "bluesnap".to_string(),
})
}
}?;
let domain_name = session_token_data.initiative_context.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "apple pay initiative_context",
},
)?;
Ok(Self {
wallet_type: "APPLE_PAY".to_string(),
validation_url: APPLEPAY_VALIDATION_URL.to_string().into(),
domain_name,
display_name: Some(session_token_data.display_name),
})
}
}
impl
ForeignTryFrom<(
PaymentsSessionResponseRouterData<BluesnapWalletTokenResponse>,
StringMajorUnit,
)> for types::PaymentsSessionRouterData
{
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
(item, apple_pay_amount): (
PaymentsSessionResponseRouterData<BluesnapWalletTokenResponse>,
StringMajorUnit,
),
) -> Result<Self, Self::Error> {
let response = &item.response;
let wallet_token = BASE64_ENGINE
.decode(response.wallet_token.clone().expose())
.change_context(errors::ConnectorError::ResponseHandlingFailed)?;
let session_response: NoThirdPartySdkSessionResponse = wallet_token
.parse_struct("NoThirdPartySdkSessionResponse")
.change_context(errors::ConnectorError::ParsingFailed)?;
let metadata = item.data.get_connector_meta()?.expose();
let applepay_metadata = metadata
.clone()
.parse_value::<ApplepayCombinedSessionTokenData>("ApplepayCombinedSessionTokenData")
.map(|combined_metadata| {
ApplepaySessionTokenMetadata::ApplePayCombined(combined_metadata.apple_pay_combined)
})
.or_else(|_| {
metadata
.parse_value::<ApplepaySessionTokenData>("ApplepaySessionTokenData")
.map(|old_metadata| {
ApplepaySessionTokenMetadata::ApplePay(old_metadata.apple_pay)
})
})
.change_context(errors::ConnectorError::ParsingFailed)?;
let (payment_request_data, session_token_data) = match applepay_metadata {
ApplepaySessionTokenMetadata::ApplePayCombined(_apple_pay_combined) => {
Err(errors::ConnectorError::FlowNotSupported {
flow: "apple pay combined".to_string(),
connector: "bluesnap".to_string(),
})
}
ApplepaySessionTokenMetadata::ApplePay(apple_pay) => {
Ok((apple_pay.payment_request_data, apple_pay.session_token_data))
}
}?;
Ok(Self {
response: Ok(PaymentsResponseData::SessionResponse {
session_token: SessionToken::ApplePay(Box::new(ApplepaySessionTokenResponse {
session_token_data: Some(ApplePaySessionResponse::NoThirdPartySdk(
session_response,
)),
payment_request_data: Some(ApplePayPaymentRequest {
country_code: item.data.get_billing_country()?,
currency_code: item.data.request.currency,
total: AmountInfo {
label: payment_request_data.label,
total_type: Some("final".to_string()),
amount: apple_pay_amount,
},
merchant_capabilities: Some(payment_request_data.merchant_capabilities),
supported_networks: Some(payment_request_data.supported_networks),
merchant_identifier: Some(session_token_data.merchant_identifier),
required_billing_contact_fields: None,
required_shipping_contact_fields: None,
recurring_payment_request: None,
}),
connector: "bluesnap".to_string(),
delayed_session_token: false,
sdk_next_action: {
SdkNextAction {
next_action: NextActionCall::Confirm,
}
},
connector_reference_id: None,
connector_sdk_public_key: None,
connector_merchant_id: None,
})),
}),
..item.data
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapCompletePaymentsRequest {
amount: StringMajorUnit,
currency: enums::Currency,
card_transaction_type: BluesnapTxnType,
pf_token: Secret<String>,
three_d_secure: Option<BluesnapThreeDSecureInfo>,
transaction_fraud_info: Option<TransactionFraudInfo>,
card_holder_info: Option<BluesnapCardHolderInfo>,
merchant_transaction_id: Option<String>,
transaction_meta_data: Option<BluesnapMetadata>,
}
impl TryFrom<&BluesnapRouterData<&types::PaymentsCompleteAuthorizeRouterData>>
for BluesnapCompletePaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BluesnapRouterData<&types::PaymentsCompleteAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let redirection_response: BluesnapRedirectionResponse = item
.router_data
.request
.redirect_response
.as_ref()
.and_then(|res| res.payload.to_owned())
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.payload",
})?
.parse_value("BluesnapRedirectionResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let transaction_meta_data =
item.router_data
.request
.metadata
.as_ref()
.map(|metadata| BluesnapMetadata {
meta_data: convert_metadata_to_request_metadata(metadata.to_owned()),
});
let token = item
.router_data
.request
.redirect_response
.clone()
.and_then(|res| res.params.to_owned())
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.params",
})?
.peek()
.split_once('=')
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "request.redirect_response.params.paymentToken",
})?
.1
.to_string();
let redirection_result: BluesnapThreeDsResult = redirection_response
.authentication_response
.parse_struct("BluesnapThreeDsResult")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
let auth_mode = match item.router_data.request.capture_method {
Some(enums::CaptureMethod::Manual) => BluesnapTxnType::AuthOnly,
_ => BluesnapTxnType::AuthCapture,
};
Ok(Self {
amount: item.amount.to_owned(),
currency: item.router_data.request.currency,
card_transaction_type: auth_mode,
three_d_secure: Some(BluesnapThreeDSecureInfo {
three_d_secure_reference_id: redirection_result
.three_d_secure
.ok_or(errors::ConnectorError::MissingConnectorRedirectionPayload {
field_name: "three_d_secure_reference_id",
})?
.three_d_secure_reference_id,
}),
transaction_fraud_info: Some(TransactionFraudInfo {
fraud_session_id: item.router_data.payment_id.clone(),
}),
card_holder_info: get_card_holder_info(
item.router_data.get_billing_address()?,
item.router_data.request.get_email()?,
)?,
merchant_transaction_id: Some(item.router_data.connector_request_reference_id.clone()),
pf_token: Secret::new(token),
transaction_meta_data,
})
}
}
#[derive(Debug, Deserialize)]
pub struct BluesnapRedirectionResponse {
pub authentication_response: String,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapThreeDsResult {
three_d_secure: Option<BluesnapThreeDsReference>,
pub status: String,
pub code: Option<String>,
pub info: Option<RedirectErrorMessage>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct RedirectErrorMessage {
pub errors: Option<Vec<String>>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapThreeDsReference {
three_d_secure_reference_id: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapVoidRequest {
card_transaction_type: BluesnapTxnType,
transaction_id: String,
}
impl TryFrom<&types::PaymentsCancelRouterData> for BluesnapVoidRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &types::PaymentsCancelRouterData) -> Result<Self, Self::Error> {
let card_transaction_type = BluesnapTxnType::AuthReversal;
let transaction_id = item.request.connector_transaction_id.to_string();
Ok(Self {
card_transaction_type,
transaction_id,
})
}
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapCaptureRequest {
card_transaction_type: BluesnapTxnType,
transaction_id: String,
amount: Option<StringMajorUnit>,
}
impl TryFrom<&BluesnapRouterData<&types::PaymentsCaptureRouterData>> for BluesnapCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BluesnapRouterData<&types::PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let card_transaction_type = BluesnapTxnType::Capture;
let transaction_id = item
.router_data
.request
.connector_transaction_id
.to_string();
Ok(Self {
card_transaction_type,
transaction_id,
amount: Some(item.amount.to_owned()),
})
}
}
// Auth Struct
pub struct BluesnapAuthType {
pub(super) api_key: Secret<String>,
pub(super) key1: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for BluesnapAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::BodyKey { api_key, key1 } = auth_type {
Ok(Self {
api_key: api_key.to_owned(),
key1: key1.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType.into())
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BluesnapTxnType {
AuthOnly,
AuthCapture,
AuthReversal,
Capture,
Refund,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum BluesnapProcessingStatus {
#[serde(alias = "success")]
Success,
#[default]
#[serde(alias = "pending")]
Pending,
#[serde(alias = "fail")]
Fail,
#[serde(alias = "pending_merchant_review")]
PendingMerchantReview,
}
impl ForeignTryFrom<(BluesnapTxnType, BluesnapProcessingStatus)> for enums::AttemptStatus {
type Error = error_stack::Report<errors::ConnectorError>;
fn foreign_try_from(
item: (BluesnapTxnType, BluesnapProcessingStatus),
) -> Result<Self, Self::Error> {
let (item_txn_status, item_processing_status) = item;
Ok(match item_processing_status {
BluesnapProcessingStatus::Success => match item_txn_status {
BluesnapTxnType::AuthOnly => Self::Authorized,
BluesnapTxnType::AuthReversal => Self::Voided,
BluesnapTxnType::AuthCapture | BluesnapTxnType::Capture => Self::Charged,
BluesnapTxnType::Refund => Self::Charged,
},
BluesnapProcessingStatus::Pending | BluesnapProcessingStatus::PendingMerchantReview => {
Self::Pending
}
BluesnapProcessingStatus::Fail => Self::Failure,
})
}
}
impl From<BluesnapProcessingStatus> for enums::RefundStatus {
fn from(item: BluesnapProcessingStatus) -> Self {
match item {
BluesnapProcessingStatus::Success => Self::Success,
BluesnapProcessingStatus::Pending => Self::Pending,
BluesnapProcessingStatus::PendingMerchantReview => Self::ManualReview,
BluesnapProcessingStatus::Fail => Self::Failure,
}
}
}
impl From<BluesnapRefundStatus> for enums::RefundStatus {
fn from(item: BluesnapRefundStatus) -> Self {
match item {
BluesnapRefundStatus::Success => Self::Success,
BluesnapRefundStatus::Pending => Self::Pending,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapPaymentsResponse {
pub processing_info: ProcessingInfoResponse,
pub transaction_id: String,
pub card_transaction_type: BluesnapTxnType,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapWalletTokenResponse {
wallet_type: String,
wallet_token: Secret<String>,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Refund {
refund_transaction_id: String,
amount: StringMajorUnit,
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ProcessingInfoResponse {
pub processing_status: BluesnapProcessingStatus,
pub authorization_code: Option<String>,
pub network_transaction_id: Option<Secret<String>>,
}
impl<F, T> TryFrom<ResponseRouterData<F, BluesnapPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, BluesnapPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
Ok(Self {
status: enums::AttemptStatus::foreign_try_from((
item.response.card_transaction_type,
item.response.processing_info.processing_status,
))?,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize)]
pub struct BluesnapRefundRequest {
amount: Option<StringMajorUnit>,
reason: Option<String>,
}
impl<F> TryFrom<&BluesnapRouterData<&types::RefundsRouterData<F>>> for BluesnapRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &BluesnapRouterData<&types::RefundsRouterData<F>>,
) -> Result<Self, Self::Error> {
Ok(Self {
reason: item.router_data.request.reason.clone(),
amount: Some(item.amount.to_owned()),
})
}
}
#[derive(Debug, Clone, Default, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum BluesnapRefundStatus {
Success,
#[default]
Pending,
}
#[derive(Default, Debug, Clone, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct RefundResponse {
refund_transaction_id: i32,
refund_status: BluesnapRefundStatus,
}
impl TryFrom<RefundsResponseRouterData<RSync, BluesnapPaymentsResponse>>
for types::RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, BluesnapPaymentsResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.clone(),
refund_status: enums::RefundStatus::from(
item.response.processing_info.processing_status,
),
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>>
for types::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.refund_transaction_id.to_string(),
refund_status: enums::RefundStatus::from(item.response.refund_status),
}),
..item.data
})
}
}
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapWebhookBody {
pub merchant_transaction_id: String,
pub reference_number: String,
pub transaction_type: BluesnapWebhookEvents,
pub reversal_ref_num: Option<String>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapWebhookObjectEventType {
transaction_type: BluesnapWebhookEvents,
cb_status: Option<BluesnapChargebackStatus>,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BluesnapChargebackStatus {
#[serde(alias = "New")]
New,
#[serde(alias = "Working")]
Working,
#[serde(alias = "Closed")]
Closed,
#[serde(alias = "Completed_Lost")]
CompletedLost,
#[serde(alias = "Completed_Pending")]
CompletedPending,
#[serde(alias = "Completed_Won")]
CompletedWon,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum BluesnapWebhookEvents {
Decline,
CcChargeFailed,
Charge,
Refund,
Chargeback,
ChargebackStatusChanged,
#[serde(other)]
Unknown,
}
impl TryFrom<BluesnapWebhookObjectEventType> for IncomingWebhookEvent {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(details: BluesnapWebhookObjectEventType) -> Result<Self, Self::Error> {
match details.transaction_type {
BluesnapWebhookEvents::Decline | BluesnapWebhookEvents::CcChargeFailed => {
Ok(Self::PaymentIntentFailure)
}
BluesnapWebhookEvents::Charge => Ok(Self::PaymentIntentSuccess),
BluesnapWebhookEvents::Refund => Ok(Self::RefundSuccess),
BluesnapWebhookEvents::Chargeback | BluesnapWebhookEvents::ChargebackStatusChanged => {
match details
.cb_status
.ok_or(errors::ConnectorError::WebhookEventTypeNotFound)?
{
BluesnapChargebackStatus::New | BluesnapChargebackStatus::Working => {
Ok(Self::DisputeOpened)
}
BluesnapChargebackStatus::Closed => Ok(Self::DisputeExpired),
BluesnapChargebackStatus::CompletedLost => Ok(Self::DisputeLost),
BluesnapChargebackStatus::CompletedPending => Ok(Self::DisputeChallenged),
BluesnapChargebackStatus::CompletedWon => Ok(Self::DisputeWon),
}
}
BluesnapWebhookEvents::Unknown => Ok(Self::EventNotSupported),
}
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapDisputeWebhookBody {
pub invoice_charge_amount: FloatMajorUnit,
pub currency: enums::Currency,
pub reversal_reason: Option<String>,
pub reversal_ref_num: String,
pub cb_status: String,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct BluesnapWebhookObjectResource {
reference_number: String,
transaction_type: BluesnapWebhookEvents,
reversal_ref_num: Option<String>,
}
impl TryFrom<BluesnapWebhookObjectResource> for Value {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(details: BluesnapWebhookObjectResource) -> Result<Self, Self::Error> {
let (card_transaction_type, processing_status, transaction_id) = match details
.transaction_type
{
BluesnapWebhookEvents::Decline | BluesnapWebhookEvents::CcChargeFailed => Ok((
BluesnapTxnType::Capture,
BluesnapProcessingStatus::Fail,
details.reference_number,
)),
BluesnapWebhookEvents::Charge => Ok((
BluesnapTxnType::Capture,
BluesnapProcessingStatus::Success,
details.reference_number,
)),
BluesnapWebhookEvents::Chargeback | BluesnapWebhookEvents::ChargebackStatusChanged => {
//It won't be consumed in dispute flow, so currently does not hold any significance
return serde_json::to_value(details)
|
crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs#chunk0
|
hyperswitch_connectors
|
chunk
| 8,191
| null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/scheduler/src/flow.rs
#[derive(Copy, Clone, Debug, strum::Display, strum::EnumString)]
#[strum(serialize_all = "snake_case")]
pub enum SchedulerFlow {
Producer,
Consumer,
Cleaner,
}
|
crates/scheduler/src/flow.rs
|
scheduler
|
full_file
| 56
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn routing_create_config() {}
|
crates/openapi/src/routes/routing.rs
|
openapi
|
function_signature
| 8
|
rust
| null | null | null | null |
routing_create_config
| null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.AuthenticationEligibilityRequest
{
"type": "object",
"required": [
"payment_method_data",
"payment_method"
],
"properties": {
"payment_method_data": {
"$ref": "#/components/schemas/PaymentMethodData"
},
"payment_method": {
"$ref": "#/components/schemas/PaymentMethod"
},
"client_secret": {
"type": "string",
"description": "Optional secret value used to identify and authorize the client making the request.\nThis can help ensure that the payment session is secure and valid.",
"nullable": true
},
"profile_id": {
"type": "string",
"description": "Optional identifier for the business profile associated with the payment.\nThis determines which configurations, rules, and branding are applied to the transaction.",
"nullable": true
},
"billing": {
"allOf": [
{
"$ref": "#/components/schemas/Address"
}
],
"nullable": true
},
"shipping": {
"allOf": [
{
"$ref": "#/components/schemas/Address"
}
],
"nullable": true
},
"browser_information": {
"allOf": [
{
"$ref": "#/components/schemas/BrowserInformation"
}
],
"nullable": true
},
"email": {
"type": "string",
"description": "Optional email address of the customer.\nUsed for customer identification, communication, and possibly for 3DS or fraud checks.",
"nullable": true
}
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 362
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"AuthenticationEligibilityRequest"
] | null | null | null | null |
impl CardRange {
pub fn get_three_ds_method_url(&self) -> Option<String> {
self.acs_protocol_versions
.iter()
.find(|acs_protocol_version| {
acs_protocol_version.version == self.highest_common_supported_version
})
.and_then(|acs_version| acs_version.three_ds_method_url.clone())
}
}
|
crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs
|
hyperswitch_connectors
|
impl_block
| 77
|
rust
| null |
CardRange
| null |
impl CardRange
| null | null | null | null | null | null | null | null |
pub struct MomoRedirection {}
|
crates/hyperswitch_domain_models/src/payment_method_data.rs
|
hyperswitch_domain_models
|
struct_definition
| 7
|
rust
|
MomoRedirection
| null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.MifinityData
{
"type": "object",
"required": [
"date_of_birth"
],
"properties": {
"date_of_birth": {
"type": "string",
"format": "date"
},
"language_preference": {
"type": "string",
"nullable": true
}
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 86
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"MifinityData"
] | null | null | null | null |
}
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: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
.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,
})
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Cybersource {
fn get_url(
&self,
_req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}pts/v2/payouts", self.base_url(connectors)))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoFulfill>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.destination_currency,
)?;
let connector_router_data = cybersource::CybersourceRouterData::from((amount, req));
let connector_req =
cybersource::CybersourcePayoutFulfillRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutFulfillType::get_headers(self, req, connectors)?)
.set_body(PayoutFulfillType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PayoutsRouterData<PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoFulfill>, errors::ConnectorError> {
let response: cybersource::CybersourceFulfillResponse = res
.response
.parse_struct("CybersourceFulfillResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_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: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
.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<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
for Cybersource
{
fn get_headers(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!(
"{}pts/v2/payments/",
ConnectorCommon::base_url(self, connectors)
))
}
fn get_request_body(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = cybersource::CybersourceRouterData::from((amount, req));
let connector_req =
cybersource::CybersourcePaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCompleteAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsCompleteAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(PaymentsCompleteAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(PaymentsCompleteAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCompleteAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCompleteAuthorizeRouterData, errors::ConnectorError> {
let response: cybersource::CybersourcePaymentsResponse = res
.response
.parse_struct("Cybersource 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: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
let attempt_status = match response.reason {
Some(reason) => match reason {
transformers::Reason::SystemError => Some(enums::AttemptStatus::Failure),
transformers::Reason::ServerTimeout | transformers::Reason::ServiceTimeout => None,
},
None => None,
};
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Cybersource {
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 minor_amount =
req.request
.minor_amount
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Amount",
})?;
let currency =
req.request
.currency
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "Currency",
})?;
let amount = convert_amount(self.amount_converter, minor_amount, currency)?;
let connector_router_data = cybersource::CybersourceRouterData::from((amount, req));
let connector_req = cybersource::CybersourceVoidRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCancelRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCancelRouterData, errors::ConnectorError> {
let response: cybersource::CybersourcePaymentsResponse = res
.response
.parse_struct("Cybersource 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: cybersource::CybersourceServerErrorResponse = res
.response
.parse_struct("CybersourceServerErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|event| event.set_response_body(&response));
router_env::logger::info!(error_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
reason: response.status.clone(),
code: response
.status
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_CODE.to_string()),
message: response
.message
.unwrap_or(hyperswitch_interfaces::consts::NO_ERROR_MESSAGE.to_string()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl Refund for Cybersource {}
impl RefundExecute for Cybersource {}
impl RefundSync for Cybersource {}
#[allow(dead_code)]
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Cybersource {
fn get_headers(
&self,
req: &RefundExecuteRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &RefundExecuteRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{}/refunds",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &RefundExecuteRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = cybersource::CybersourceRouterData::from((refund_amount, req));
let connector_req =
cybersource::CybersourceRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundExecuteRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(self.get_request_body(req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundExecuteRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundExecuteRouterData, errors::ConnectorError> {
let response: cybersource::CybersourceRefundResponse = res
.response
.parse_struct("Cybersource 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)
}
}
#[allow(dead_code)]
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Cybersource {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_http_method(&self) -> Method {
Method::Get
}
fn get_url(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let refund_id = req.request.get_connector_refund_id()?;
Ok(format!(
"{}tss/v2/transactions/{}",
self.base_url(connectors),
refund_id
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: cybersource::CybersourceRsyncResponse = res
.response
.parse_struct("Cybersource RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl
ConnectorIntegration<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
> for Cybersource
{
fn get_headers(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_http_method(&self) -> Method {
Method::Patch
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let connector_payment_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}pts/v2/payments/{}",
self.base_url(connectors),
connector_payment_id
))
}
fn get_request_body(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let minor_additional_amount = MinorUnit::new(req.request.additional_amount);
let additional_amount = convert_amount(
self.amount_converter,
minor_additional_amount,
req.request.currency,
)?;
let connector_router_data =
cybersource::CybersourceRouterData::from((additional_amount, req));
let connector_request =
cybersource::CybersourcePaymentsIncrementalAuthorizationRequest::try_from(
&connector_router_data,
)?;
Ok(RequestContent::Json(Box::new(connector_request)))
}
fn build_request(
&self,
req: &PaymentsIncrementalAuthorizationRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Patch)
.url(&IncrementalAuthorizationType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(IncrementalAuthorizationType::get_headers(
self, req, connectors,
)?)
.set_body(IncrementalAuthorizationType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsIncrementalAuthorizationRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>,
errors::ConnectorError,
> {
let response: cybersource::CybersourcePaymentsIncrementalAuthorizationResponse = res
.response
.parse_struct("Cybersource PaymentResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
.change_context(errors::ConnectorError::ResponseHandlingFailed)
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Cybersource {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
static CYBERSOURCE_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> =
LazyLock::new(|| {
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::CartesBancaires,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Maestro,
];
let mut cybersource_supported_payment_methods = SupportedPaymentMethods::new();
cybersource_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
cybersource_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
cybersource_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
cybersource_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
cybersource_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::Paze,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
cybersource_supported_payment_methods.add(
enums::PaymentMethod::Wallet,
enums::PaymentMethodType::SamsungPay,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
cybersource_supported_payment_methods
});
static CYBERSOURCE_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Cybersource",
description: "Cybersource provides payments, fraud protection, integrations, and support to help businesses grow with a digital-first approach.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Live,
};
static CYBERSOURCE_SUPPORTED_WEBHOOK_FLOWS: [common_enums::EventClass; 0] = [];
impl ConnectorSpecifications for Cybersource {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&CYBERSOURCE_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*CYBERSOURCE_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&CYBERSOURCE_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/cybersource.rs#chunk1
|
hyperswitch_connectors
|
chunk
| 6,373
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl ConnectorRedirectResponse for Mollie {
fn get_flow_type(
&self,
_query_params: &str,
_json_payload: Option<serde_json::Value>,
action: enums::PaymentAction,
) -> CustomResult<enums::CallConnectorAction, errors::ConnectorError> {
match action {
enums::PaymentAction::PSync
| enums::PaymentAction::CompleteAuthorize
| enums::PaymentAction::PaymentAuthenticateCompleteAuthorize => {
Ok(enums::CallConnectorAction::Trigger)
}
}
}
}
|
crates/hyperswitch_connectors/src/connectors/mollie.rs
|
hyperswitch_connectors
|
impl_block
| 119
|
rust
| null |
Mollie
|
ConnectorRedirectResponse for
|
impl ConnectorRedirectResponse for for Mollie
| null | null | null | null | null | null | null | null |
pub struct ApplePayCertificatesMigration;
|
crates/router/src/routes/app.rs
|
router
|
struct_definition
| 7
|
rust
|
ApplePayCertificatesMigration
| null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentToken for Dlocal {}
|
crates/hyperswitch_connectors/src/connectors/dlocal.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Dlocal
|
api::PaymentToken for
|
impl api::PaymentToken for for Dlocal
| null | null | null | null | null | null | null | null |
/// Name of current environment. Either "development", "sandbox" or "production".
pub fn which() -> Env {
#[cfg(debug_assertions)]
let default_env = Env::Development;
#[cfg(not(debug_assertions))]
let default_env = Env::Production;
std::env::var(vars::RUN_ENV).map_or_else(|_| default_env, |v| v.parse().unwrap_or(default_env))
}
|
crates/router_env/src/env.rs
|
router_env
|
function_signature
| 88
|
rust
| null | null | null | null |
which
| null | null | null | null | null | null | null |
pub fn get_base_url(state: &SessionState) -> &str {
if !state.conf.multitenancy.enabled {
&state.conf.user.base_url
} else {
&state.tenant.user.control_center_url
}
}
|
crates/router/src/utils/user.rs
|
router
|
function_signature
| 50
|
rust
| null | null | null | null |
get_base_url
| null | null | null | null | null | null | null |
pub async fn decrypt_generic_data<T>(
state: &routes::SessionState,
data: Option<Encryption>,
key_store: &domain::MerchantKeyStore,
) -> errors::RouterResult<Option<T>>
where
T: serde::de::DeserializeOwned,
{
let key = key_store.key.get_inner().peek();
let identifier = Identifier::Merchant(key_store.merchant_id.clone());
let decrypted_data = domain::types::crypto_operation::<serde_json::Value, masking::WithType>(
&state.into(),
type_name!(T),
domain::types::CryptoOperation::DecryptOptional(data),
identifier,
key,
)
.await
.and_then(|val| val.try_into_optionaloperation())
.change_context(errors::StorageError::DecryptionError)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to decrypt data")?;
decrypted_data
.map(|decrypted_data| decrypted_data.into_inner().expose())
.map(|decrypted_value| decrypted_value.parse_value("generic_data"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to parse generic data value")
}
|
crates/router/src/core/payment_methods/cards.rs
|
router
|
function_signature
| 253
|
rust
| null | null | null | null |
decrypt_generic_data
| null | null | null | null | null | null | null |
File: crates/router/src/core/payments/flows/approve_flow.rs
use async_trait::async_trait;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ApiErrorResponse, NotImplementedMessage, RouterResult},
payments::{self, access_token, helpers, transformers, PaymentData},
},
routes::SessionState,
services,
types::{self, api, domain},
};
#[async_trait]
impl
ConstructFlowSpecificData<api::Approve, types::PaymentsApproveData, types::PaymentsResponseData>
for PaymentData<api::Approve>
{
#[cfg(feature = "v2")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsApproveRouterData> {
todo!()
}
#[cfg(feature = "v1")]
async fn construct_router_data<'a>(
&self,
state: &SessionState,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &Option<domain::Customer>,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsApproveRouterData> {
Box::pin(transformers::construct_payment_router_data::<
api::Approve,
types::PaymentsApproveData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
}
#[async_trait]
impl Feature<api::Approve, types::PaymentsApproveData>
for types::RouterData<api::Approve, types::PaymentsApproveData, types::PaymentsResponseData>
{
async fn decide_flows<'a>(
self,
_state: &SessionState,
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
_connector_request: Option<services::Request>,
_business_profile: &domain::Profile,
_header_payload: hyperswitch_domain_models::payments::HeaderPayload,
_return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
}
.into())
}
async fn add_access_token<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
merchant_context: &domain::MerchantContext,
creds_identifier: Option<&str>,
) -> RouterResult<types::AddAccessTokenResult> {
Box::pin(access_token::add_access_token(
state,
connector,
merchant_context,
self,
creds_identifier,
))
.await
}
async fn build_flow_specific_connector_request(
&mut self,
_state: &SessionState,
_connector: &api::ConnectorData,
_call_connector_action: payments::CallConnectorAction,
) -> RouterResult<(Option<services::Request>, bool)> {
Err(ApiErrorResponse::NotImplemented {
message: NotImplementedMessage::Reason("Flow not supported".to_string()),
}
.into())
}
}
|
crates/router/src/core/payments/flows/approve_flow.rs
|
router
|
full_file
| 795
| null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/pm_auth/src/types/api/auth_service.rs
Public structs: 4
use crate::types::{
BankAccountCredentialsRequest, BankAccountCredentialsResponse, ExchangeTokenRequest,
ExchangeTokenResponse, LinkTokenRequest, LinkTokenResponse, RecipientCreateRequest,
RecipientCreateResponse,
};
pub trait AuthService:
super::ConnectorCommon
+ AuthServiceLinkToken
+ AuthServiceExchangeToken
+ AuthServiceBankAccountCredentials
{
}
pub trait PaymentInitiation: super::ConnectorCommon + PaymentInitiationRecipientCreate {}
#[derive(Debug, Clone)]
pub struct LinkToken;
pub trait AuthServiceLinkToken:
super::ConnectorIntegration<LinkToken, LinkTokenRequest, LinkTokenResponse>
{
}
#[derive(Debug, Clone)]
pub struct ExchangeToken;
pub trait AuthServiceExchangeToken:
super::ConnectorIntegration<ExchangeToken, ExchangeTokenRequest, ExchangeTokenResponse>
{
}
#[derive(Debug, Clone)]
pub struct BankAccountCredentials;
pub trait AuthServiceBankAccountCredentials:
super::ConnectorIntegration<
BankAccountCredentials,
BankAccountCredentialsRequest,
BankAccountCredentialsResponse,
>
{
}
#[derive(Debug, Clone)]
pub struct RecipientCreate;
pub trait PaymentInitiationRecipientCreate:
super::ConnectorIntegration<RecipientCreate, RecipientCreateRequest, RecipientCreateResponse>
{
}
|
crates/pm_auth/src/types/api/auth_service.rs
|
pm_auth
|
full_file
| 268
| null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_interfaces/src/api/payments.rs
//! Payments interface
use hyperswitch_domain_models::{
router_flow_types::{
payments::{
Approve, Authorize, AuthorizeSessionToken, CalculateTax, Capture, CompleteAuthorize,
CreateConnectorCustomer, IncrementalAuthorization, PSync, PaymentMethodToken,
PostCaptureVoid, PostProcessing, PostSessionTokens, PreProcessing, Reject,
SdkSessionUpdate, Session, SetupMandate, UpdateMetadata, Void,
},
CreateOrder, ExternalVaultProxy,
},
router_request_types::{
AuthorizeSessionTokenData, CompleteAuthorizeData, ConnectorCustomerData,
CreateOrderRequestData, ExternalVaultProxyPaymentsData, PaymentMethodTokenizationData,
PaymentsApproveData, PaymentsAuthorizeData, PaymentsCancelData,
PaymentsCancelPostCaptureData, PaymentsCaptureData, PaymentsIncrementalAuthorizationData,
PaymentsPostProcessingData, PaymentsPostSessionTokensData, PaymentsPreProcessingData,
PaymentsRejectData, PaymentsSessionData, PaymentsSyncData, PaymentsTaxCalculationData,
PaymentsUpdateMetadataData, SdkPaymentsSessionUpdateData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, TaxCalculationResponseData},
};
use crate::api;
/// trait Payment
pub trait Payment:
api::ConnectorCommon
+ api::ConnectorSpecifications
+ api::ConnectorValidation
+ PaymentAuthorize
+ PaymentAuthorizeSessionToken
+ PaymentsCompleteAuthorize
+ PaymentSync
+ PaymentCapture
+ PaymentVoid
+ PaymentPostCaptureVoid
+ PaymentApprove
+ PaymentReject
+ MandateSetup
+ PaymentSession
+ PaymentToken
+ PaymentsPreProcessing
+ PaymentsPostProcessing
+ ConnectorCustomer
+ PaymentIncrementalAuthorization
+ PaymentSessionUpdate
+ PaymentPostSessionTokens
+ PaymentUpdateMetadata
+ PaymentsCreateOrder
+ ExternalVaultProxyPaymentsCreateV1
{
}
/// trait PaymentSession
pub trait PaymentSession:
api::ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData>
{
}
/// trait MandateSetup
pub trait MandateSetup:
api::ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData>
{
}
/// trait PaymentAuthorize
pub trait PaymentAuthorize:
api::ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData>
{
}
/// trait PaymentCapture
pub trait PaymentCapture:
api::ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData>
{
}
/// trait PaymentSync
pub trait PaymentSync:
api::ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData>
{
}
/// trait PaymentVoid
pub trait PaymentVoid:
api::ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData>
{
}
/// trait PaymentPostCaptureVoid
pub trait PaymentPostCaptureVoid:
api::ConnectorIntegration<PostCaptureVoid, PaymentsCancelPostCaptureData, PaymentsResponseData>
{
}
/// trait PaymentApprove
pub trait PaymentApprove:
api::ConnectorIntegration<Approve, PaymentsApproveData, PaymentsResponseData>
{
}
/// trait PaymentReject
pub trait PaymentReject:
api::ConnectorIntegration<Reject, PaymentsRejectData, PaymentsResponseData>
{
}
/// trait PaymentToken
pub trait PaymentToken:
api::ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
{
}
/// trait PaymentAuthorizeSessionToken
pub trait PaymentAuthorizeSessionToken:
api::ConnectorIntegration<AuthorizeSessionToken, AuthorizeSessionTokenData, PaymentsResponseData>
{
}
/// trait PaymentIncrementalAuthorization
pub trait PaymentIncrementalAuthorization:
api::ConnectorIntegration<
IncrementalAuthorization,
PaymentsIncrementalAuthorizationData,
PaymentsResponseData,
>
{
}
/// trait TaxCalculation
pub trait TaxCalculation:
api::ConnectorIntegration<CalculateTax, PaymentsTaxCalculationData, TaxCalculationResponseData>
{
}
/// trait SessionUpdate
pub trait PaymentSessionUpdate:
api::ConnectorIntegration<SdkSessionUpdate, SdkPaymentsSessionUpdateData, PaymentsResponseData>
{
}
/// trait PostSessionTokens
pub trait PaymentPostSessionTokens:
api::ConnectorIntegration<PostSessionTokens, PaymentsPostSessionTokensData, PaymentsResponseData>
{
}
/// trait UpdateMetadata
pub trait PaymentUpdateMetadata:
api::ConnectorIntegration<UpdateMetadata, PaymentsUpdateMetadataData, PaymentsResponseData>
{
}
/// trait PaymentsCompleteAuthorize
pub trait PaymentsCompleteAuthorize:
api::ConnectorIntegration<CompleteAuthorize, CompleteAuthorizeData, PaymentsResponseData>
{
}
/// trait ConnectorCustomer
pub trait ConnectorCustomer:
api::ConnectorIntegration<CreateConnectorCustomer, ConnectorCustomerData, PaymentsResponseData>
{
}
/// trait PaymentsPreProcessing
pub trait PaymentsPreProcessing:
api::ConnectorIntegration<PreProcessing, PaymentsPreProcessingData, PaymentsResponseData>
{
}
/// trait PaymentsPostProcessing
pub trait PaymentsPostProcessing:
api::ConnectorIntegration<PostProcessing, PaymentsPostProcessingData, PaymentsResponseData>
{
}
/// trait PaymentsCreateOrder
pub trait PaymentsCreateOrder:
api::ConnectorIntegration<CreateOrder, CreateOrderRequestData, PaymentsResponseData>
{
}
/// trait ExternalVaultProxyPaymentsCreate
pub trait ExternalVaultProxyPaymentsCreateV1:
api::ConnectorIntegration<ExternalVaultProxy, ExternalVaultProxyPaymentsData, PaymentsResponseData>
{
}
|
crates/hyperswitch_interfaces/src/api/payments.rs
|
hyperswitch_interfaces
|
full_file
| 1,128
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn terminate_two_factor_auth(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<user_api::SkipTwoFactorAuthQueryParam>,
) -> HttpResponse {
let flow = Flow::TerminateTwoFactorAuth;
let skip_two_factor_auth = query.into_inner().skip_two_factor_auth.unwrap_or(false);
Box::pin(api::server_wrap(
flow,
state.clone(),
&req,
(),
|state, user, _, _| user_core::terminate_two_factor_auth(state, user, skip_two_factor_auth),
&auth::SinglePurposeJWTAuth(TokenPurpose::TOTP),
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/user.rs
|
router
|
function_signature
| 151
|
rust
| null | null | null | null |
terminate_two_factor_auth
| null | null | null | null | null | null | null |
pub struct BluesnapThreeDsReference {
three_d_secure_reference_id: String,
}
|
crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 18
|
rust
|
BluesnapThreeDsReference
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/router/src/macros.rs
pub use common_utils::newtype;
#[macro_export]
macro_rules! get_payment_link_config_value_based_on_priority {
($config:expr, $business_config:expr, $field:ident, $default:expr) => {
$config
.as_ref()
.and_then(|pc_config| pc_config.theme_config.$field.clone())
.or_else(|| {
$business_config
.as_ref()
.and_then(|business_config| business_config.$field.clone())
})
.unwrap_or($default)
};
}
#[macro_export]
macro_rules! get_payment_link_config_value {
($config:expr, $business_config:expr, $(($field:ident, $default:expr)),*) => {
(
$(get_payment_link_config_value_based_on_priority!($config, $business_config, $field, $default)),*
)
};
($config:expr, $business_config:expr, $(($field:ident)),*) => {
(
$(
$config
.as_ref()
.and_then(|pc_config| pc_config.theme_config.$field.clone())
.or_else(|| {
$business_config
.as_ref()
.and_then(|business_config| business_config.$field.clone())
})
),*
)
};
($config:expr, $business_config:expr, $(($field:ident $(, $transform:expr)?)),* $(,)?) => {
(
$(
$config
.as_ref()
.and_then(|pc_config| pc_config.theme_config.$field.clone())
.or_else(|| {
$business_config
.as_ref()
.and_then(|business_config| {
let value = business_config.$field.clone();
$(let value = value.map($transform);)?
value
})
})
),*
)
};
}
|
crates/router/src/macros.rs
|
router
|
full_file
| 395
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl Responder {
let flow = AnalyticsFlow::GetDisputeFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let auth: AuthInfo = AuthInfo::OrgLevel {
org_id: org_id.clone(),
};
analytics::disputes::get_filters(&state.pool, req, &auth)
.await
.map(ApplicationResponse::Json)
},
auth::auth_type(
&auth::PlatformOrgAdminAuth {
is_admin_auth_allowed: false,
organization_id: None,
},
&auth::JWTAuth {
permission: Permission::OrganizationAnalyticsRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/analytics.rs
|
router
|
impl_block
| 199
|
rust
| null |
Responder
| null |
impl Responder
| null | null | null | null | null | null | null | null |
pub struct Authentication {
pub user: Secret<String>,
pub password: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 19
|
rust
|
Authentication
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/analytics/src/routing_events.rs
mod core;
pub mod events;
pub trait RoutingEventAnalytics: events::RoutingEventLogAnalytics {}
pub use self::core::routing_events_core;
|
crates/analytics/src/routing_events.rs
|
analytics
|
full_file
| 41
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn get_merchant_refund_filters(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<GetRefundFilterRequest>,
) -> impl Responder {
let flow = AnalyticsFlow::GetRefundFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req: GetRefundFilterRequest, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let auth: AuthInfo = AuthInfo::MerchantLevel {
org_id: org_id.clone(),
merchant_ids: vec![merchant_id.clone()],
};
analytics::refunds::get_filters(&state.pool, req, &auth)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::MerchantAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/analytics.rs
|
router
|
function_signature
| 234
|
rust
| null | null | null | null |
get_merchant_refund_filters
| null | null | null | null | null | null | null |
impl api::MandateSetup for Deutschebank {}
|
crates/hyperswitch_connectors/src/connectors/deutschebank.rs
|
hyperswitch_connectors
|
impl_block
| 11
|
rust
| null |
Deutschebank
|
api::MandateSetup for
|
impl api::MandateSetup for for Deutschebank
| null | null | null | null | null | null | null | null |
impl Gocardless {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
|
crates/hyperswitch_connectors/src/connectors/gocardless.rs
|
hyperswitch_connectors
|
impl_block
| 34
|
rust
| null |
Gocardless
| null |
impl Gocardless
| null | null | null | null | null | null | null | null |
impl MerchantConnectorCreate {
pub fn get_transaction_type(&self) -> api_enums::TransactionType {
match self.connector_type {
#[cfg(feature = "payouts")]
api_enums::ConnectorType::PayoutProcessor => api_enums::TransactionType::Payout,
_ => api_enums::TransactionType::Payment,
}
}
pub fn get_frm_config_as_secret(&self) -> Option<Vec<Secret<serde_json::Value>>> {
match self.frm_configs.as_ref() {
Some(frm_value) => {
let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value
.iter()
.map(|config| config.encode_to_value().map(Secret::new))
.collect::<Result<Vec<_>, _>>()
.ok()?;
Some(configs_for_frm_value)
}
None => None,
}
}
}
|
crates/api_models/src/admin.rs
|
api_models
|
impl_block
| 193
|
rust
| null |
MerchantConnectorCreate
| null |
impl MerchantConnectorCreate
| null | null | null | null | null | null | null | null |
pub struct NetceteraAuthenticationFailureResponse {
pub error_details: NetceteraErrorDetails,
}
|
crates/hyperswitch_connectors/src/connectors/netcetera/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 23
|
rust
|
NetceteraAuthenticationFailureResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub struct ErrorDetails {
pub issue: String,
pub description: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 19
|
rust
|
ErrorDetails
| null | null | null | null | null | null | null | null | null | null | null |
pub struct PaymentsDslInput<'a> {
pub setup_mandate: Option<&'a mandates::MandateData>,
pub payment_attempt: &'a storage::PaymentAttempt,
pub payment_intent: &'a storage::PaymentIntent,
pub payment_method_data: Option<&'a domain::PaymentMethodData>,
pub address: &'a payment_address::PaymentAddress,
pub recurring_details: Option<&'a mandates_api::RecurringDetails>,
pub currency: storage_enums::Currency,
}
|
crates/router/src/core/routing.rs
|
router
|
struct_definition
| 107
|
rust
|
PaymentsDslInput
| null | null | null | null | null | null | null | null | null | null | null |
pub struct RoutingDictionaryRecord {
pub rule_id: String,
pub name: String,
pub created_at: time::PrimitiveDateTime,
pub modified_at: time::PrimitiveDateTime,
}
|
crates/router/src/core/payments/routing/utils.rs
|
router
|
struct_definition
| 40
|
rust
|
RoutingDictionaryRecord
| null | null | null | null | null | null | null | null | null | null | null |
impl BillingConnectorInvoiceSyncResponseData {
async fn handle_billing_connector_invoice_sync_call(
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
id: &str,
) -> CustomResult<Self, errors::RevenueRecoveryError> {
let connector_data = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
connector_name,
api::GetToken::Connector,
None,
)
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)
.attach_printable("invalid connector name received in payment attempt")?;
let connector_integration: services::BoxedBillingConnectorInvoiceSyncIntegrationInterface<
router_flow_types::BillingConnectorInvoiceSync,
revenue_recovery_request::BillingConnectorInvoiceSyncRequest,
revenue_recovery_response::BillingConnectorInvoiceSyncResponse,
> = connector_data.connector.get_connector_integration();
let router_data =
BillingConnectorInvoiceSyncFlowRouterData::construct_router_data_for_billing_connector_invoice_sync_call(
state,
connector_name,
merchant_connector_account,
merchant_context,
id,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)
.attach_printable(
"Failed while constructing router data for billing connector psync call",
)?
.inner();
let response = services::execute_connector_processing_step(
state,
connector_integration,
&router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.change_context(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)
.attach_printable("Failed while fetching billing connector Invoice details")?;
let additional_recovery_details = match response.response {
Ok(response) => Ok(response),
error @ Err(_) => {
logger::error!(?error);
Err(errors::RevenueRecoveryError::BillingConnectorPaymentsSyncFailed)
.attach_printable("Failed while fetching billing connector Invoice details")
}
}?;
Ok(Self(additional_recovery_details))
}
async fn get_billing_connector_invoice_details(
should_billing_connector_invoice_api_called: bool,
state: &SessionState,
merchant_context: &domain::MerchantContext,
billing_connector_account: &hyperswitch_domain_models::merchant_connector_account::MerchantConnectorAccount,
connector_name: &str,
merchant_reference_id: Option<id_type::PaymentReferenceId>,
) -> CustomResult<
Option<revenue_recovery_response::BillingConnectorInvoiceSyncResponse>,
errors::RevenueRecoveryError,
> {
let response_data = match should_billing_connector_invoice_api_called {
true => {
let billing_connector_invoice_id = merchant_reference_id
.as_ref()
.map(|id| id.get_string_repr())
.ok_or(errors::RevenueRecoveryError::BillingConnectorInvoiceSyncFailed)?;
let billing_connector_invoice_details =
Self::handle_billing_connector_invoice_sync_call(
state,
merchant_context,
billing_connector_account,
connector_name,
billing_connector_invoice_id,
)
.await?;
Some(billing_connector_invoice_details.inner())
}
false => None,
};
Ok(response_data)
}
fn inner(self) -> revenue_recovery_response::BillingConnectorInvoiceSyncResponse {
self.0
}
}
|
crates/router/src/core/webhooks/recovery_incoming.rs
|
router
|
impl_block
| 721
|
rust
| null |
BillingConnectorInvoiceSyncResponseData
| null |
impl BillingConnectorInvoiceSyncResponseData
| null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.PayoutMethodDataResponse
{
"oneOf": [
{
"type": "object",
"required": [
"card"
],
"properties": {
"card": {
"$ref": "#/components/schemas/CardAdditionalData"
}
}
},
{
"type": "object",
"required": [
"bank"
],
"properties": {
"bank": {
"$ref": "#/components/schemas/BankAdditionalData"
}
}
},
{
"type": "object",
"required": [
"wallet"
],
"properties": {
"wallet": {
"$ref": "#/components/schemas/WalletAdditionalData"
}
}
}
],
"description": "The payout method information for response"
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 185
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"PayoutMethodDataResponse"
] | null | null | null | null |
pub async fn refunds_manual_update(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<api_models::refunds::RefundManualUpdateRequest>,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::RefundsManualUpdate;
let mut refund_manual_update_req = payload.into_inner();
refund_manual_update_req.refund_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
refund_manual_update_req,
|state, _auth, req, _| refund_manual_update(state, req),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/refunds.rs
|
router
|
function_signature
| 157
|
rust
| null | null | null | null |
refunds_manual_update
| null | null | null | null | null | null | null |
pub async fn list_routing_configs() {}
|
crates/openapi/src/routes/routing.rs
|
openapi
|
function_signature
| 8
|
rust
| null | null | null | null |
list_routing_configs
| null | null | null | null | null | null | null |
pub struct RefundResponse {
response_code: AuthorizedotnetRefundStatus,
#[serde(rename = "transId")]
transaction_id: String,
#[allow(dead_code)]
network_trans_id: Option<Secret<String>>,
pub account_number: Option<Secret<String>>,
pub errors: Option<Vec<ErrorMessage>>,
}
|
crates/hyperswitch_connectors/src/connectors/authorizedotnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 68
|
rust
|
RefundResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub struct UpdatePaymentMethodRecord {
pub payment_method_id: String,
pub status: Option<common_enums::PaymentMethodStatus>,
pub network_transaction_id: Option<String>,
pub line_number: Option<i64>,
pub payment_instrument_id: Option<masking::Secret<String>>,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
}
|
crates/api_models/src/payment_methods.rs
|
api_models
|
struct_definition
| 79
|
rust
|
UpdatePaymentMethodRecord
| null | null | null | null | null | null | null | null | null | null | null |
pub struct WorldpayRouterData<T> {
amount: i64,
router_data: T,
}
|
crates/hyperswitch_connectors/src/connectors/worldpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 23
|
rust
|
WorldpayRouterData
| null | null | null | null | null | null | null | null | null | null | null |
impl ConnectorValidation for Opayo {
fn validate_connector_against_payment_request(
&self,
capture_method: Option<enums::CaptureMethod>,
_payment_method: enums::PaymentMethod,
_pmt: Option<enums::PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
match capture_method {
enums::CaptureMethod::Automatic
| enums::CaptureMethod::Manual
| enums::CaptureMethod::SequentialAutomatic => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
crate::utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
|
crates/hyperswitch_connectors/src/connectors/opayo.rs
|
hyperswitch_connectors
|
impl_block
| 154
|
rust
| null |
Opayo
|
ConnectorValidation for
|
impl ConnectorValidation for for Opayo
| null | null | null | null | null | null | null | null |
pub async fn create_decision_engine_merchant(
state: &SessionState,
profile_id: &id_type::ProfileId,
) -> RouterResult<()> {
let merchant_account_req = open_router::MerchantAccount {
merchant_id: profile_id.get_string_repr().to_string(),
gateway_success_rate_based_decider_input: None,
};
routing_utils::ConfigApiClient::send_decision_engine_request::<_, serde_json::Value>(
state,
services::Method::Post,
DECISION_ENGINE_MERCHANT_CREATE_ENDPOINT,
Some(merchant_account_req),
None,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to create merchant account on decision engine")?;
Ok(())
}
|
crates/router/src/core/routing/helpers.rs
|
router
|
function_signature
| 158
|
rust
| null | null | null | null |
create_decision_engine_merchant
| null | null | null | null | null | null | null |
pub struct ThreeDSRequestChallenge {
pub return_url: String,
#[serde(skip_serializing_if = "Option::is_none")]
pub preference: Option<ThreeDsPreference>,
}
|
crates/hyperswitch_connectors/src/connectors/worldpay/requests.rs
|
hyperswitch_connectors
|
struct_definition
| 39
|
rust
|
ThreeDSRequestChallenge
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/euclid/src/dssa/types.rs
Public functions: 5
Public structs: 3
use std::{collections::HashMap, fmt};
use serde::Serialize;
use crate::{
dssa::{self, graph},
frontend::{ast, dir},
types::{DataType, EuclidValue, Metadata},
};
pub trait EuclidAnalysable: Sized {
fn get_dir_value_for_analysis(&self, rule_name: String) -> Vec<(dir::DirValue, Metadata)>;
}
#[derive(Debug, Clone)]
pub enum CtxValueKind<'a> {
Assertion(&'a dir::DirValue),
Negation(&'a [dir::DirValue]),
}
impl CtxValueKind<'_> {
pub fn get_assertion(&self) -> Option<&dir::DirValue> {
if let Self::Assertion(val) = self {
Some(val)
} else {
None
}
}
pub fn get_negation(&self) -> Option<&[dir::DirValue]> {
if let Self::Negation(vals) = self {
Some(vals)
} else {
None
}
}
pub fn get_key(&self) -> Option<dir::DirKey> {
match self {
Self::Assertion(val) => Some(val.get_key()),
Self::Negation(vals) => vals.first().map(|v| (*v).get_key()),
}
}
}
#[derive(Debug, Clone)]
pub struct ContextValue<'a> {
pub value: CtxValueKind<'a>,
pub metadata: &'a Metadata,
}
impl<'a> ContextValue<'a> {
#[inline]
pub fn assertion(value: &'a dir::DirValue, metadata: &'a Metadata) -> Self {
Self {
value: CtxValueKind::Assertion(value),
metadata,
}
}
#[inline]
pub fn negation(values: &'a [dir::DirValue], metadata: &'a Metadata) -> Self {
Self {
value: CtxValueKind::Negation(values),
metadata,
}
}
}
pub type ConjunctiveContext<'a> = Vec<ContextValue<'a>>;
#[derive(Clone, Serialize)]
pub enum AnalyzeResult {
AllOk,
}
#[derive(Debug, Clone, Serialize, thiserror::Error)]
pub struct AnalysisError {
#[serde(flatten)]
pub error_type: AnalysisErrorType,
pub metadata: Metadata,
}
impl fmt::Display for AnalysisError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.error_type.fmt(f)
}
}
#[derive(Debug, Clone, Serialize)]
pub struct ValueData {
pub value: dir::DirValue,
pub metadata: Metadata,
}
#[derive(Debug, Clone, Serialize, thiserror::Error)]
#[serde(tag = "type", content = "info", rename_all = "snake_case")]
pub enum AnalysisErrorType {
#[error("Invalid program key given: '{0}'")]
InvalidKey(String),
#[error("Invalid variant '{got}' received for key '{key}'")]
InvalidVariant {
key: String,
expected: Vec<String>,
got: String,
},
#[error(
"Invalid data type for value '{}' (expected {expected}, got {got})",
key
)]
InvalidType {
key: String,
expected: DataType,
got: DataType,
},
#[error("Invalid comparison '{operator:?}' for value type {value_type}")]
InvalidComparison {
operator: ast::ComparisonType,
value_type: DataType,
},
#[error("Invalid value received for length as '{value}: {:?}'", message)]
InvalidValue {
key: dir::DirKeyKind,
value: String,
message: Option<String>,
},
#[error("Conflicting assertions received for key '{}'", .key.kind)]
ConflictingAssertions {
key: dir::DirKey,
values: Vec<ValueData>,
},
#[error("Key '{}' exhaustively negated", .key.kind)]
ExhaustiveNegation {
key: dir::DirKey,
metadata: Vec<Metadata>,
},
#[error("The condition '{value}' was asserted and negated in the same condition")]
NegatedAssertion {
value: dir::DirValue,
assertion_metadata: Metadata,
negation_metadata: Metadata,
},
#[error("Graph analysis error: {0:#?}")]
GraphAnalysis(
graph::AnalysisError<dir::DirValue>,
hyperswitch_constraint_graph::Memoization<dir::DirValue>,
),
#[error("State machine error")]
StateMachine(dssa::state_machine::StateMachineError),
#[error("Unsupported program key '{0}'")]
UnsupportedProgramKey(dir::DirKeyKind),
#[error("Ran into an unimplemented feature")]
NotImplemented,
#[error("The payment method type is not supported under the payment method")]
NotSupported,
}
#[derive(Debug, Clone)]
pub enum ValueType {
EnumVariants(Vec<EuclidValue>),
Number,
}
impl EuclidAnalysable for common_enums::AuthenticationType {
fn get_dir_value_for_analysis(&self, rule_name: String) -> Vec<(dir::DirValue, Metadata)> {
let auth = self.to_string();
let dir_value = match self {
Self::ThreeDs => dir::DirValue::AuthenticationType(Self::ThreeDs),
Self::NoThreeDs => dir::DirValue::AuthenticationType(Self::NoThreeDs),
};
vec![(
dir_value,
HashMap::from_iter([(
"AUTHENTICATION_TYPE".to_string(),
serde_json::json!({
"rule_name": rule_name,
"Authentication_type": auth,
}),
)]),
)]
}
}
|
crates/euclid/src/dssa/types.rs
|
euclid
|
full_file
| 1,231
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl Responder {
let flow = Flow::CustomersGetMandates;
let customer_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
customer_id,
|state, auth: auth::AuthenticationData, customer_id, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
crate::core::mandate::get_customer_mandates(state, merchant_context, customer_id)
},
auth::auth_type(
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
&auth::JWTAuth {
permission: Permission::MerchantMandateRead,
},
req.headers(),
),
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/customers.rs
|
router
|
impl_block
| 196
|
rust
| null |
Responder
| null |
impl Responder
| null | null | null | null | null | null | null | null |
impl webhooks::IncomingWebhook for Bankofamerica {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Ok(api_models::webhooks::IncomingWebhookEvent::EventNotSupported)
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
|
crates/hyperswitch_connectors/src/connectors/bankofamerica.rs
|
hyperswitch_connectors
|
impl_block
| 215
|
rust
| null |
Bankofamerica
|
webhooks::IncomingWebhook for
|
impl webhooks::IncomingWebhook for for Bankofamerica
| null | null | null | null | null | null | null | null |
pub struct ProfileNew;
|
crates/router/src/routes/app.rs
|
router
|
struct_definition
| 5
|
rust
|
ProfileNew
| null | null | null | null | null | null | null | null | null | null | null |
pub struct AuthenticationErrorInformation {
pub rmsg: String,
}
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 14
|
rust
|
AuthenticationErrorInformation
| null | null | null | null | null | null | null | null | null | null | null |
impl auth_service::AuthServiceBankAccountCredentials for Plaid {}
|
crates/pm_auth/src/connector/plaid.rs
|
pm_auth
|
impl_block
| 12
|
rust
| null |
Plaid
|
auth_service::AuthServiceBankAccountCredentials for
|
impl auth_service::AuthServiceBankAccountCredentials for for Plaid
| null | null | null | null | null | null | null | null |
pub fn add_connector_http_status_code_metrics(option_status_code: Option<u16>) {
if let Some(status_code) = option_status_code {
let status_code_type = get_http_status_code_type(status_code).ok();
match status_code_type.as_deref() {
Some("1xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_1XX_COUNT.add(1, &[]),
Some("2xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_2XX_COUNT.add(1, &[]),
Some("3xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_3XX_COUNT.add(1, &[]),
Some("4xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_4XX_COUNT.add(1, &[]),
Some("5xx") => metrics::CONNECTOR_HTTP_STATUS_CODE_5XX_COUNT.add(1, &[]),
_ => logger::info!("Skip metrics as invalid http status code received from connector"),
};
} else {
logger::info!("Skip metrics as no http status code received from connector")
}
}
|
crates/router/src/utils.rs
|
router
|
function_signature
| 224
|
rust
| null | null | null | null |
add_connector_http_status_code_metrics
| null | null | null | null | null | null | null |
pub struct PaymentAdditionalData<'a, F>
where
F: Clone,
{
router_base_url: String,
connector_name: String,
payment_data: PaymentData<F>,
state: &'a SessionState,
customer_data: &'a Option<domain::Customer>,
}
|
crates/router/src/core/payments/transformers.rs
|
router
|
struct_definition
| 60
|
rust
|
PaymentAdditionalData
| null | null | null | null | null | null | null | null | null | null | null |
pub struct MerchantConnectorDetails {
/// Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object.
#[schema(value_type = Option<Object>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))]
pub connector_account_details: pii::SecretSerdeValue,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))]
pub metadata: Option<pii::SecretSerdeValue>,
}
|
crates/api_models/src/admin.rs
|
api_models
|
struct_definition
| 171
|
rust
|
MerchantConnectorDetails
| null | null | null | null | null | null | null | null | null | null | null |
impl api::Refund for CtpMastercard {}
|
crates/hyperswitch_connectors/src/connectors/ctp_mastercard.rs
|
hyperswitch_connectors
|
impl_block
| 11
|
rust
| null |
CtpMastercard
|
api::Refund for
|
impl api::Refund for for CtpMastercard
| null | null | null | null | null | null | null | null |
pub struct CeleroAddress {
first_name: Option<Secret<String>>,
last_name: Option<Secret<String>>,
address_line_1: Option<Secret<String>>,
address_line_2: Option<Secret<String>>,
city: Option<String>,
state: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
country: Option<common_enums::CountryAlpha2>,
phone: Option<Secret<String>>,
email: Option<Email>,
}
|
crates/hyperswitch_connectors/src/connectors/celero/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 98
|
rust
|
CeleroAddress
| null | null | null | null | null | null | null | null | null | null | null |
pub struct Card {
number: cards::CardNumber,
expiration_month: Secret<String>,
expiration_year: Secret<String>,
security_code: Option<Secret<String>>,
#[serde(rename = "type")]
card_type: Option<String>,
type_selection_indicator: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 59
|
rust
|
Card
| null | null | null | null | null | null | null | null | null | null | null |
pub struct GlobalpayCancelRouterData<T> {
pub amount: Option<StringMinorUnit>,
pub router_data: T,
}
|
crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
|
hyperswitch_connectors
|
struct_definition
| 27
|
rust
|
GlobalpayCancelRouterData
| null | null | null | null | null | null | null | null | null | null | null |
pub trait TransitionTo<S: State> {}
|
crates/router/src/core/payment_methods/tokenize.rs
|
router
|
trait_definition
| 9
|
rust
| null | null |
TransitionTo
| null | null | null | null | null | null | null | null | null |
impl MergedEnabledPaymentMethodTypes {
fn get_required_fields(
self,
input: RequiredFieldsInput,
) -> RequiredFieldsForEnabledPaymentMethodTypes {
let required_fields_config = input.required_fields_config;
let is_cit_transaction = input.setup_future_usage == common_enums::FutureUsage::OffSession;
let required_fields_info = self
.0
.into_iter()
.map(|payment_methods_enabled| {
let required_fields =
required_fields_config.get_required_fields(&payment_methods_enabled);
let required_fields = required_fields
.map(|required_fields| {
let common_required_fields = required_fields
.common
.iter()
.flatten()
.map(ToOwned::to_owned);
// Collect mandate required fields because this is for zero auth mandates only
let mandate_required_fields = required_fields
.mandate
.iter()
.flatten()
.map(ToOwned::to_owned);
// Collect non-mandate required fields because this is for zero auth mandates only
let non_mandate_required_fields = required_fields
.non_mandate
.iter()
.flatten()
.map(ToOwned::to_owned);
// Combine mandate and non-mandate required fields based on setup_future_usage
if is_cit_transaction {
common_required_fields
.chain(non_mandate_required_fields)
.collect::<Vec<_>>()
} else {
common_required_fields
.chain(mandate_required_fields)
.collect::<Vec<_>>()
}
})
.unwrap_or_default();
RequiredFieldsForEnabledPaymentMethod {
required_fields,
payment_method_type: payment_methods_enabled.payment_method_type,
payment_method_subtype: payment_methods_enabled.payment_method_subtype,
payment_experience: payment_methods_enabled.payment_experience,
connectors: payment_methods_enabled.connectors,
}
})
.collect();
RequiredFieldsForEnabledPaymentMethodTypes(required_fields_info)
}
}
|
crates/router/src/core/payments/payment_methods.rs
|
router
|
impl_block
| 421
|
rust
| null |
MergedEnabledPaymentMethodTypes
| null |
impl MergedEnabledPaymentMethodTypes
| null | null | null | null | null | null | null | null |
pub fn get_pending_captures_without_connector_capture_id(&self) -> Vec<&storage::Capture> {
self.get_pending_captures()
.into_iter()
.filter(|capture| capture.get_optional_connector_transaction_id().is_none())
.collect()
}
|
crates/router/src/core/payments/types.rs
|
router
|
function_signature
| 57
|
rust
| null | null | null | null |
get_pending_captures_without_connector_capture_id
| null | null | null | null | null | null | null |
impl api::ConnectorAccessToken for Fiserv {}
|
crates/hyperswitch_connectors/src/connectors/fiserv.rs
|
hyperswitch_connectors
|
impl_block
| 10
|
rust
| null |
Fiserv
|
api::ConnectorAccessToken for
|
impl api::ConnectorAccessToken for for Fiserv
| null | null | null | null | null | null | null | null |
pub struct SilverflowCardData {
pub number: String,
pub expiry_month: Secret<String>,
pub expiry_year: Secret<String>,
pub cvc: String,
pub holder_name: String,
}
|
crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 44
|
rust
|
SilverflowCardData
| null | null | null | null | null | null | null | null | null | null | null |
pub fn get_value(&self) -> &T {
match self {
Self::ValueSet(value) => value,
Self::ValueExists(value) => value,
}
}
|
crates/redis_interface/src/types.rs
|
redis_interface
|
function_signature
| 39
|
rust
| null | null | null | null |
get_value
| null | null | null | null | null | null | null |
pub struct Advice {
pub code: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
|
hyperswitch_connectors
|
struct_definition
| 12
|
rust
|
Advice
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
Public structs: 22
#[cfg(feature = "payouts")]
use common_enums::enums::PayoutEntityType;
use common_enums::{enums, Currency, PayoutStatus};
use common_utils::{pii::Email, types::FloatMajorUnit};
use hyperswitch_domain_models::router_data::ConnectorAuthType;
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_response_types::PayoutsResponseData, types::PayoutsRouterData,
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
#[cfg(feature = "payouts")]
use crate::utils::PayoutFulfillRequestData;
#[cfg(feature = "payouts")]
use crate::{types::PayoutsResponseRouterData, utils::RouterData as UtilsRouterData};
pub const PURPOSE_OF_PAYMENT_IS_OTHER: &str = "OTHER";
pub struct NomupayRouterData<T> {
pub amount: FloatMajorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
impl<T> From<(FloatMajorUnit, T)> for NomupayRouterData<T> {
fn from((amount, item): (FloatMajorUnit, T)) -> Self {
//Todo : use utils to convert the amount to the type of amount that a connector accepts
Self {
amount,
router_data: item,
}
}
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Address {
pub country: enums::CountryAlpha2,
pub state_province: Secret<String>,
pub street: Secret<String>,
pub city: String,
pub postal_code: Secret<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum ProfileType {
#[default]
Individual,
Businness,
}
#[cfg(feature = "payouts")]
impl From<PayoutEntityType> for ProfileType {
fn from(entity: PayoutEntityType) -> Self {
match entity {
PayoutEntityType::Personal
| PayoutEntityType::NaturalPerson
| PayoutEntityType::Individual => Self::Individual,
_ => Self::Businness,
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
pub enum NomupayGender {
Male,
Female,
#[default]
Other,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct Profile {
pub profile_type: ProfileType,
pub first_name: Secret<String>,
pub last_name: Secret<String>,
pub date_of_birth: Secret<String>,
pub gender: NomupayGender,
pub email_address: Email,
pub phone_number_country_code: Option<String>,
pub phone_number: Option<Secret<String>>,
pub address: Address,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct OnboardSubAccountRequest {
pub account_id: Secret<String>,
pub client_sub_account_id: Secret<String>,
pub profile: Profile,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct BankAccount {
pub bank_id: Option<Secret<String>>,
pub account_id: Secret<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct VirtualAccountsType {
pub country_code: String,
pub currency_code: String,
pub bank_id: Secret<String>,
pub bank_account_id: Secret<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum TransferMethodType {
#[default]
BankAccount,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct OnboardTransferMethodRequest {
pub country_code: enums::CountryAlpha2,
pub currency_code: Currency,
#[serde(rename = "type")]
pub transfer_method_type: TransferMethodType,
pub display_name: Secret<String>,
pub bank_account: BankAccount,
pub profile: Profile,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct NomupayPaymentRequest {
pub source_id: Secret<String>,
pub destination_id: Secret<String>,
pub payment_reference: String,
pub amount: FloatMajorUnit,
pub currency_code: Currency,
pub purpose: String,
pub description: Option<String>,
pub internal_memo: Option<String>,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct QuoteRequest {
pub source_id: Secret<String>,
pub source_currency_code: Currency,
pub destination_currency_code: Currency,
pub amount: FloatMajorUnit,
pub include_fee: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct CommitRequest {
pub source_id: Secret<String>,
pub id: String,
pub destination_id: Secret<String>,
pub payment_reference: String,
pub amount: FloatMajorUnit,
pub currency_code: Currency,
pub purpose: String,
pub description: String,
pub internal_memo: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct OnboardSubAccountResponse {
pub account_id: Secret<String>,
pub id: String,
pub client_sub_account_id: Secret<String>,
pub profile: Profile,
pub virtual_accounts: Vec<VirtualAccountsType>,
pub status: String,
pub created_on: String,
pub last_updated: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct OnboardTransferMethodResponse {
pub parent_id: Secret<String>,
pub account_id: Secret<String>,
pub sub_account_id: Secret<String>,
pub id: String,
pub status: String,
pub created_on: String,
pub last_updated: String,
pub country_code: String,
pub currency_code: Currency,
pub display_name: String,
#[serde(rename = "type")]
pub transfer_method_type: String,
pub profile: Profile,
pub bank_account: BankAccount,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct NomupayPaymentResponse {
pub id: String,
pub status: NomupayPaymentStatus,
pub created_on: String,
pub last_updated: String,
pub source_id: Secret<String>,
pub destination_id: Secret<String>,
pub payment_reference: String,
pub amount: FloatMajorUnit,
pub currency_code: String,
pub purpose: String,
pub description: String,
pub internal_memo: String,
pub release_on: String,
pub expire_on: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct FeesType {
#[serde(rename = "type")]
pub fees_type: String,
pub fees: FloatMajorUnit,
pub currency_code: Currency,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct PayoutQuoteResponse {
pub source_id: Secret<String>,
pub destination_currency_code: Currency,
pub amount: FloatMajorUnit,
pub source_currency_code: Currency,
pub include_fee: bool,
pub fees: Vec<FeesType>,
pub payment_reference: String,
}
#[derive(Serialize, Deserialize, Debug)]
#[serde(rename_all = "camelCase")]
pub struct CommitResponse {
pub id: String,
pub status: String,
pub created_on: String,
pub last_updated: String,
pub source_id: Secret<String>,
pub destination_id: Secret<String>,
pub payment_reference: String,
pub amount: FloatMajorUnit,
pub currency_code: Currency,
pub purpose: String,
pub description: String,
pub internal_memo: String,
pub release_on: String,
pub expire_on: String,
}
#[derive(Serialize, Deserialize, Debug)]
pub struct NomupayMetadata {
pub private_key: Secret<String>,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ValidationError {
pub field: String,
pub message: String,
}
#[derive(Default, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct DetailsType {
pub loc: Vec<String>,
#[serde(rename = "type")]
pub error_type: String,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NomupayInnerError {
pub error_code: String,
pub error_description: Option<String>,
pub validation_errors: Option<Vec<ValidationError>>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct NomupayErrorResponse {
pub status: Option<String>,
pub code: Option<u64>,
pub error: Option<NomupayInnerError>,
pub status_code: Option<u16>,
pub detail: Option<Vec<DetailsType>>,
}
pub struct NomupayAuthType {
pub(super) kid: Secret<String>,
#[cfg(feature = "payouts")]
pub(super) eid: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for NomupayAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
#[cfg(feature = "payouts")]
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
kid: api_key.to_owned(),
eid: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum NomupayPaymentStatus {
Pending,
Processed,
Failed,
#[default]
Processing,
Scheduled,
PendingAccountActivation,
PendingTransferMethodCreation,
PendingAccountKyc,
}
impl From<NomupayPaymentStatus> for PayoutStatus {
fn from(item: NomupayPaymentStatus) -> Self {
match item {
NomupayPaymentStatus::Processed => Self::Success,
NomupayPaymentStatus::Failed => Self::Failed,
NomupayPaymentStatus::Processing
| NomupayPaymentStatus::Pending
| NomupayPaymentStatus::Scheduled
| NomupayPaymentStatus::PendingAccountActivation
| NomupayPaymentStatus::PendingTransferMethodCreation
| NomupayPaymentStatus::PendingAccountKyc => Self::Pending,
}
}
}
#[cfg(feature = "payouts")]
fn get_profile<F>(
item: &PayoutsRouterData<F>,
entity_type: PayoutEntityType,
) -> Result<Profile, error_stack::Report<errors::ConnectorError>> {
let my_address = Address {
country: item.get_billing_country()?,
state_province: item.get_billing_state()?,
street: item.get_billing_line1()?,
city: item.get_billing_city()?,
postal_code: item.get_billing_zip()?,
};
Ok(Profile {
profile_type: ProfileType::from(entity_type),
first_name: item.get_billing_first_name()?,
last_name: item.get_billing_last_name()?,
date_of_birth: Secret::new("1991-01-01".to_string()), // Query raised with Nomupay regarding why this field is required
gender: NomupayGender::Other, // Query raised with Nomupay regarding why this field is required
email_address: item.get_billing_email()?,
phone_number_country_code: item
.get_billing_phone()
.map(|phone| phone.country_code.clone())?,
phone_number: Some(item.get_billing_phone_number()?),
address: my_address,
})
}
// PoRecipient Request
#[cfg(feature = "payouts")]
impl<F> TryFrom<&PayoutsRouterData<F>> for OnboardSubAccountRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let request = item.request.to_owned();
let payout_type = request.payout_type;
let profile = get_profile(item, request.entity_type)?;
let nomupay_auth_type = NomupayAuthType::try_from(&item.connector_auth_type)?;
match payout_type {
Some(common_enums::PayoutType::Bank) => Ok(Self {
account_id: nomupay_auth_type.eid,
client_sub_account_id: Secret::new(item.connector_request_reference_id.clone()),
profile,
}),
_ => Err(errors::ConnectorError::NotImplemented(
"This payment method is not implemented for Nomupay".to_string(),
)
.into()),
}
}
}
// PoRecipient Response
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, OnboardSubAccountResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, OnboardSubAccountResponse>,
) -> Result<Self, Self::Error> {
let response: OnboardSubAccountResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::RequiresVendorAccountCreation),
connector_payout_id: Some(response.id.to_string()),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
}),
..item.data
})
}
}
// PoRecipientAccount Request
#[cfg(feature = "payouts")]
impl<F> TryFrom<&PayoutsRouterData<F>> for OnboardTransferMethodRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &PayoutsRouterData<F>) -> Result<Self, Self::Error> {
let payout_method_data = item.get_payout_method_data()?;
match payout_method_data {
api_models::payouts::PayoutMethodData::Bank(bank) => match bank {
api_models::payouts::Bank::Sepa(bank_details) => {
let bank_account = BankAccount {
bank_id: bank_details.bic,
account_id: bank_details.iban,
};
let country_iso2_code = item
.get_billing_country()
.unwrap_or(enums::CountryAlpha2::CA);
let profile = get_profile(item, item.request.entity_type)?;
Ok(Self {
country_code: country_iso2_code,
currency_code: item.request.destination_currency,
transfer_method_type: TransferMethodType::BankAccount,
display_name: item.get_billing_full_name()?,
bank_account,
profile,
})
}
other_bank => Err(errors::ConnectorError::NotSupported {
message: format!("{other_bank:?} is not supported"),
connector: "nomupay",
}
.into()),
},
_ => Err(errors::ConnectorError::NotImplemented(
"This payment method is not implemented for Nomupay".to_string(),
)
.into()),
}
}
}
// PoRecipientAccount response
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, OnboardTransferMethodResponse>>
for PayoutsRouterData<F>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, OnboardTransferMethodResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::RequiresCreation),
connector_payout_id: Some(item.response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
}),
..item.data
})
}
}
// PoFulfill Request
#[cfg(feature = "payouts")]
impl<F> TryFrom<(&PayoutsRouterData<F>, FloatMajorUnit)> for NomupayPaymentRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(item, amount): (&PayoutsRouterData<F>, FloatMajorUnit),
) -> Result<Self, Self::Error> {
let nomupay_auth_type = NomupayAuthType::try_from(&item.connector_auth_type)?;
let destination = item.request.clone().get_connector_transfer_method_id()?;
Ok(Self {
source_id: nomupay_auth_type.eid,
destination_id: Secret::new(destination),
payment_reference: item.connector_request_reference_id.clone(),
amount,
currency_code: item.request.destination_currency,
purpose: PURPOSE_OF_PAYMENT_IS_OTHER.to_string(),
description: item.description.clone(),
internal_memo: item.description.clone(),
})
}
}
// PoFulfill response
#[cfg(feature = "payouts")]
impl<F> TryFrom<PayoutsResponseRouterData<F, NomupayPaymentResponse>> for PayoutsRouterData<F> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: PayoutsResponseRouterData<F, NomupayPaymentResponse>,
) -> Result<Self, Self::Error> {
let response: NomupayPaymentResponse = item.response;
Ok(Self {
response: Ok(PayoutsResponseData {
status: Some(PayoutStatus::from(response.status)),
connector_payout_id: Some(response.id),
payout_eligible: None,
should_add_next_step_to_process_tracker: false,
error_code: None,
error_message: None,
}),
..item.data
})
}
}
|
crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
|
hyperswitch_connectors
|
full_file
| 3,924
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl masking::SerializableSecret for Address {}
|
crates/hyperswitch_domain_models/src/address.rs
|
hyperswitch_domain_models
|
impl_block
| 8
|
rust
| null |
Address
|
masking::SerializableSecret for
|
impl masking::SerializableSecret for for Address
| null | null | null | null | null | null | null | null |
impl ResourceExt for Resource {
fn entities(&self) -> Vec<EntityType> {
match self {
#(#entity_impl_res),*
}
}
}
|
crates/router_derive/src/macros/generate_permissions.rs
|
router_derive
|
impl_block
| 36
|
rust
| null |
Resource
|
ResourceExt for
|
impl ResourceExt for for Resource
| null | null | null | null | null | null | null | null |
pub async fn customer_retrieve(
state: web::Data<routes::AppState>,
req: HttpRequest,
path: web::Path<id_type::CustomerId>,
) -> HttpResponse {
let customer_id = path.into_inner();
let flow = Flow::CustomersRetrieve;
Box::pin(wrap::compatibility_api_wrap::<
_,
_,
_,
_,
_,
types::CustomerRetrieveResponse,
errors::StripeErrorCode,
_,
>(
flow,
state.into_inner(),
&req,
customer_id,
|state, auth: auth::AuthenticationData, customer_id, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
customers::retrieve_customer(state, merchant_context, None, customer_id)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: false,
}),
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/compatibility/stripe/customers.rs
|
router
|
function_signature
| 230
|
rust
| null | null | null | null |
customer_retrieve
| null | null | null | null | null | null | null |
Documentation: api-reference/v2/merchant-account/merchant-account--profile-list.mdx
# Type: Doc File
---
openapi: get /v2/merchant-accounts/{id}/profiles
---
|
api-reference/v2/merchant-account/merchant-account--profile-list.mdx
| null |
doc_file
| 42
|
doc
| null | null | null | null | null | null | null | null | null | null | null | null |
pub struct MandatePaymentRequest {
pub amount: FloatMajorUnit,
pub currency: Currency,
pub capture_method: String,
pub payment_method_id: Secret<String>,
pub channel_properties: ChannelProperties,
}
|
crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 46
|
rust
|
MandatePaymentRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub struct CaptureNew {
pub capture_id: String,
pub payment_id: common_utils::id_type::PaymentId,
pub merchant_id: common_utils::id_type::MerchantId,
pub status: storage_enums::CaptureStatus,
pub amount: MinorUnit,
pub currency: Option<storage_enums::Currency>,
pub connector: String,
pub error_message: Option<String>,
pub error_code: Option<String>,
pub error_reason: Option<String>,
pub tax_amount: Option<MinorUnit>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub authorized_attempt_id: String,
pub connector_capture_id: Option<ConnectorTransactionId>,
pub capture_sequence: i16,
pub connector_response_reference_id: Option<String>,
/// INFO: This field is deprecated and replaced by processor_capture_data
pub connector_capture_data: Option<String>,
pub processor_capture_data: Option<String>,
}
|
crates/diesel_models/src/capture.rs
|
diesel_models
|
struct_definition
| 237
|
rust
|
CaptureNew
| null | null | null | null | null | null | null | null | null | null | null |
pub struct AirwallexPaymentsResponse {
status: AirwallexPaymentStatus,
//Unique identifier for the PaymentIntent
id: String,
amount: Option<f32>,
//ID of the PaymentConsent related to this PaymentIntent
payment_consent_id: Option<Secret<String>>,
next_action: Option<AirwallexPaymentsNextAction>,
}
|
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 78
|
rust
|
AirwallexPaymentsResponse
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/api_models/src/analytics/active_payments.rs
Public functions: 1
Public structs: 4
use std::{
collections::hash_map::DefaultHasher,
hash::{Hash, Hasher},
};
use super::NameDescription;
#[derive(
Clone,
Debug,
Hash,
PartialEq,
Eq,
serde::Serialize,
serde::Deserialize,
strum::Display,
strum::EnumIter,
strum::AsRefStr,
)]
#[strum(serialize_all = "snake_case")]
#[serde(rename_all = "snake_case")]
pub enum ActivePaymentsMetrics {
ActivePayments,
}
pub mod metric_behaviour {
pub struct ActivePayments;
}
impl From<ActivePaymentsMetrics> for NameDescription {
fn from(value: ActivePaymentsMetrics) -> Self {
Self {
name: value.to_string(),
desc: String::new(),
}
}
}
#[derive(Debug, serde::Serialize, Eq)]
pub struct ActivePaymentsMetricsBucketIdentifier {
pub time_bucket: Option<String>,
}
impl ActivePaymentsMetricsBucketIdentifier {
pub fn new(time_bucket: Option<String>) -> Self {
Self { time_bucket }
}
}
impl Hash for ActivePaymentsMetricsBucketIdentifier {
fn hash<H: Hasher>(&self, state: &mut H) {
self.time_bucket.hash(state);
}
}
impl PartialEq for ActivePaymentsMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
#[derive(Debug, serde::Serialize)]
pub struct ActivePaymentsMetricsBucketValue {
pub active_payments: Option<u64>,
}
#[derive(Debug, serde::Serialize)]
pub struct MetricsBucketResponse {
#[serde(flatten)]
pub values: ActivePaymentsMetricsBucketValue,
#[serde(flatten)]
pub dimensions: ActivePaymentsMetricsBucketIdentifier,
}
|
crates/api_models/src/analytics/active_payments.rs
|
api_models
|
full_file
| 428
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl ConnectorPreAuthentication for Threedsecureio {}
|
crates/hyperswitch_connectors/src/connectors/threedsecureio.rs
|
hyperswitch_connectors
|
impl_block
| 10
|
rust
| null |
Threedsecureio
|
ConnectorPreAuthentication for
|
impl ConnectorPreAuthentication for for Threedsecureio
| null | null | null | null | null | null | null | null |
impl ConnectorCommon for Hipay {
fn id(&self) -> &'static str {
"hipay"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.hipay.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = hipay::HipayAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
let auth_key = format!("{}:{}", auth.api_key.peek(), auth.key1.peek());
let auth_header = format!("Basic {}", BASE64_ENGINE.encode(auth_key));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth_header.into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: hipay::HipayErrorResponse =
res.response
.parse_struct("HipayErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code.to_string(),
message: response.message,
reason: response.description,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
|
crates/hyperswitch_connectors/src/connectors/hipay.rs
|
hyperswitch_connectors
|
impl_block
| 401
|
rust
| null |
Hipay
|
ConnectorCommon for
|
impl ConnectorCommon for for Hipay
| null | null | null | null | null | null | null | null |
impl api::PaymentCapture for Santander {}
|
crates/hyperswitch_connectors/src/connectors/santander.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Santander
|
api::PaymentCapture for
|
impl api::PaymentCapture for for Santander
| null | null | null | null | null | null | null | null |
pub struct LabelWithStatusEliminationEventResponse {
pub label: String,
pub elimination_information: Option<EliminationInformationEventResponse>,
}
|
crates/router/src/core/payments/routing/utils.rs
|
router
|
struct_definition
| 30
|
rust
|
LabelWithStatusEliminationEventResponse
| null | null | null | null | null | null | null | null | null | null | null |
Documentation: api-reference/v2/payments/payments--confirm-intent.mdx
# Type: Doc File
---
openapi: post /v2/payments/{id}/confirm-intent
---
|
api-reference/v2/payments/payments--confirm-intent.mdx
| null |
doc_file
| 41
|
doc
| null | null | null | null | null | null | null | null | null | null | null | null |
Documentation: crates/api_models/README.md
# Type: Doc File
# API Models
Request/response models for the `router` crate.
|
crates/api_models/README.md
| null |
doc_file
| 29
|
doc
| null | null | null | null | null | null | null | null | null | null | null | null |
pub struct VoidStatus {
pub authorization: SilverflowVoidAuthorizationStatus,
}
|
crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 16
|
rust
|
VoidStatus
| null | null | null | null | null | null | null | null | null | null | null |
pub struct ArchipelWalletInformation {
wallet_indicator: Option<String>,
wallet_provider: ArchipelWalletProvider,
wallet_cryptogram: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 33
|
rust
|
ArchipelWalletInformation
| null | null | null | null | null | null | null | null | null | null | null |
pub struct ExchangeTokenRequest {
pub public_token: String,
}
|
crates/pm_auth/src/types.rs
|
pm_auth
|
struct_definition
| 14
|
rust
|
ExchangeTokenRequest
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/openapi/src/routes/poll.rs
Public functions: 1
/// Poll - Retrieve Poll Status
#[utoipa::path(
get,
path = "/poll/status/{poll_id}",
params(
("poll_id" = String, Path, description = "The identifier for poll")
),
responses(
(status = 200, description = "The poll status was retrieved successfully", body = PollResponse),
(status = 404, description = "Poll not found")
),
tag = "Poll",
operation_id = "Retrieve Poll Status",
security(("publishable_key" = []))
)]
pub async fn retrieve_poll_status() {}
|
crates/openapi/src/routes/poll.rs
|
openapi
|
full_file
| 145
| null | null | null | null | null | null | null | null | null | null | null | null | null |
let router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
customer,
&merchant_connector_account_type_details,
None,
None,
)
.await?;
Ok((
merchant_connector_account_type_details,
updated_customer,
router_data,
))
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[allow(clippy::type_complexity)]
#[instrument(skip_all)]
pub async fn call_connector_service_prerequisites_for_external_vault_proxy<
F,
RouterDReq,
ApiRequest,
D,
>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
is_retry_payment: bool,
should_retry_with_pan: bool,
all_keys_required: Option<bool>,
) -> RouterResult<(
domain::MerchantConnectorAccountTypeDetails,
domain::MerchantConnectorAccountTypeDetails,
Option<storage::CustomerUpdate>,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
)>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
{
// get merchant connector account related to external vault
let external_vault_source: id_type::MerchantConnectorAccountId = business_profile
.external_vault_connector_details
.clone()
.map(|connector_details| connector_details.vault_connector_id.clone())
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("mca_id not present for external vault")?;
let external_vault_merchant_connector_account_type_details =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
Some(&external_vault_source),
)
.await?,
));
let (merchant_connector_account_type_details, updated_customer, router_data) =
call_connector_service_prerequisites(
state,
req_state,
merchant_context,
connector,
operation,
payment_data,
customer,
call_connector_action,
schedule_time,
header_payload,
frm_suggestion,
business_profile,
is_retry_payment,
should_retry_with_pan,
all_keys_required,
)
.await?;
Ok((
merchant_connector_account_type_details,
external_vault_merchant_connector_account_type_details,
updated_customer,
router_data,
))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn internal_call_connector_service_prerequisites<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
business_profile: &domain::Profile,
) -> RouterResult<(
domain::MerchantConnectorAccountTypeDetails,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
)>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
{
let merchant_connector_details =
payment_data
.get_merchant_connector_details()
.ok_or_else(|| {
error_stack::report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Merchant connector details not found in payment data")
})?;
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(
merchant_connector_details,
);
operation
.to_domain()?
.populate_payment_data(
state,
payment_data,
merchant_context,
business_profile,
&connector,
)
.await?;
let router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
&None,
&merchant_connector_account,
None,
None,
)
.await?;
Ok((merchant_connector_account, router_data))
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn connector_service_decider<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
business_profile: &domain::Profile,
return_raw_connector_response: Option<bool>,
merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails,
) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
{
let mut router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
&None,
&merchant_connector_account_type_details,
None,
None,
)
.await?;
// do order creation
let should_call_unified_connector_service = should_call_unified_connector_service(
state,
merchant_context,
&router_data,
Some(payment_data),
)
.await?;
let (connector_request, should_continue_further) = if !should_call_unified_connector_service {
let mut should_continue_further = true;
let should_continue = match router_data
.create_order_at_connector(state, &connector, should_continue_further)
.await?
{
Some(create_order_response) => {
if let Ok(order_id) = create_order_response.clone().create_order_result {
payment_data.set_connector_response_reference_id(Some(order_id))
}
// Set the response in routerdata response to carry forward
router_data
.update_router_data_with_create_order_response(create_order_response.clone());
create_order_response.create_order_result.ok().map(|_| ())
}
// If create order is not required, then we can proceed with further processing
None => Some(()),
};
let should_continue: (Option<common_utils::request::Request>, bool) = match should_continue
{
Some(_) => {
router_data
.build_flow_specific_connector_request(
state,
&connector,
call_connector_action.clone(),
)
.await?
}
None => (None, false),
};
should_continue
} else {
// If unified connector service is called, these values are not used
// as the request is built in the unified connector service call
(None, false)
};
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
None, // customer is not used in internal flows
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
None, // frm_suggestion is not used in internal flows
header_payload.clone(),
)
.await?;
record_time_taken_with(|| async {
if should_call_unified_connector_service {
router_env::logger::info!(
"Processing payment through UCS gateway system- payment_id={}, attempt_id={}",
payment_data.get_payment_intent().id.get_string_repr(),
payment_data.get_payment_attempt().id.get_string_repr()
);
router_data
.call_unified_connector_service(
state,
merchant_connector_account_type_details.clone(),
merchant_context,
)
.await?;
Ok(router_data)
} else {
Err(
errors::ApiErrorResponse::InternalServerError
)
.attach_printable("Unified connector service is down and traditional connector service fallback is not implemented")
}
})
.await
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn decide_unified_connector_service_call<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
business_profile: &domain::Profile,
is_retry_payment: bool,
should_retry_with_pan: bool,
return_raw_connector_response: Option<bool>,
merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails,
mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
updated_customer: Option<storage::CustomerUpdate>,
) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
{
record_time_taken_with(|| async {
if should_call_unified_connector_service(
state,
merchant_context,
&router_data,
Some(payment_data),
)
.await?
{
router_env::logger::info!(
"Executing payment through UCS gateway system - payment_id={}, attempt_id={}",
payment_data.get_payment_intent().id.get_string_repr(),
payment_data.get_payment_attempt().id.get_string_repr()
);
if should_add_task_to_process_tracker(payment_data) {
operation
.to_domain()?
.add_task_to_process_tracker(
state,
payment_data.get_payment_attempt(),
false,
schedule_time,
)
.await
.map_err(|error| logger::error!(process_tracker_error=?error))
.ok();
}
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
frm_suggestion,
header_payload.clone(),
)
.await?;
router_data
.call_unified_connector_service(
state,
merchant_connector_account_type_details.clone(),
merchant_context,
)
.await?;
Ok(router_data)
} else {
router_env::logger::info!(
"Processing payment through Direct gateway system - payment_id={}, attempt_id={}",
payment_data.get_payment_intent().id.get_string_repr(),
payment_data.get_payment_attempt().id.get_string_repr()
);
call_connector_service(
state,
req_state,
merchant_context,
connector,
operation,
payment_data,
customer,
call_connector_action,
schedule_time,
header_payload,
frm_suggestion,
business_profile,
is_retry_payment,
should_retry_with_pan,
return_raw_connector_response,
merchant_connector_account_type_details,
router_data,
updated_customer,
)
.await
}
})
.await
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn call_unified_connector_service_for_external_proxy<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
_connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
customer: &Option<domain::Customer>,
_call_connector_action: CallConnectorAction,
_schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
frm_suggestion: Option<storage_enums::FrmSuggestion>,
_business_profile: &domain::Profile,
_is_retry_payment: bool,
_should_retry_with_pan: bool,
_return_raw_connector_response: Option<bool>,
merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails,
external_vault_merchant_connector_account_type_details: domain::MerchantConnectorAccountTypeDetails,
mut router_data: RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
_updated_customer: Option<storage::CustomerUpdate>,
) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
{
record_time_taken_with(|| async {
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
frm_suggestion,
header_payload.clone(),
)
.await?;
router_data
.call_unified_connector_service_with_external_vault_proxy(
state,
merchant_connector_account_type_details.clone(),
external_vault_merchant_connector_account_type_details.clone(),
merchant_context,
)
.await?;
Ok(router_data)
})
.await
}
#[cfg(feature = "v1")]
// This function does not perform the tokenization action, as the payment method is not saved in this flow.
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn proxy_for_call_connector_service<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
customer: &Option<domain::Customer>,
call_connector_action: CallConnectorAction,
validate_result: &operations::ValidateResult,
schedule_time: Option<time::PrimitiveDateTime>,
header_payload: HeaderPayload,
business_profile: &domain::Profile,
return_raw_connector_response: Option<bool>,
) -> RouterResult<(
RouterData<F, RouterDReq, router_types::PaymentsResponseData>,
helpers::MerchantConnectorAccountType,
)>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
{
let stime_connector = Instant::now();
let merchant_connector_account = construct_profile_id_and_get_mca(
state,
merchant_context,
payment_data,
&connector.connector_name.to_string(),
connector.merchant_connector_id.as_ref(),
false,
)
.await?;
if payment_data
.get_payment_attempt()
.merchant_connector_id
.is_none()
{
payment_data.set_merchant_connector_id_in_attempt(merchant_connector_account.get_mca_id());
}
let merchant_recipient_data = None;
let mut router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
customer,
&merchant_connector_account,
merchant_recipient_data,
None,
)
.await?;
let add_access_token_result = router_data
.add_access_token(
state,
&connector,
merchant_context,
payment_data.get_creds_identifier(),
)
.await?;
router_data = router_data.add_session_token(state, &connector).await?;
let mut should_continue_further = access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&call_connector_action,
);
(router_data, should_continue_further) = complete_preprocessing_steps_if_required(
state,
&connector,
payment_data,
router_data,
operation,
should_continue_further,
)
.await?;
if let Ok(router_types::PaymentsResponseData::PreProcessingResponse {
session_token: Some(session_token),
..
}) = router_data.response.to_owned()
{
payment_data.push_sessions_token(session_token);
};
let (connector_request, should_continue_further) = if should_continue_further {
// Check if the actual flow specific request can be built with available data
router_data
.build_flow_specific_connector_request(state, &connector, call_connector_action.clone())
.await?
} else {
(None, false)
};
if should_add_task_to_process_tracker(payment_data) {
operation
.to_domain()?
.add_task_to_process_tracker(
state,
payment_data.get_payment_attempt(),
validate_result.requeue,
schedule_time,
)
.await
.map_err(|error| logger::error!(process_tracker_error=?error))
.ok();
}
let updated_customer = None;
let frm_suggestion = None;
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
customer.clone(),
merchant_context.get_merchant_account().storage_scheme,
updated_customer,
merchant_context.get_merchant_key_store(),
frm_suggestion,
header_payload.clone(),
)
.await?;
let router_data = if should_continue_further {
// The status of payment_attempt and intent will be updated in the previous step
// update this in router_data.
// This is added because few connector integrations do not update the status,
// and rely on previous status set in router_data
router_data.status = payment_data.get_payment_attempt().status;
router_data
.decide_flows(
state,
&connector,
call_connector_action,
connector_request,
business_profile,
header_payload.clone(),
return_raw_connector_response,
)
.await
} else {
Ok(router_data)
}?;
let etime_connector = Instant::now();
let duration_connector = etime_connector.saturating_duration_since(stime_connector);
tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis()));
Ok((router_data, merchant_connector_account))
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn proxy_for_call_connector_service<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
business_profile: &domain::Profile,
return_raw_connector_response: Option<bool>,
) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
{
let stime_connector = Instant::now();
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
connector.merchant_connector_id.as_ref(),
)
.await?,
));
operation
.to_domain()?
.populate_payment_data(
state,
payment_data,
merchant_context,
business_profile,
&connector,
)
.await?;
let mut router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
&None,
&merchant_connector_account,
None,
None,
)
.await?;
let add_access_token_result = router_data
.add_access_token(
state,
&connector,
merchant_context,
payment_data.get_creds_identifier(),
)
.await?;
router_data = router_data.add_session_token(state, &connector).await?;
let mut should_continue_further = access_token::update_router_data_with_access_token_result(
&add_access_token_result,
&mut router_data,
&call_connector_action,
);
let (connector_request, should_continue_further) = if should_continue_further {
router_data
.build_flow_specific_connector_request(state, &connector, call_connector_action.clone())
.await?
} else {
(None, false)
};
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
None,
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
None,
header_payload.clone(),
)
.await?;
let router_data = if should_continue_further {
router_data
.decide_flows(
state,
&connector,
call_connector_action,
connector_request,
business_profile,
header_payload.clone(),
return_raw_connector_response,
)
.await
} else {
Ok(router_data)
}?;
let etime_connector = Instant::now();
let duration_connector = etime_connector.saturating_duration_since(stime_connector);
tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis()));
Ok(router_data)
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
#[instrument(skip_all)]
pub async fn call_connector_service_for_external_vault_proxy<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: &domain::MerchantContext,
connector: api::ConnectorData,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
payment_data: &mut D,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
business_profile: &domain::Profile,
return_raw_connector_response: Option<bool>,
) -> RouterResult<RouterData<F, RouterDReq, router_types::PaymentsResponseData>>
where
F: Send + Clone + Sync,
RouterDReq: Send + Sync,
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, RouterDReq, router_types::PaymentsResponseData>,
RouterData<F, RouterDReq, router_types::PaymentsResponseData>: Feature<F, RouterDReq> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, RouterDReq, router_types::PaymentsResponseData>,
{
let stime_connector = Instant::now();
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
connector.merchant_connector_id.as_ref(),
)
.await?,
));
operation
.to_domain()?
.populate_payment_data(
state,
payment_data,
merchant_context,
business_profile,
&connector,
)
.await?;
let mut router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
&None,
&merchant_connector_account,
None,
None,
)
.await?;
// let add_access_token_result = router_data
// .add_access_token(
// state,
// &connector,
// merchant_context,
// payment_data.get_creds_identifier(),
// )
// .await?;
// router_data = router_data.add_session_token(state, &connector).await?;
// let mut should_continue_further = access_token::update_router_data_with_access_token_result(
// &add_access_token_result,
// &mut router_data,
// &call_connector_action,
// );
let should_continue_further = true;
let (connector_request, should_continue_further) = if should_continue_further {
router_data
.build_flow_specific_connector_request(state, &connector, call_connector_action.clone())
.await?
} else {
(None, false)
};
(_, *payment_data) = operation
.to_update_tracker()?
.update_trackers(
state,
req_state,
payment_data.clone(),
None,
merchant_context.get_merchant_account().storage_scheme,
None,
merchant_context.get_merchant_key_store(),
None,
header_payload.clone(),
)
.await?;
let router_data = if should_continue_further {
router_data
.decide_flows(
state,
&connector,
call_connector_action,
connector_request,
business_profile,
header_payload.clone(),
return_raw_connector_response,
)
.await
} else {
Ok(router_data)
}?;
let etime_connector = Instant::now();
let duration_connector = etime_connector.saturating_duration_since(stime_connector);
tracing::info!(duration = format!("Duration taken: {}", duration_connector.as_millis()));
Ok(router_data)
}
struct ApplePayWallet;
struct PazeWallet;
struct GooglePayWallet;
#[async_trait::async_trait]
pub trait WalletFlow<F, D>: Send + Sync
where
F: Send + Clone,
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
/// Check if wallet data is already decrypted and return token if so
fn check_predecrypted_token(
&self,
_payment_data: &D,
) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> {
// Default implementation returns None (no pre-decrypted data)
Ok(None)
}
fn decide_wallet_flow(
&self,
state: &SessionState,
payment_data: &D,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse>;
async fn decrypt_wallet_token(
&self,
wallet_flow: &DecideWalletFlow,
payment_data: &D,
) -> CustomResult<PaymentMethodToken, errors::ApiErrorResponse>;
}
#[async_trait::async_trait]
impl<F, D> WalletFlow<F, D> for PazeWallet
where
F: Send + Clone,
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
fn decide_wallet_flow(
&self,
state: &SessionState,
_payment_data: &D,
_merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse> {
let paze_keys = state
.conf
.paze_decrypt_keys
.as_ref()
.get_required_value("Paze decrypt keys")
.attach_printable("Paze decrypt keys not found in the configuration")?;
let wallet_flow = DecideWalletFlow::PazeDecrypt(PazePaymentProcessingDetails {
paze_private_key: paze_keys.get_inner().paze_private_key.clone(),
paze_private_key_passphrase: paze_keys.get_inner().paze_private_key_passphrase.clone(),
});
Ok(Some(wallet_flow))
}
async fn decrypt_wallet_token(
&self,
wallet_flow: &DecideWalletFlow,
payment_data: &D,
) -> CustomResult<PaymentMethodToken, errors::ApiErrorResponse> {
let paze_payment_processing_details = wallet_flow
.get_paze_payment_processing_details()
.get_required_value("Paze payment processing details")
.attach_printable(
"Paze payment processing details not found in Paze decryption flow",
)?;
let paze_wallet_data = payment_data
.get_payment_method_data()
.and_then(|payment_method_data| payment_method_data.get_wallet_data())
.and_then(|wallet_data| wallet_data.get_paze_wallet_data())
.get_required_value("Paze wallet token").attach_printable(
"Paze wallet data not found in the payment method data during the Paze decryption flow",
)?;
let paze_data = decrypt_paze_token(
paze_wallet_data.clone(),
paze_payment_processing_details.paze_private_key.clone(),
paze_payment_processing_details
.paze_private_key_passphrase
.clone(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to decrypt paze token")?;
let paze_decrypted_data = paze_data
.parse_value::<hyperswitch_domain_models::router_data::PazeDecryptedData>(
"PazeDecryptedData",
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to parse PazeDecryptedData")?;
Ok(PaymentMethodToken::PazeDecrypt(Box::new(
paze_decrypted_data,
)))
}
}
#[async_trait::async_trait]
impl<F, D> WalletFlow<F, D> for ApplePayWallet
where
F: Send + Clone,
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
fn check_predecrypted_token(
&self,
payment_data: &D,
) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> {
let apple_pay_wallet_data = payment_data
.get_payment_method_data()
.and_then(|payment_method_data| payment_method_data.get_wallet_data())
.and_then(|wallet_data| wallet_data.get_apple_pay_wallet_data());
let result = if let Some(data) = apple_pay_wallet_data {
match &data.payment_data {
common_payments_types::ApplePayPaymentData::Encrypted(_) => None,
common_payments_types::ApplePayPaymentData::Decrypted(
apple_pay_predecrypt_data,
) => {
helpers::validate_card_expiry(
&apple_pay_predecrypt_data.application_expiration_month,
&apple_pay_predecrypt_data.application_expiration_year,
)?;
Some(PaymentMethodToken::ApplePayDecrypt(Box::new(
apple_pay_predecrypt_data.clone(),
)))
}
}
} else {
None
};
Ok(result)
}
fn decide_wallet_flow(
&self,
state: &SessionState,
payment_data: &D,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
) -> CustomResult<Option<DecideWalletFlow>, errors::ApiErrorResponse> {
let apple_pay_metadata = check_apple_pay_metadata(state, Some(merchant_connector_account));
add_apple_pay_flow_metrics(
&apple_pay_metadata,
payment_data.get_payment_attempt().connector.clone(),
payment_data.get_payment_attempt().merchant_id.clone(),
);
let wallet_flow = match apple_pay_metadata {
Some(domain::ApplePayFlow::Simplified(payment_processing_details)) => Some(
DecideWalletFlow::ApplePayDecrypt(payment_processing_details),
),
Some(domain::ApplePayFlow::Manual) | None => None,
};
Ok(wallet_flow)
}
async fn decrypt_wallet_token(
&self,
wallet_flow: &DecideWalletFlow,
payment_data: &D,
) -> CustomResult<PaymentMethodToken, errors::ApiErrorResponse> {
let apple_pay_payment_processing_details = wallet_flow
.get_apple_pay_payment_processing_details()
.get_required_value("Apple Pay payment processing details")
.attach_printable(
"Apple Pay payment processing details not found in Apple Pay decryption flow",
)?;
let apple_pay_wallet_data = payment_data
.get_payment_method_data()
.and_then(|payment_method_data| payment_method_data.get_wallet_data())
.and_then(|wallet_data| wallet_data.get_apple_pay_wallet_data())
.get_required_value("Apple Pay wallet token").attach_printable(
"Apple Pay wallet data not found in the payment method data during the Apple Pay decryption flow",
)?;
let apple_pay_data =
ApplePayData::token_json(domain::WalletData::ApplePay(apple_pay_wallet_data.clone()))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to parse apple pay token to json")?
.decrypt(
&apple_pay_payment_processing_details.payment_processing_certificate,
&apple_pay_payment_processing_details.payment_processing_certificate_key,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to decrypt apple pay token")?;
let apple_pay_predecrypt_internal = apple_pay_data
.parse_value::<hyperswitch_domain_models::router_data::ApplePayPredecryptDataInternal>(
"ApplePayPredecryptDataInternal",
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"failed to parse decrypted apple pay response to ApplePayPredecryptData",
)?;
let apple_pay_predecrypt =
common_types::payments::ApplePayPredecryptData::try_from(apple_pay_predecrypt_internal)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"failed to convert ApplePayPredecryptDataInternal to ApplePayPredecryptData",
)?;
Ok(PaymentMethodToken::ApplePayDecrypt(Box::new(
apple_pay_predecrypt,
)))
}
}
#[async_trait::async_trait]
impl<F, D> WalletFlow<F, D> for GooglePayWallet
where
F: Send + Clone,
D: OperationSessionGetters<F> + Send + Sync + Clone,
{
fn check_predecrypted_token(
&self,
payment_data: &D,
) -> CustomResult<Option<PaymentMethodToken>, errors::ApiErrorResponse> {
let google_pay_wallet_data = payment_data
.get_payment_method_data()
|
crates/router/src/core/payments.rs#chunk4
|
router
|
chunk
| 8,184
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl api::MandateSetup for Inespay {}
|
crates/hyperswitch_connectors/src/connectors/inespay.rs
|
hyperswitch_connectors
|
impl_block
| 12
|
rust
| null |
Inespay
|
api::MandateSetup for
|
impl api::MandateSetup for for Inespay
| null | null | null | null | null | null | null | null |
impl ConnectorAuthenticationMap {
pub fn inner(&self) -> &HashMap<String, ConnectorAuthType> {
&self.0
}
/// # Panics
///
/// Will panic if `CONNECTOR_AUTH_FILE_PATH` env is not set
#[allow(clippy::expect_used)]
pub fn new() -> Self {
// Do `export CONNECTOR_AUTH_FILE_PATH="/hyperswitch/crates/router/tests/connectors/sample_auth.toml"`
// before running tests in shell
let path = env::var("CONNECTOR_AUTH_FILE_PATH")
.expect("connector authentication file path not set");
// Read the file contents to a JsonString
let contents =
&std::fs::read_to_string(path).expect("Failed to read connector authentication file");
// Deserialize the JsonString to a HashMap
let auth_config: HashMap<String, toml::Value> =
toml::from_str(contents).expect("Failed to deserialize TOML file");
// auth_config contains the data in below given format:
// {
// "connector_name": Table(
// {
// "api_key": String(
// "API_Key",
// ),
// "api_secret": String(
// "Secret key",
// ),
// "key1": String(
// "key1",
// ),
// "key2": String(
// "key2",
// ),
// },
// ),
// "connector_name": Table(
// ...
// }
// auth_map refines and extracts required information
let auth_map = auth_config
.into_iter()
.map(|(connector_name, config)| {
let auth_type = match config {
toml::Value::Table(mut table) => {
if let Some(auth_key_map_value) = table.remove("auth_key_map") {
// This is a CurrencyAuthKey
if let toml::Value::Table(auth_key_map_table) = auth_key_map_value {
let mut parsed_auth_map = HashMap::new();
for (currency, val) in auth_key_map_table {
if let Ok(currency_enum) =
currency.parse::<common_enums::Currency>()
{
parsed_auth_map
.insert(currency_enum, Secret::new(val.to_string()));
}
}
ConnectorAuthType::CurrencyAuthKey {
auth_key_map: parsed_auth_map,
}
} else {
ConnectorAuthType::NoKey
}
} else {
match (
table.get("api_key"),
table.get("key1"),
table.get("api_secret"),
table.get("key2"),
) {
(Some(api_key), None, None, None) => ConnectorAuthType::HeaderKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
},
(Some(api_key), Some(key1), None, None) => {
ConnectorAuthType::BodyKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
key1: Secret::new(
key1.as_str().unwrap_or_default().to_string(),
),
}
}
(Some(api_key), Some(key1), Some(api_secret), None) => {
ConnectorAuthType::SignatureKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
key1: Secret::new(
key1.as_str().unwrap_or_default().to_string(),
),
api_secret: Secret::new(
api_secret.as_str().unwrap_or_default().to_string(),
),
}
}
(Some(api_key), Some(key1), Some(api_secret), Some(key2)) => {
ConnectorAuthType::MultiAuthKey {
api_key: Secret::new(
api_key.as_str().unwrap_or_default().to_string(),
),
key1: Secret::new(
key1.as_str().unwrap_or_default().to_string(),
),
api_secret: Secret::new(
api_secret.as_str().unwrap_or_default().to_string(),
),
key2: Secret::new(
key2.as_str().unwrap_or_default().to_string(),
),
}
}
_ => ConnectorAuthType::NoKey,
}
}
}
_ => ConnectorAuthType::NoKey,
};
(connector_name, auth_type)
})
.collect();
Self(auth_map)
}
}
|
crates/test_utils/src/connector_auth.rs
|
test_utils
|
impl_block
| 971
|
rust
| null |
ConnectorAuthenticationMap
| null |
impl ConnectorAuthenticationMap
| null | null | null | null | null | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.