text
stringlengths 65
57.3k
| file_path
stringlengths 22
92
| module
stringclasses 38
values | type
stringclasses 7
values | struct_name
stringlengths 3
60
⌀ | impl_count
int64 0
60
⌀ | traits
listlengths 0
59
⌀ | tokens
int64 16
8.19k
| function_name
stringlengths 3
85
⌀ | type_name
stringlengths 1
67
⌀ | trait_name
stringclasses 573
values | method_count
int64 0
31
⌀ | public_method_count
int64 0
19
⌀ | submodule_count
int64 0
56
⌀ | export_count
int64 0
9
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
// Implementation: impl api::PaymentAuthorize for for Nmi
// File: crates/hyperswitch_connectors/src/connectors/nmi.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentAuthorize for for Nmi
|
crates/hyperswitch_connectors/src/connectors/nmi.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Nmi
|
api::PaymentAuthorize for
| 0
| 0
| null | null |
// File: crates/router/src/core/payments/flows/authorize_flow.rs
// Module: router
// Public functions: 2
use std::str::FromStr;
use async_trait::async_trait;
use common_enums as enums;
use common_types::payments as common_payments_types;
use common_utils::{id_type, ucs_types};
use error_stack::ResultExt;
use external_services::grpc_client;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payments::PaymentConfirmData;
use hyperswitch_domain_models::{
errors::api_error_response::ApiErrorResponse, payments as domain_payments,
};
use masking::{ExposeInterface, Secret};
use unified_connector_service_client::payments as payments_grpc;
// use router_env::tracing::Instrument;
use super::{ConstructFlowSpecificData, Feature};
use crate::{
core::{
errors::{ConnectorErrorExt, RouterResult},
mandate,
payments::{
self, access_token, customers, helpers, tokenization, transformers, PaymentData,
},
unified_connector_service::{
build_unified_connector_service_auth_metadata,
handle_unified_connector_service_response_for_payment_authorize,
handle_unified_connector_service_response_for_payment_repeat, ucs_logging_wrapper,
},
},
logger,
routes::{metrics, SessionState},
services::{self, api::ConnectorValidation},
types::{
self, api, domain,
transformers::{ForeignFrom, ForeignTryFrom},
},
utils::OptionExt,
};
#[cfg(feature = "v2")]
#[async_trait]
impl
ConstructFlowSpecificData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> for PaymentConfirmData<api::Authorize>
{
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<domain_payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
> {
Box::pin(transformers::construct_payment_router_data_for_authorize(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
async fn get_merchant_recipient_data<'a>(
&self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
connector: &api::ConnectorData,
) -> RouterResult<Option<types::MerchantRecipientData>> {
let is_open_banking = &self
.payment_attempt
.get_payment_method()
.get_required_value("PaymentMethod")?
.eq(&enums::PaymentMethod::OpenBanking);
if *is_open_banking {
payments::get_merchant_bank_data_for_open_banking_connectors(
merchant_connector_account,
merchant_context,
connector,
state,
)
.await
} else {
Ok(None)
}
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl
ConstructFlowSpecificData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> for PaymentData<api::Authorize>
{
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<domain_payments::HeaderPayload>,
) -> RouterResult<
types::RouterData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
> {
Box::pin(transformers::construct_payment_router_data::<
api::Authorize,
types::PaymentsAuthorizeData,
>(
state,
self.clone(),
connector_id,
merchant_context,
customer,
merchant_connector_account,
merchant_recipient_data,
header_payload,
))
.await
}
async fn get_merchant_recipient_data<'a>(
&self,
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account: &helpers::MerchantConnectorAccountType,
connector: &api::ConnectorData,
) -> RouterResult<Option<types::MerchantRecipientData>> {
match &self.payment_intent.is_payment_processor_token_flow {
Some(true) => Ok(None),
Some(false) | None => {
let is_open_banking = &self
.payment_attempt
.get_payment_method()
.get_required_value("PaymentMethod")?
.eq(&enums::PaymentMethod::OpenBanking);
Ok(if *is_open_banking {
payments::get_merchant_bank_data_for_open_banking_connectors(
merchant_connector_account,
merchant_context,
connector,
state,
)
.await?
} else {
None
})
}
}
}
}
#[async_trait]
impl Feature<api::Authorize, types::PaymentsAuthorizeData> for types::PaymentsAuthorizeRouterData {
async fn decide_flows<'a>(
mut self,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<services::Request>,
business_profile: &domain::Profile,
header_payload: domain_payments::HeaderPayload,
return_raw_connector_response: Option<bool>,
) -> RouterResult<Self> {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
if self.should_proceed_with_authorize() {
self.decide_authentication_type();
logger::debug!(auth_type=?self.auth_type);
let mut auth_router_data = services::execute_connector_processing_step(
state,
connector_integration,
&self,
call_connector_action.clone(),
connector_request,
return_raw_connector_response,
)
.await
.to_payment_failed_response()?;
// Initiating Integrity check
let integrity_result = helpers::check_integrity_based_on_flow(
&auth_router_data.request,
&auth_router_data.response,
);
auth_router_data.integrity_check = integrity_result;
metrics::PAYMENT_COUNT.add(1, &[]); // Move outside of the if block
match auth_router_data.response.clone() {
Err(_) => Ok(auth_router_data),
Ok(authorize_response) => {
// Check if the Capture API should be called based on the connector and other parameters
if super::should_initiate_capture_flow(
&connector.connector_name,
self.request.customer_acceptance,
self.request.capture_method,
self.request.setup_future_usage,
auth_router_data.status,
) {
auth_router_data = Box::pin(process_capture_flow(
auth_router_data,
authorize_response,
state,
connector,
call_connector_action.clone(),
business_profile,
header_payload,
))
.await?;
}
Ok(auth_router_data)
}
}
} else {
Ok(self.clone())
}
}
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 add_session_token<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self>
where
Self: Sized,
{
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::AuthorizeSessionToken,
types::AuthorizeSessionTokenData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let authorize_data = &types::PaymentsAuthorizeSessionTokenRouterData::foreign_from((
&self,
types::AuthorizeSessionTokenData::foreign_from(&self),
));
let resp = services::execute_connector_processing_step(
state,
connector_integration,
authorize_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let mut router_data = self;
router_data.session_token = resp.session_token;
Ok(router_data)
}
async fn add_payment_method_token<'a>(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
tokenization_action: &payments::TokenizationAction,
should_continue_payment: bool,
) -> RouterResult<types::PaymentMethodTokenResult> {
let request = self.request.clone();
tokenization::add_payment_method_token(
state,
connector,
tokenization_action,
self,
types::PaymentMethodTokenizationData::try_from(request)?,
should_continue_payment,
)
.await
}
async fn preprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
authorize_preprocessing_steps(state, &self, true, connector).await
}
async fn postprocessing_steps<'a>(
self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Self> {
authorize_postprocessing_steps(state, &self, true, connector).await
}
async fn create_connector_customer<'a>(
&self,
state: &SessionState,
connector: &api::ConnectorData,
) -> RouterResult<Option<String>> {
customers::create_connector_customer(
state,
connector,
self,
types::ConnectorCustomerData::try_from(self)?,
)
.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)> {
match call_connector_action {
payments::CallConnectorAction::Trigger => {
connector
.connector
.validate_connector_against_payment_request(
self.request.capture_method,
self.payment_method,
self.request.payment_method_type,
)
.to_payment_failed_response()?;
// Check if the connector supports mandate payment
// if the payment_method_type does not support mandate for the given connector, downgrade the setup future usage to on session
if self.request.setup_future_usage
== Some(diesel_models::enums::FutureUsage::OffSession)
&& !self
.request
.payment_method_type
.and_then(|payment_method_type| {
state
.conf
.mandates
.supported_payment_methods
.0
.get(&enums::PaymentMethod::from(payment_method_type))
.and_then(|supported_pm_for_mandates| {
supported_pm_for_mandates.0.get(&payment_method_type).map(
|supported_connector_for_mandates| {
supported_connector_for_mandates
.connector_list
.contains(&connector.connector_name)
},
)
})
})
.unwrap_or(false)
{
// downgrade the setup future usage to on session
self.request.setup_future_usage =
Some(diesel_models::enums::FutureUsage::OnSession);
};
if crate::connector::utils::PaymentsAuthorizeRequestData::is_customer_initiated_mandate_payment(
&self.request,
) {
connector
.connector
.validate_mandate_payment(
self.request.payment_method_type,
self.request.payment_method_data.clone(),
)
.to_payment_failed_response()?;
};
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
metrics::EXECUTE_PRETASK_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("flow", format!("{:?}", api::Authorize)),
),
);
logger::debug!(completed_pre_tasks=?true);
if self.should_proceed_with_authorize() {
self.decide_authentication_type();
logger::debug!(auth_type=?self.auth_type);
Ok((
connector_integration
.build_request(self, &state.conf.connectors)
.to_payment_failed_response()?,
true,
))
} else {
Ok((None, false))
}
}
_ => Ok((None, true)),
}
}
async fn create_order_at_connector(
&mut self,
state: &SessionState,
connector: &api::ConnectorData,
should_continue_payment: bool,
) -> RouterResult<Option<types::CreateOrderResult>> {
if connector
.connector_name
.requires_order_creation_before_payment(self.payment_method)
&& should_continue_payment
{
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::CreateOrder,
types::CreateOrderRequestData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let request_data = types::CreateOrderRequestData::try_from(self.request.clone())?;
let response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let createorder_router_data =
helpers::router_data_type_conversion::<_, api::CreateOrder, _, _, _, _>(
self.clone(),
request_data,
response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&createorder_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let create_order_resp = match resp.response {
Ok(res) => {
if let types::PaymentsResponseData::PaymentsCreateOrderResponse { order_id } =
res
{
Ok(order_id)
} else {
Err(error_stack::report!(ApiErrorResponse::InternalServerError)
.attach_printable(format!(
"Unexpected response format from connector: {res:?}",
)))?
}
}
Err(error) => Err(error),
};
Ok(Some(types::CreateOrderResult {
create_order_result: create_order_resp,
}))
} else {
// If the connector does not require order creation, return None
Ok(None)
}
}
fn update_router_data_with_create_order_response(
&mut self,
create_order_result: types::CreateOrderResult,
) {
match create_order_result.create_order_result {
Ok(order_id) => {
self.request.order_id = Some(order_id.clone()); // ? why this is assigned here and ucs also wants this to populate data
self.response =
Ok(types::PaymentsResponseData::PaymentsCreateOrderResponse { order_id });
}
Err(err) => {
self.response = Err(err.clone());
}
}
}
async fn call_unified_connector_service<'a>(
&mut self,
state: &SessionState,
header_payload: &domain_payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
#[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
#[cfg(feature = "v2")]
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
merchant_context: &domain::MerchantContext,
) -> RouterResult<()> {
if self.request.mandate_id.is_some() {
Box::pin(call_unified_connector_service_repeat_payment(
self,
state,
header_payload,
lineage_ids,
merchant_connector_account,
merchant_context,
))
.await
} else {
Box::pin(call_unified_connector_service_authorize(
self,
state,
header_payload,
lineage_ids,
merchant_connector_account,
merchant_context,
))
.await
}
}
}
pub trait RouterDataAuthorize {
fn decide_authentication_type(&mut self);
/// to decide if we need to proceed with authorize or not, Eg: If any of the pretask returns `redirection_response` then we should not proceed with authorize call
fn should_proceed_with_authorize(&self) -> bool;
}
impl RouterDataAuthorize for types::PaymentsAuthorizeRouterData {
fn decide_authentication_type(&mut self) {
if let hyperswitch_domain_models::payment_method_data::PaymentMethodData::Wallet(
hyperswitch_domain_models::payment_method_data::WalletData::GooglePay(google_pay_data),
) = &self.request.payment_method_data
{
if let Some(assurance_details) = google_pay_data.info.assurance_details.as_ref() {
// Step up the transaction to 3DS when either assurance_details.card_holder_authenticated or assurance_details.account_verified is false
if !assurance_details.card_holder_authenticated
|| !assurance_details.account_verified
{
logger::info!("Googlepay transaction stepped up to 3DS");
self.auth_type = diesel_models::enums::AuthenticationType::ThreeDs;
}
}
}
if self.auth_type == diesel_models::enums::AuthenticationType::ThreeDs
&& !self.request.enrolled_for_3ds
{
self.auth_type = diesel_models::enums::AuthenticationType::NoThreeDs
}
}
/// to decide if we need to proceed with authorize or not, Eg: If any of the pretask returns `redirection_response` then we should not proceed with authorize call
fn should_proceed_with_authorize(&self) -> bool {
match &self.response {
Ok(types::PaymentsResponseData::TransactionResponse {
redirection_data, ..
}) => !redirection_data.is_some(),
_ => true,
}
}
}
impl mandate::MandateBehaviour for types::PaymentsAuthorizeData {
fn get_amount(&self) -> i64 {
self.amount
}
fn get_mandate_id(&self) -> Option<&api_models::payments::MandateIds> {
self.mandate_id.as_ref()
}
fn get_payment_method_data(&self) -> domain::payments::PaymentMethodData {
self.payment_method_data.clone()
}
fn get_setup_future_usage(&self) -> Option<diesel_models::enums::FutureUsage> {
self.setup_future_usage
}
fn get_setup_mandate_details(
&self,
) -> Option<&hyperswitch_domain_models::mandates::MandateData> {
self.setup_mandate_details.as_ref()
}
fn set_mandate_id(&mut self, new_mandate_id: Option<api_models::payments::MandateIds>) {
self.mandate_id = new_mandate_id;
}
fn get_customer_acceptance(&self) -> Option<common_payments_types::CustomerAcceptance> {
self.customer_acceptance.clone()
}
}
pub async fn authorize_preprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>> {
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PreProcessing,
types::PaymentsPreProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let preprocessing_request_data =
types::PaymentsPreProcessingData::try_from(router_data.request.to_owned())?;
let preprocessing_response_data: Result<types::PaymentsResponseData, types::ErrorResponse> =
Err(types::ErrorResponse::default());
let preprocessing_router_data =
helpers::router_data_type_conversion::<_, api::PreProcessing, _, _, _, _>(
router_data.clone(),
preprocessing_request_data,
preprocessing_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&preprocessing_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
metrics::PREPROCESSING_STEPS_COUNT.add(
1,
router_env::metric_attributes!(
("connector", connector.connector_name.to_string()),
("payment_method", router_data.payment_method.to_string()),
(
"payment_method_type",
router_data
.request
.payment_method_type
.map(|inner| inner.to_string())
.unwrap_or("null".to_string()),
),
),
);
let mut authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
resp.clone(),
router_data.request.to_owned(),
resp.response.clone(),
);
if connector.connector_name == api_models::enums::Connector::Airwallex {
authorize_router_data.reference_id = resp.reference_id;
} else if connector.connector_name == api_models::enums::Connector::Nuvei {
let (enrolled_for_3ds, related_transaction_id) = match &authorize_router_data.response {
Ok(types::PaymentsResponseData::ThreeDSEnrollmentResponse {
enrolled_v2,
related_transaction_id,
}) => (*enrolled_v2, related_transaction_id.clone()),
_ => (false, None),
};
authorize_router_data.request.enrolled_for_3ds = enrolled_for_3ds;
authorize_router_data.request.related_transaction_id = related_transaction_id;
} else if connector.connector_name == api_models::enums::Connector::Shift4 {
if resp.request.enrolled_for_3ds {
authorize_router_data.response = resp.response;
authorize_router_data.status = resp.status;
} else {
authorize_router_data.request.enrolled_for_3ds = false;
}
}
Ok(authorize_router_data)
} else {
Ok(router_data.clone())
}
}
pub async fn authorize_postprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>> {
if confirm {
let connector_integration: services::BoxedPaymentConnectorIntegrationInterface<
api::PostProcessing,
types::PaymentsPostProcessingData,
types::PaymentsResponseData,
> = connector.connector.get_connector_integration();
let postprocessing_request_data =
types::PaymentsPostProcessingData::try_from(router_data.to_owned())?;
let postprocessing_response_data: Result<
types::PaymentsResponseData,
types::ErrorResponse,
> = Err(types::ErrorResponse::default());
let postprocessing_router_data =
helpers::router_data_type_conversion::<_, api::PostProcessing, _, _, _, _>(
router_data.clone(),
postprocessing_request_data,
postprocessing_response_data,
);
let resp = services::execute_connector_processing_step(
state,
connector_integration,
&postprocessing_router_data,
payments::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_payment_failed_response()?;
let authorize_router_data = helpers::router_data_type_conversion::<_, F, _, _, _, _>(
resp.clone(),
router_data.request.to_owned(),
resp.response,
);
Ok(authorize_router_data)
} else {
Ok(router_data.clone())
}
}
impl<F>
ForeignTryFrom<types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>>
for types::PaymentsCaptureData
{
type Error = error_stack::Report<ApiErrorResponse>;
fn foreign_try_from(
item: types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let response = item
.response
.map_err(|err| ApiErrorResponse::ExternalConnectorError {
code: err.code,
message: err.message,
connector: item.connector.clone(),
status_code: err.status_code,
reason: err.reason,
})?;
Ok(Self {
amount_to_capture: item.request.amount,
currency: item.request.currency,
connector_transaction_id: types::PaymentsResponseData::get_connector_transaction_id(
&response,
)?,
payment_amount: item.request.amount,
multiple_capture_data: None,
connector_meta: types::PaymentsResponseData::get_connector_metadata(&response)
.map(|secret| secret.expose()),
browser_info: None,
metadata: None,
capture_method: item.request.capture_method,
minor_payment_amount: item.request.minor_amount,
minor_amount_to_capture: item.request.minor_amount,
integrity_object: None,
split_payments: item.request.split_payments,
webhook_url: item.request.webhook_url,
})
}
}
async fn process_capture_flow(
mut router_data: types::RouterData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
authorize_response: types::PaymentsResponseData,
state: &SessionState,
connector: &api::ConnectorData,
call_connector_action: payments::CallConnectorAction,
business_profile: &domain::Profile,
header_payload: domain_payments::HeaderPayload,
) -> RouterResult<
types::RouterData<api::Authorize, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
> {
// Convert RouterData into Capture RouterData
let capture_router_data = helpers::router_data_type_conversion(
router_data.clone(),
types::PaymentsCaptureData::foreign_try_from(router_data.clone())?,
Err(types::ErrorResponse::default()),
);
// Call capture request
let post_capture_router_data = super::call_capture_request(
capture_router_data,
state,
connector,
call_connector_action,
business_profile,
header_payload,
)
.await;
// Process capture response
let (updated_status, updated_response) =
super::handle_post_capture_response(authorize_response, post_capture_router_data)?;
router_data.status = updated_status;
router_data.response = Ok(updated_response);
Ok(router_data)
}
async fn call_unified_connector_service_authorize(
router_data: &mut types::RouterData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
state: &SessionState,
header_payload: &domain_payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
#[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
#[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
merchant_context: &domain::MerchantContext,
) -> RouterResult<()> {
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_authorize_request =
payments_grpc::PaymentServiceAuthorizeRequest::foreign_try_from(&*router_data)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct Payment Authorize Request")?;
let connector_auth_metadata =
build_unified_connector_service_auth_metadata(merchant_connector_account, merchant_context)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct request metadata")?;
let merchant_order_reference_id = header_payload
.x_reference_id
.clone()
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let headers_builder = state
.get_grpc_headers_ucs()
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_order_reference_id)
.lineage_ids(lineage_ids);
let updated_router_data = Box::pin(ucs_logging_wrapper(
router_data.clone(),
state,
payment_authorize_request,
headers_builder,
|mut router_data, payment_authorize_request, grpc_headers| async move {
let response = client
.payment_authorize(
payment_authorize_request,
connector_auth_metadata,
grpc_headers,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to authorize payment")?;
let payment_authorize_response = response.into_inner();
let (router_data_response, status_code) =
handle_unified_connector_service_response_for_payment_authorize(
payment_authorize_response.clone(),
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.raw_connector_response = payment_authorize_response
.raw_connector_response
.clone()
.map(Secret::new);
router_data.connector_http_status_code = Some(status_code);
Ok((router_data, payment_authorize_response))
},
))
.await?;
// Copy back the updated data
*router_data = updated_router_data;
Ok(())
}
async fn call_unified_connector_service_repeat_payment(
router_data: &mut types::RouterData<
api::Authorize,
types::PaymentsAuthorizeData,
types::PaymentsResponseData,
>,
state: &SessionState,
header_payload: &domain_payments::HeaderPayload,
lineage_ids: grpc_client::LineageIds,
#[cfg(feature = "v1")] merchant_connector_account: helpers::MerchantConnectorAccountType,
#[cfg(feature = "v2")] merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
merchant_context: &domain::MerchantContext,
) -> RouterResult<()> {
let client = state
.grpc_client
.unified_connector_service_client
.clone()
.ok_or(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch Unified Connector Service client")?;
let payment_repeat_request =
payments_grpc::PaymentServiceRepeatEverythingRequest::foreign_try_from(&*router_data)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct Payment Repeat Request")?;
let connector_auth_metadata =
build_unified_connector_service_auth_metadata(merchant_connector_account, merchant_context)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to construct request metadata")?;
let merchant_order_reference_id = header_payload
.x_reference_id
.clone()
.map(|id| id_type::PaymentReferenceId::from_str(id.as_str()))
.transpose()
.inspect_err(|err| logger::warn!(error=?err, "Invalid Merchant ReferenceId found"))
.ok()
.flatten()
.map(ucs_types::UcsReferenceId::Payment);
let headers_builder = state
.get_grpc_headers_ucs()
.external_vault_proxy_metadata(None)
.merchant_reference_id(merchant_order_reference_id)
.lineage_ids(lineage_ids);
let updated_router_data = Box::pin(ucs_logging_wrapper(
router_data.clone(),
state,
payment_repeat_request,
headers_builder,
|mut router_data, payment_repeat_request, grpc_headers| async move {
let response = client
.payment_repeat(
payment_repeat_request,
connector_auth_metadata.clone(),
grpc_headers,
)
.await
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to repeat payment")?;
let payment_repeat_response = response.into_inner();
let (router_data_response, status_code) =
handle_unified_connector_service_response_for_payment_repeat(
payment_repeat_response.clone(),
)
.change_context(ApiErrorResponse::InternalServerError)
.attach_printable("Failed to deserialize UCS response")?;
let router_data_response = router_data_response.map(|(response, status)| {
router_data.status = status;
response
});
router_data.response = router_data_response;
router_data.raw_connector_response = payment_repeat_response
.raw_connector_response
.clone()
.map(Secret::new);
router_data.connector_http_status_code = Some(status_code);
Ok((router_data, payment_repeat_response))
},
))
.await?;
// Copy back the updated data
*router_data = updated_router_data;
Ok(())
}
|
crates/router/src/core/payments/flows/authorize_flow.rs
|
router
|
full_file
| null | null | null | 7,116
| null | null | null | null | null | null | null |
// Struct: PayoutListFilters
// File: crates/api_models/src/payouts.rs
// Module: api_models
// Implementations: 0
pub struct PayoutListFilters
|
crates/api_models/src/payouts.rs
|
api_models
|
struct_definition
|
PayoutListFilters
| 0
|
[] | 39
| null | null | null | null | null | null | null |
// Function: get_connector_customer_id
// File: crates/hyperswitch_domain_models/src/customer.rs
// Module: hyperswitch_domain_models
pub fn get_connector_customer_id(
&self,
merchant_connector_account: &MerchantConnectorAccountTypeDetails,
) -> Option<&str>
|
crates/hyperswitch_domain_models/src/customer.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 60
|
get_connector_customer_id
| null | null | null | null | null | null |
// Implementation: impl Hash for for ActivePaymentsMetricsBucketIdentifier
// File: crates/api_models/src/analytics/active_payments.rs
// Module: api_models
// Methods: 1 total (0 public)
impl Hash for for ActivePaymentsMetricsBucketIdentifier
|
crates/api_models/src/analytics/active_payments.rs
|
api_models
|
impl_block
| null | null | null | 52
| null |
ActivePaymentsMetricsBucketIdentifier
|
Hash for
| 1
| 0
| null | null |
// Struct: GocardlessMandateRequest
// File: crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct GocardlessMandateRequest
|
crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
GocardlessMandateRequest
| 0
|
[] | 56
| null | null | null | null | null | null | null |
// Struct: FacilitapayAuthType
// File: crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct FacilitapayAuthType
|
crates/hyperswitch_connectors/src/connectors/facilitapay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
FacilitapayAuthType
| 0
|
[] | 56
| null | null | null | null | null | null | null |
// Struct: PaymentDetails
// File: crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaymentDetails
|
crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymentDetails
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Implementation: impl api::Payment for for UnifiedAuthenticationService
// File: crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Payment for for UnifiedAuthenticationService
|
crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
UnifiedAuthenticationService
|
api::Payment for
| 0
| 0
| null | null |
// Struct: MetricsBucketResponse
// File: crates/api_models/src/analytics/active_payments.rs
// Module: api_models
// Implementations: 0
pub struct MetricsBucketResponse
|
crates/api_models/src/analytics/active_payments.rs
|
api_models
|
struct_definition
|
MetricsBucketResponse
| 0
|
[] | 39
| null | null | null | null | null | null | null |
// Struct: BokuRsyncRequest
// File: crates/hyperswitch_connectors/src/connectors/boku/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BokuRsyncRequest
|
crates/hyperswitch_connectors/src/connectors/boku/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
BokuRsyncRequest
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// File: crates/router/src/core/payments/vault_session.rs
// Module: router
// Public functions: 3
use std::{fmt::Debug, str::FromStr};
pub use common_enums::enums::CallConnectorAction;
use common_utils::id_type;
use error_stack::{report, ResultExt};
pub use hyperswitch_domain_models::{
mandates::MandateData,
payment_address::PaymentAddress,
payments::{HeaderPayload, PaymentIntentData},
router_data::{PaymentMethodToken, RouterData},
router_data_v2::{flow_common_types::VaultConnectorFlowData, RouterDataV2},
router_flow_types::ExternalVaultCreateFlow,
router_request_types::CustomerDetails,
types::{VaultRouterData, VaultRouterDataV2},
};
use hyperswitch_interfaces::{
api::Connector as ConnectorTrait,
connector_integration_v2::{ConnectorIntegrationV2, ConnectorV2},
};
use masking::ExposeInterface;
use router_env::{env::Env, instrument, tracing};
use crate::{
core::{
errors::{self, utils::StorageErrorExt, RouterResult},
payments::{
self as payments_core, call_multiple_connectors_service, customers,
flows::{ConstructFlowSpecificData, Feature},
helpers, helpers as payment_helpers, operations,
operations::{BoxedOperation, Operation},
transformers, OperationSessionGetters, OperationSessionSetters,
},
utils as core_utils,
},
db::errors::ConnectorErrorExt,
errors::RouterResponse,
routes::{app::ReqState, SessionState},
services::{self, connector_integration_interface::RouterDataConversion},
types::{
self as router_types,
api::{self, enums as api_enums, ConnectorCommon},
domain, storage,
},
utils::{OptionExt, ValueExt},
};
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn populate_vault_session_details<F, RouterDReq, ApiRequest, D>(
state: &SessionState,
req_state: ReqState,
customer: &Option<domain::Customer>,
merchant_context: &domain::MerchantContext,
operation: &BoxedOperation<'_, F, ApiRequest, D>,
profile: &domain::Profile,
payment_data: &mut D,
header_payload: HeaderPayload,
) -> RouterResult<()>
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 is_external_vault_sdk_enabled = profile.is_vault_sdk_enabled();
if is_external_vault_sdk_enabled {
let external_vault_source = profile
.external_vault_connector_details
.as_ref()
.map(|details| &details.vault_connector_id);
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
external_vault_source,
)
.await?,
));
let updated_customer = call_create_connector_customer_if_required(
state,
customer,
merchant_context,
&merchant_connector_account,
payment_data,
)
.await?;
if let Some((customer, updated_customer)) = customer.clone().zip(updated_customer) {
let db = &*state.store;
let customer_id = customer.get_id().clone();
let customer_merchant_id = customer.merchant_id.clone();
let _updated_customer = db
.update_customer_by_global_id(
&state.into(),
&customer_id,
customer,
updated_customer,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update customer during Vault session")?;
};
let vault_session_details = generate_vault_session_details(
state,
merchant_context,
&merchant_connector_account,
payment_data.get_connector_customer_id(),
)
.await?;
payment_data.set_vault_session_details(vault_session_details);
}
Ok(())
}
#[cfg(feature = "v2")]
pub async fn call_create_connector_customer_if_required<F, Req, D>(
state: &SessionState,
customer: &Option<domain::Customer>,
merchant_context: &domain::MerchantContext,
merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,
payment_data: &mut D,
) -> RouterResult<Option<storage::CustomerUpdate>>
where
F: Send + Clone + Sync,
Req: Send + Sync,
// To create connector flow specific interface data
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
D: ConstructFlowSpecificData<F, Req, router_types::PaymentsResponseData>,
RouterData<F, Req, router_types::PaymentsResponseData>: Feature<F, Req> + Send,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, Req, router_types::PaymentsResponseData>,
{
let db_merchant_connector_account =
merchant_connector_account_type.get_inner_db_merchant_connector_account();
match db_merchant_connector_account {
Some(merchant_connector_account) => {
let connector_name = merchant_connector_account.get_connector_name_as_string();
let merchant_connector_id = merchant_connector_account.get_id();
let connector = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name,
api::GetToken::Connector,
Some(merchant_connector_id.clone()),
)?;
let (should_call_connector, existing_connector_customer_id) =
customers::should_call_connector_create_customer(
&connector,
customer,
payment_data.get_payment_attempt(),
merchant_connector_account_type,
);
if should_call_connector {
// Create customer at connector and update the customer table to store this data
let router_data = payment_data
.construct_router_data(
state,
connector.connector.id(),
merchant_context,
customer,
merchant_connector_account_type,
None,
None,
)
.await?;
let connector_customer_id = router_data
.create_connector_customer(state, &connector)
.await?;
let customer_update = customers::update_connector_customer_in_customers(
merchant_connector_account_type,
customer.as_ref(),
connector_customer_id.clone(),
)
.await;
payment_data.set_connector_customer_id(connector_customer_id);
Ok(customer_update)
} else {
// Customer already created in previous calls use the same value, no need to update
payment_data.set_connector_customer_id(
existing_connector_customer_id.map(ToOwned::to_owned),
);
Ok(None)
}
}
None => {
router_env::logger::error!(
"Merchant connector account is missing, cannot create customer for vault session"
);
Err(errors::ApiErrorResponse::InternalServerError.into())
}
}
}
#[cfg(feature = "v2")]
pub async fn generate_vault_session_details(
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,
connector_customer_id: Option<String>,
) -> RouterResult<Option<api::VaultSessionDetails>> {
let connector_name = merchant_connector_account_type
.get_connector_name()
.map(|name| name.to_string())
.ok_or(errors::ApiErrorResponse::InternalServerError)?; // should not panic since we should always have a connector name
let connector = api_enums::VaultConnectors::from_str(&connector_name)
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let connector_auth_type: router_types::ConnectorAuthType = merchant_connector_account_type
.get_connector_account_details()
.map_err(|err| {
err.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to parse connector auth type")
})?;
match (connector, connector_auth_type) {
// create session for vgs vault
(
api_enums::VaultConnectors::Vgs,
router_types::ConnectorAuthType::SignatureKey { api_secret, .. },
) => {
let sdk_env = match state.conf.env {
Env::Sandbox | Env::Development => "sandbox",
Env::Production => "live",
}
.to_string();
Ok(Some(api::VaultSessionDetails::Vgs(
api::VgsSessionDetails {
external_vault_id: api_secret,
sdk_env,
},
)))
}
// create session for hyperswitch vault
(
api_enums::VaultConnectors::HyperswitchVault,
router_types::ConnectorAuthType::SignatureKey {
key1, api_secret, ..
},
) => {
generate_hyperswitch_vault_session_details(
state,
merchant_context,
merchant_connector_account_type,
connector_customer_id,
connector_name,
key1,
api_secret,
)
.await
}
_ => {
router_env::logger::warn!(
"External vault session creation is not supported for connector: {}",
connector_name
);
Ok(None)
}
}
}
async fn generate_hyperswitch_vault_session_details(
state: &SessionState,
merchant_context: &domain::MerchantContext,
merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,
connector_customer_id: Option<String>,
connector_name: String,
vault_publishable_key: masking::Secret<String>,
vault_profile_id: masking::Secret<String>,
) -> RouterResult<Option<api::VaultSessionDetails>> {
let connector_response = call_external_vault_create(
state,
merchant_context,
connector_name,
merchant_connector_account_type,
connector_customer_id,
)
.await?;
match connector_response.response {
Ok(router_types::VaultResponseData::ExternalVaultCreateResponse {
session_id,
client_secret,
}) => Ok(Some(api::VaultSessionDetails::HyperswitchVault(
api::HyperswitchVaultSessionDetails {
payment_method_session_id: session_id,
client_secret,
publishable_key: vault_publishable_key,
profile_id: vault_profile_id,
},
))),
Ok(_) => {
router_env::logger::warn!("Unexpected response from external vault create API");
Err(errors::ApiErrorResponse::InternalServerError.into())
}
Err(err) => {
router_env::logger::error!(error_response_from_external_vault_create=?err);
Err(errors::ApiErrorResponse::InternalServerError.into())
}
}
}
#[cfg(feature = "v2")]
async fn call_external_vault_create(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector_name: String,
merchant_connector_account_type: &domain::MerchantConnectorAccountTypeDetails,
connector_customer_id: Option<String>,
) -> RouterResult<VaultRouterData<ExternalVaultCreateFlow>>
where
dyn ConnectorTrait + Sync: services::api::ConnectorIntegration<
ExternalVaultCreateFlow,
router_types::VaultRequestData,
router_types::VaultResponseData,
>,
dyn ConnectorV2 + Sync: ConnectorIntegrationV2<
ExternalVaultCreateFlow,
VaultConnectorFlowData,
router_types::VaultRequestData,
router_types::VaultResponseData,
>,
{
let connector_data: api::ConnectorData = api::ConnectorData::get_connector_by_name(
&state.conf.connectors,
&connector_name,
api::GetToken::Connector,
merchant_connector_account_type.get_mca_id(),
)?;
let merchant_connector_account = match &merchant_connector_account_type {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(mca) => {
Ok(mca.as_ref())
}
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("MerchantConnectorDetails not supported for vault operations"))
}
}?;
let mut router_data = core_utils::construct_vault_router_data(
state,
merchant_context.get_merchant_account().get_id(),
merchant_connector_account,
None,
None,
connector_customer_id,
)
.await?;
let mut old_router_data = VaultConnectorFlowData::to_old_router_data(router_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Cannot construct router data for making the external vault create api call",
)?;
let connector_integration: services::BoxedVaultConnectorIntegrationInterface<
ExternalVaultCreateFlow,
router_types::VaultRequestData,
router_types::VaultResponseData,
> = connector_data.connector.get_connector_integration();
services::execute_connector_processing_step(
state,
connector_integration,
&old_router_data,
CallConnectorAction::Trigger,
None,
None,
)
.await
.to_vault_failed_response()
}
|
crates/router/src/core/payments/vault_session.rs
|
router
|
full_file
| null | null | null | 2,862
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSession for for Gpayments
// File: crates/hyperswitch_connectors/src/connectors/gpayments.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSession for for Gpayments
|
crates/hyperswitch_connectors/src/connectors/gpayments.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Gpayments
|
api::PaymentSession for
| 0
| 0
| null | null |
// Function: perform_payments_sync
// File: crates/router/src/core/revenue_recovery.rs
// Module: router
pub fn perform_payments_sync(
state: &SessionState,
process: &storage::ProcessTracker,
profile: &domain::Profile,
merchant_context: domain::MerchantContext,
tracking_data: &pcr::RevenueRecoveryWorkflowTrackingData,
revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
payment_intent: &PaymentIntent,
) -> Result<(), errors::ProcessTrackerError>
|
crates/router/src/core/revenue_recovery.rs
|
router
|
function_signature
| null | null | null | 112
|
perform_payments_sync
| null | null | null | null | null | null |
// Struct: ThreeDsInvokeExempt
// File: crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ThreeDsInvokeExempt
|
crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ThreeDsInvokeExempt
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Implementation: impl Currency
// File: crates/common_enums/src/enums.rs
// Module: common_enums
// Methods: 9 total (9 public)
impl Currency
|
crates/common_enums/src/enums.rs
|
common_enums
|
impl_block
| null | null | null | 37
| null |
Currency
| null | 9
| 9
| null | null |
// File: crates/router/src/db/unified_translations.rs
// Module: router
use diesel_models::unified_translations as storage;
use error_stack::report;
use super::MockDb;
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
};
#[async_trait::async_trait]
pub trait UnifiedTranslationsInterface {
async fn add_unfied_translation(
&self,
translation: storage::UnifiedTranslationsNew,
) -> CustomResult<storage::UnifiedTranslations, errors::StorageError>;
async fn update_translation(
&self,
unified_code: String,
unified_message: String,
locale: String,
data: storage::UnifiedTranslationsUpdate,
) -> CustomResult<storage::UnifiedTranslations, errors::StorageError>;
async fn find_translation(
&self,
unified_code: String,
unified_message: String,
locale: String,
) -> CustomResult<String, errors::StorageError>;
async fn delete_translation(
&self,
unified_code: String,
unified_message: String,
locale: String,
) -> CustomResult<bool, errors::StorageError>;
}
#[async_trait::async_trait]
impl UnifiedTranslationsInterface for Store {
async fn add_unfied_translation(
&self,
translation: storage::UnifiedTranslationsNew,
) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
translation
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn update_translation(
&self,
unified_code: String,
unified_message: String,
locale: String,
data: storage::UnifiedTranslationsUpdate,
) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::UnifiedTranslations::update_by_unified_code_unified_message_locale(
&conn,
unified_code,
unified_message,
locale,
data,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn find_translation(
&self,
unified_code: String,
unified_message: String,
locale: String,
) -> CustomResult<String, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
let translations =
storage::UnifiedTranslations::find_by_unified_code_unified_message_locale(
&conn,
unified_code,
unified_message,
locale,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))?;
Ok(translations.translation)
}
async fn delete_translation(
&self,
unified_code: String,
unified_message: String,
locale: String,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::UnifiedTranslations::delete_by_unified_code_unified_message_locale(
&conn,
unified_code,
unified_message,
locale,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl UnifiedTranslationsInterface for MockDb {
async fn add_unfied_translation(
&self,
_translation: storage::UnifiedTranslationsNew,
) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn find_translation(
&self,
_unified_code: String,
_unified_message: String,
_locale: String,
) -> CustomResult<String, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn update_translation(
&self,
_unified_code: String,
_unified_message: String,
_locale: String,
_data: storage::UnifiedTranslationsUpdate,
) -> CustomResult<storage::UnifiedTranslations, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn delete_translation(
&self,
_unified_code: String,
_unified_message: String,
_locale: String,
) -> CustomResult<bool, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
}
|
crates/router/src/db/unified_translations.rs
|
router
|
full_file
| null | null | null | 955
| null | null | null | null | null | null | null |
// Struct: PaysafePaymentHandleResponse
// File: crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaysafePaymentHandleResponse
|
crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaysafePaymentHandleResponse
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Implementation: impl RedisKey
// File: crates/redis_interface/src/types.rs
// Module: redis_interface
// Methods: 2 total (2 public)
impl RedisKey
|
crates/redis_interface/src/types.rs
|
redis_interface
|
impl_block
| null | null | null | 37
| null |
RedisKey
| null | 2
| 2
| null | null |
// Implementation: impl api::PayoutEligibility for for Nomupay
// File: crates/hyperswitch_connectors/src/connectors/nomupay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PayoutEligibility for for Nomupay
|
crates/hyperswitch_connectors/src/connectors/nomupay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 67
| null |
Nomupay
|
api::PayoutEligibility for
| 0
| 0
| null | null |
// Implementation: impl Relay
// File: crates/hyperswitch_domain_models/src/relay.rs
// Module: hyperswitch_domain_models
// Methods: 1 total (1 public)
impl Relay
|
crates/hyperswitch_domain_models/src/relay.rs
|
hyperswitch_domain_models
|
impl_block
| null | null | null | 41
| null |
Relay
| null | 1
| 1
| null | null |
// File: crates/pm_auth/src/lib.rs
// Module: pm_auth
pub mod connector;
pub mod consts;
pub mod core;
pub mod types;
|
crates/pm_auth/src/lib.rs
|
pm_auth
|
full_file
| null | null | null | 32
| null | null | null | null | null | null | null |
// Function: update_user_role
// File: crates/router/src/core/user_role.rs
// Module: router
pub fn update_user_role(
state: SessionState,
user_from_token: auth::UserFromToken,
req: user_role_api::UpdateUserRoleRequest,
_req_state: ReqState,
) -> UserResponse<()>
|
crates/router/src/core/user_role.rs
|
router
|
function_signature
| null | null | null | 70
|
update_user_role
| null | null | null | null | null | null |
// Function: list_metadata_by_merchant_id_transaction_type
// File: crates/diesel_models/src/query/routing_algorithm.rs
// Module: diesel_models
pub fn list_metadata_by_merchant_id_transaction_type(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
transaction_type: &enums::TransactionType,
limit: i64,
offset: i64,
) -> StorageResult<Vec<RoutingProfileMetadata>>
|
crates/diesel_models/src/query/routing_algorithm.rs
|
diesel_models
|
function_signature
| null | null | null | 101
|
list_metadata_by_merchant_id_transaction_type
| null | null | null | null | null | null |
// Function: insert_totp_in_redis
// File: crates/router/src/utils/user/two_factor_auth.rs
// Module: router
pub fn insert_totp_in_redis(state: &SessionState, user_id: &str) -> UserResult<()>
|
crates/router/src/utils/user/two_factor_auth.rs
|
router
|
function_signature
| null | null | null | 51
|
insert_totp_in_redis
| null | null | null | null | null | null |
// Struct: SquareWebhookBody
// File: crates/hyperswitch_connectors/src/connectors/square/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SquareWebhookBody
|
crates/hyperswitch_connectors/src/connectors/square/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
SquareWebhookBody
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Function: get_webhook_object_from_body
// File: crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
// Module: hyperswitch_connectors
pub fn get_webhook_object_from_body(
body: &[u8],
) -> CustomResult<SantanderWebhookBody, common_utils::errors::ParsingError>
|
crates/hyperswitch_connectors/src/connectors/santander/transformers.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 74
|
get_webhook_object_from_body
| null | null | null | null | null | null |
// Function: get_network_config
// File: crates/router/src/types/storage/revenue_recovery.rs
// Module: router
pub fn get_network_config(&self, network: Option<CardNetwork>) -> &NetworkRetryConfig
|
crates/router/src/types/storage/revenue_recovery.rs
|
router
|
function_signature
| null | null | null | 44
|
get_network_config
| null | null | null | null | null | null |
// Struct: PaymentCaptureResponse
// File: crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaymentCaptureResponse
|
crates/hyperswitch_connectors/src/connectors/fiuu/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymentCaptureResponse
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// Function: api_error_derive_inner
// File: crates/router_derive/src/macros/api_error.rs
// Module: router_derive
pub fn api_error_derive_inner(ast: &DeriveInput) -> syn::Result<TokenStream>
|
crates/router_derive/src/macros/api_error.rs
|
router_derive
|
function_signature
| null | null | null | 51
|
api_error_derive_inner
| null | null | null | null | null | null |
// Struct: CustombillingErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/custombilling/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CustombillingErrorResponse
|
crates/hyperswitch_connectors/src/connectors/custombilling/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CustombillingErrorResponse
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Function: generic_find_by_id_optional
// File: crates/diesel_models/src/query/generics.rs
// Module: diesel_models
pub fn generic_find_by_id_optional<T, Pk, R>(
conn: &PgPooledConn,
id: Pk,
) -> StorageResult<Option<R>>
where
T: FindDsl<Pk> + HasTable<Table = T> + LimitDsl + Table + 'static,
<T as HasTable>::Table: FindDsl<Pk>,
Find<T, Pk>: LimitDsl + QueryFragment<Pg> + RunQueryDsl<PgConnection> + Send + 'static,
Limit<Find<T, Pk>>: LoadQuery<'static, PgConnection, R>,
Pk: Clone + Debug,
R: Send + 'static,
|
crates/diesel_models/src/query/generics.rs
|
diesel_models
|
function_signature
| null | null | null | 176
|
generic_find_by_id_optional
| null | null | null | null | null | null |
// Function: server
// File: crates/router/src/compatibility/stripe/app.rs
// Module: router
pub fn server(config: routes::AppState) -> Scope
|
crates/router/src/compatibility/stripe/app.rs
|
router
|
function_signature
| null | null | null | 35
|
server
| null | null | null | null | null | null |
// Struct: Charges
// File: crates/router/src/compatibility/stripe/payment_intents/types.rs
// Module: router
// Implementations: 1
pub struct Charges
|
crates/router/src/compatibility/stripe/payment_intents/types.rs
|
router
|
struct_definition
|
Charges
| 1
|
[] | 37
| null | null | null | null | null | null | null |
// Implementation: impl Event for for AuditEvent
// File: crates/router/src/events/audit_events.rs
// Module: router
// Methods: 3 total (0 public)
impl Event for for AuditEvent
|
crates/router/src/events/audit_events.rs
|
router
|
impl_block
| null | null | null | 43
| null |
AuditEvent
|
Event for
| 3
| 0
| null | null |
// Function: get_connector_list
// File: crates/api_models/src/routing.rs
// Module: api_models
pub fn get_connector_list(&self) -> Vec<RoutableConnectorChoice>
|
crates/api_models/src/routing.rs
|
api_models
|
function_signature
| null | null | null | 40
|
get_connector_list
| null | null | null | null | null | null |
// Implementation: impl Responder
// File: crates/router/src/routes/payments.rs
// Module: router
// Methods: 0 total (0 public)
impl Responder
|
crates/router/src/routes/payments.rs
|
router
|
impl_block
| null | null | null | 36
| null |
Responder
| null | 0
| 0
| null | null |
// Function: insert
// File: crates/diesel_models/src/query/hyperswitch_ai_interaction.rs
// Module: diesel_models
pub fn insert(self, conn: &PgPooledConn) -> StorageResult<HyperswitchAiInteraction>
|
crates/diesel_models/src/query/hyperswitch_ai_interaction.rs
|
diesel_models
|
function_signature
| null | null | null | 51
|
insert
| null | null | null | null | null | null |
// File: crates/router/src/types/storage/file.rs
// Module: router
pub use diesel_models::file::{
FileMetadata, FileMetadataNew, FileMetadataUpdate, FileMetadataUpdateInternal,
};
|
crates/router/src/types/storage/file.rs
|
router
|
full_file
| null | null | null | 41
| null | null | null | null | null | null | null |
// Struct: SquarePaymentsRequestExternalDetails
// File: crates/hyperswitch_connectors/src/connectors/square/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct SquarePaymentsRequestExternalDetails
|
crates/hyperswitch_connectors/src/connectors/square/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
SquarePaymentsRequestExternalDetails
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Struct: ShippingAddress
// File: crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 1
// Traits: AddressConstructor
pub struct ShippingAddress
|
crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ShippingAddress
| 1
|
[
"AddressConstructor"
] | 53
| null | null | null | null | null | null | null |
// Struct: ChargebackUpdateRequest
// File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ChargebackUpdateRequest
|
crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ChargebackUpdateRequest
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// File: crates/router/src/workflows/revenue_recovery.rs
// Module: router
// Public functions: 8
// Public structs: 2
#[cfg(feature = "v2")]
use std::collections::HashMap;
#[cfg(feature = "v2")]
use api_models::{enums::RevenueRecoveryAlgorithmType, payments::PaymentsGetIntentRequest};
use common_utils::errors::CustomResult;
#[cfg(feature = "v2")]
use common_utils::{
ext_traits::AsyncExt,
ext_traits::{StringExt, ValueExt},
id_type,
};
#[cfg(feature = "v2")]
use diesel_models::types::BillingConnectorPaymentMethodDetails;
#[cfg(feature = "v2")]
use error_stack::{Report, ResultExt};
#[cfg(all(feature = "revenue_recovery", feature = "v2"))]
use external_services::{
date_time, grpc_client::revenue_recovery::recovery_decider_client as external_grpc_client,
};
#[cfg(feature = "v2")]
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
payments::{payment_attempt, PaymentConfirmData, PaymentIntent, PaymentIntentData},
router_flow_types,
router_flow_types::Authorize,
};
#[cfg(feature = "v2")]
use masking::{ExposeInterface, PeekInterface, Secret};
#[cfg(feature = "v2")]
use rand::Rng;
use router_env::{
logger,
tracing::{self, instrument},
};
use scheduler::{
consumer::{self, workflows::ProcessTrackerWorkflow},
errors,
};
#[cfg(feature = "v2")]
use scheduler::{types::process_data, utils as scheduler_utils};
#[cfg(feature = "v2")]
use storage_impl::errors as storage_errors;
#[cfg(feature = "v2")]
use time::Date;
#[cfg(feature = "v2")]
use crate::core::payments::operations;
#[cfg(feature = "v2")]
use crate::routes::app::ReqState;
#[cfg(feature = "v2")]
use crate::services;
#[cfg(feature = "v2")]
use crate::types::storage::{
revenue_recovery::RetryLimitsConfig,
revenue_recovery_redis_operation::{
PaymentProcessorTokenStatus, PaymentProcessorTokenWithRetryInfo, RedisTokenManager,
},
};
#[cfg(feature = "v2")]
use crate::workflows::revenue_recovery::pcr::api;
#[cfg(feature = "v2")]
use crate::{
core::{
payments,
revenue_recovery::{self as pcr},
},
db::StorageInterface,
errors::StorageError,
types::{
api::{self as api_types},
domain,
storage::{
revenue_recovery as pcr_storage_types,
revenue_recovery_redis_operation::PaymentProcessorTokenDetails,
},
},
};
use crate::{routes::SessionState, types::storage};
pub struct ExecutePcrWorkflow;
#[cfg(feature = "v2")]
pub const REVENUE_RECOVERY: &str = "revenue_recovery";
#[async_trait::async_trait]
impl ProcessTrackerWorkflow<SessionState> for ExecutePcrWorkflow {
#[cfg(feature = "v1")]
async fn execute_workflow<'a>(
&'a self,
_state: &'a SessionState,
_process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
Ok(())
}
#[cfg(feature = "v2")]
async fn execute_workflow<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
) -> Result<(), errors::ProcessTrackerError> {
let tracking_data = process
.tracking_data
.clone()
.parse_value::<pcr_storage_types::RevenueRecoveryWorkflowTrackingData>(
"PCRWorkflowTrackingData",
)?;
let request = PaymentsGetIntentRequest {
id: tracking_data.global_payment_id.clone(),
};
let revenue_recovery_payment_data =
extract_data_and_perform_action(state, &tracking_data).await?;
let merchant_context_from_revenue_recovery_payment_data =
domain::MerchantContext::NormalMerchant(Box::new(domain::Context(
revenue_recovery_payment_data.merchant_account.clone(),
revenue_recovery_payment_data.key_store.clone(),
)));
let (payment_data, _, _) = payments::payments_intent_operation_core::<
api_types::PaymentGetIntent,
_,
_,
PaymentIntentData<api_types::PaymentGetIntent>,
>(
state,
state.get_req_state(),
merchant_context_from_revenue_recovery_payment_data.clone(),
revenue_recovery_payment_data.profile.clone(),
payments::operations::PaymentGetIntent,
request,
tracking_data.global_payment_id.clone(),
hyperswitch_domain_models::payments::HeaderPayload::default(),
)
.await?;
match process.name.as_deref() {
Some("EXECUTE_WORKFLOW") => {
Box::pin(pcr::perform_execute_payment(
state,
&process,
&revenue_recovery_payment_data.profile.clone(),
merchant_context_from_revenue_recovery_payment_data.clone(),
&tracking_data,
&revenue_recovery_payment_data,
&payment_data.payment_intent,
))
.await
}
Some("PSYNC_WORKFLOW") => {
Box::pin(pcr::perform_payments_sync(
state,
&process,
&revenue_recovery_payment_data.profile.clone(),
merchant_context_from_revenue_recovery_payment_data.clone(),
&tracking_data,
&revenue_recovery_payment_data,
&payment_data.payment_intent,
))
.await?;
Ok(())
}
Some("CALCULATE_WORKFLOW") => {
Box::pin(pcr::perform_calculate_workflow(
state,
&process,
&revenue_recovery_payment_data.profile.clone(),
merchant_context_from_revenue_recovery_payment_data,
&tracking_data,
&revenue_recovery_payment_data,
&payment_data.payment_intent,
))
.await
}
_ => Err(errors::ProcessTrackerError::JobNotFound),
}
}
#[instrument(skip_all)]
async fn error_handler<'a>(
&'a self,
state: &'a SessionState,
process: storage::ProcessTracker,
error: errors::ProcessTrackerError,
) -> CustomResult<(), errors::ProcessTrackerError> {
logger::error!("Encountered error");
consumer::consumer_error_handler(state.store.as_scheduler(), process, error).await
}
}
#[cfg(feature = "v2")]
pub(crate) async fn extract_data_and_perform_action(
state: &SessionState,
tracking_data: &pcr_storage_types::RevenueRecoveryWorkflowTrackingData,
) -> Result<pcr_storage_types::RevenueRecoveryPaymentData, errors::ProcessTrackerError> {
let db = &state.store;
let key_manager_state = &state.into();
let key_store = db
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&tracking_data.merchant_id,
&db.get_master_key().to_vec().into(),
)
.await?;
let merchant_account = db
.find_merchant_account_by_merchant_id(
key_manager_state,
&tracking_data.merchant_id,
&key_store,
)
.await?;
let profile = db
.find_business_profile_by_profile_id(
key_manager_state,
&key_store,
&tracking_data.profile_id,
)
.await?;
let billing_mca = db
.find_merchant_connector_account_by_id(
key_manager_state,
&tracking_data.billing_mca_id,
&key_store,
)
.await?;
let pcr_payment_data = pcr_storage_types::RevenueRecoveryPaymentData {
merchant_account,
profile: profile.clone(),
key_store,
billing_mca,
retry_algorithm: profile
.revenue_recovery_retry_algorithm_type
.unwrap_or(tracking_data.revenue_recovery_retry),
psync_data: None,
};
Ok(pcr_payment_data)
}
#[cfg(feature = "v2")]
pub(crate) async fn get_schedule_time_to_retry_mit_payments(
db: &dyn StorageInterface,
merchant_id: &id_type::MerchantId,
retry_count: i32,
) -> Option<time::PrimitiveDateTime> {
let key = "pt_mapping_pcr_retries";
let result = db
.find_config_by_key(key)
.await
.map(|value| value.config)
.and_then(|config| {
config
.parse_struct("RevenueRecoveryPaymentProcessTrackerMapping")
.change_context(StorageError::DeserializationFailed)
});
let mapping = result.map_or_else(
|error| {
if error.current_context().is_db_not_found() {
logger::debug!("Revenue Recovery retry config `{key}` not found, ignoring");
} else {
logger::error!(
?error,
"Failed to read Revenue Recovery retry config `{key}`"
);
}
process_data::RevenueRecoveryPaymentProcessTrackerMapping::default()
},
|mapping| {
logger::debug!(?mapping, "Using custom pcr payments retry config");
mapping
},
);
let time_delta =
scheduler_utils::get_pcr_payments_retry_schedule_time(mapping, merchant_id, retry_count);
scheduler_utils::get_time_from_delta(time_delta)
}
#[cfg(feature = "v2")]
pub(crate) async fn get_schedule_time_for_smart_retry(
state: &SessionState,
payment_intent: &PaymentIntent,
retry_after_time: Option<prost_types::Timestamp>,
token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let card_config = &state.conf.revenue_recovery.card_config;
// Not populating it right now
let first_error_message = "None".to_string();
let retry_count_left = token_with_retry_info.monthly_retry_remaining;
let pg_error_code = token_with_retry_info.token_status.error_code.clone();
let card_info = token_with_retry_info
.token_status
.payment_processor_token_details
.clone();
let billing_state = payment_intent
.billing_address
.as_ref()
.and_then(|addr_enc| addr_enc.get_inner().address.as_ref())
.and_then(|details| details.state.as_ref())
.cloned();
let revenue_recovery_metadata = payment_intent
.feature_metadata
.as_ref()
.and_then(|metadata| metadata.payment_revenue_recovery_metadata.as_ref());
let card_network = card_info.card_network.clone();
let total_retry_count_within_network = card_config.get_network_config(card_network.clone());
let card_network_str = card_network.map(|network| network.to_string());
let card_issuer_str = card_info.card_issuer.clone();
let card_funding_str = match card_info.card_type.as_deref() {
Some("card") => None,
Some(s) => Some(s.to_string()),
None => None,
};
let start_time_primitive = payment_intent.created_at;
let recovery_timestamp_config = &state.conf.revenue_recovery.recovery_timestamp;
let modified_start_time_primitive = start_time_primitive.saturating_add(
time::Duration::seconds(recovery_timestamp_config.initial_timestamp_in_seconds),
);
let start_time_proto = date_time::convert_to_prost_timestamp(modified_start_time_primitive);
let merchant_id = Some(payment_intent.merchant_id.get_string_repr().to_string());
let invoice_amount = Some(
payment_intent
.amount_details
.order_amount
.get_amount_as_i64(),
);
let invoice_currency = Some(payment_intent.amount_details.currency.to_string());
let billing_country = payment_intent
.billing_address
.as_ref()
.and_then(|addr_enc| addr_enc.get_inner().address.as_ref())
.and_then(|details| details.country.as_ref())
.map(|country| country.to_string());
let billing_city = payment_intent
.billing_address
.as_ref()
.and_then(|addr_enc| addr_enc.get_inner().address.as_ref())
.and_then(|details| details.city.as_ref())
.cloned();
let first_pg_error_code = revenue_recovery_metadata
.and_then(|metadata| metadata.first_payment_attempt_pg_error_code.clone());
let first_network_advice_code = revenue_recovery_metadata
.and_then(|metadata| metadata.first_payment_attempt_network_advice_code.clone());
let first_network_error_code = revenue_recovery_metadata
.and_then(|metadata| metadata.first_payment_attempt_network_decline_code.clone());
let invoice_due_date = revenue_recovery_metadata
.and_then(|metadata| metadata.invoice_next_billing_time)
.map(date_time::convert_to_prost_timestamp);
let decider_request = InternalDeciderRequest {
first_error_message,
billing_state,
card_funding: card_funding_str,
card_network: card_network_str,
card_issuer: card_issuer_str,
invoice_start_time: Some(start_time_proto),
retry_count: Some(token_with_retry_info.total_30_day_retries.into()),
merchant_id,
invoice_amount,
invoice_currency,
invoice_due_date,
billing_country,
billing_city,
attempt_currency: None,
attempt_status: None,
attempt_amount: None,
pg_error_code,
network_advice_code: None,
network_error_code: None,
first_pg_error_code,
first_network_advice_code,
first_network_error_code,
attempt_response_time: None,
payment_method_type: None,
payment_gateway: None,
retry_count_left: Some(retry_count_left.into()),
total_retry_count_within_network: Some(
total_retry_count_within_network
.max_retry_count_for_thirty_day
.into(),
),
first_error_msg_time: None,
wait_time: retry_after_time,
};
if let Some(mut client) = state.grpc_client.recovery_decider_client.clone() {
match client
.decide_on_retry(decider_request.into(), state.get_recovery_grpc_headers())
.await
{
Ok(grpc_response) => Ok(grpc_response
.retry_flag
.then_some(())
.and(grpc_response.retry_time)
.and_then(|prost_ts| {
match date_time::convert_from_prost_timestamp(&prost_ts) {
Ok(pdt) => Some(pdt),
Err(e) => {
logger::error!(
"Failed to convert retry_time from prost::Timestamp: {e:?}"
);
None // If conversion fails, treat as no valid retry time
}
}
})),
Err(e) => {
logger::error!("Recovery decider gRPC call failed: {e:?}");
Ok(None)
}
}
} else {
logger::debug!("Recovery decider client is not configured");
Ok(None)
}
}
#[cfg(feature = "v2")]
#[derive(Debug)]
struct InternalDeciderRequest {
first_error_message: String,
billing_state: Option<Secret<String>>,
card_funding: Option<String>,
card_network: Option<String>,
card_issuer: Option<String>,
invoice_start_time: Option<prost_types::Timestamp>,
retry_count: Option<i64>,
merchant_id: Option<String>,
invoice_amount: Option<i64>,
invoice_currency: Option<String>,
invoice_due_date: Option<prost_types::Timestamp>,
billing_country: Option<String>,
billing_city: Option<String>,
attempt_currency: Option<String>,
attempt_status: Option<String>,
attempt_amount: Option<i64>,
pg_error_code: Option<String>,
network_advice_code: Option<String>,
network_error_code: Option<String>,
first_pg_error_code: Option<String>,
first_network_advice_code: Option<String>,
first_network_error_code: Option<String>,
attempt_response_time: Option<prost_types::Timestamp>,
payment_method_type: Option<String>,
payment_gateway: Option<String>,
retry_count_left: Option<i64>,
total_retry_count_within_network: Option<i64>,
first_error_msg_time: Option<prost_types::Timestamp>,
wait_time: Option<prost_types::Timestamp>,
}
#[cfg(feature = "v2")]
impl From<InternalDeciderRequest> for external_grpc_client::DeciderRequest {
fn from(internal_request: InternalDeciderRequest) -> Self {
Self {
first_error_message: internal_request.first_error_message,
billing_state: internal_request.billing_state.map(|s| s.peek().to_string()),
card_funding: internal_request.card_funding,
card_network: internal_request.card_network,
card_issuer: internal_request.card_issuer,
invoice_start_time: internal_request.invoice_start_time,
retry_count: internal_request.retry_count,
merchant_id: internal_request.merchant_id,
invoice_amount: internal_request.invoice_amount,
invoice_currency: internal_request.invoice_currency,
invoice_due_date: internal_request.invoice_due_date,
billing_country: internal_request.billing_country,
billing_city: internal_request.billing_city,
attempt_currency: internal_request.attempt_currency,
attempt_status: internal_request.attempt_status,
attempt_amount: internal_request.attempt_amount,
pg_error_code: internal_request.pg_error_code,
network_advice_code: internal_request.network_advice_code,
network_error_code: internal_request.network_error_code,
first_pg_error_code: internal_request.first_pg_error_code,
first_network_advice_code: internal_request.first_network_advice_code,
first_network_error_code: internal_request.first_network_error_code,
attempt_response_time: internal_request.attempt_response_time,
payment_method_type: internal_request.payment_method_type,
payment_gateway: internal_request.payment_gateway,
retry_count_left: internal_request.retry_count_left,
total_retry_count_within_network: internal_request.total_retry_count_within_network,
first_error_msg_time: internal_request.first_error_msg_time,
wait_time: internal_request.wait_time,
}
}
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone)]
pub struct ScheduledToken {
pub token_details: PaymentProcessorTokenDetails,
pub schedule_time: time::PrimitiveDateTime,
}
#[cfg(feature = "v2")]
pub fn calculate_difference_in_seconds(scheduled_time: time::PrimitiveDateTime) -> i64 {
let now_utc = time::OffsetDateTime::now_utc();
let scheduled_offset_dt = scheduled_time.assume_utc();
let difference = scheduled_offset_dt - now_utc;
difference.whole_seconds()
}
#[cfg(feature = "v2")]
pub async fn update_token_expiry_based_on_schedule_time(
state: &SessionState,
connector_customer_id: &str,
delayed_schedule_time: Option<time::PrimitiveDateTime>,
) -> CustomResult<(), errors::ProcessTrackerError> {
let expiry_buffer = state
.conf
.revenue_recovery
.recovery_timestamp
.redis_ttl_buffer_in_seconds;
delayed_schedule_time
.async_map(|t| async move {
let expiry_time = calculate_difference_in_seconds(t) + expiry_buffer;
RedisTokenManager::update_connector_customer_lock_ttl(
state,
connector_customer_id,
expiry_time,
)
.await
.change_context(errors::ProcessTrackerError::ERedisError(
errors::RedisError::RedisConnectionError.into(),
))
})
.await
.transpose()?;
Ok(())
}
#[cfg(feature = "v2")]
pub async fn get_token_with_schedule_time_based_on_retry_algorithm_type(
state: &SessionState,
connector_customer_id: &str,
payment_intent: &PaymentIntent,
retry_algorithm_type: RevenueRecoveryAlgorithmType,
retry_count: i32,
) -> CustomResult<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let mut scheduled_time = None;
match retry_algorithm_type {
RevenueRecoveryAlgorithmType::Monitoring => {
logger::error!("Monitoring type found for Revenue Recovery retry payment");
}
RevenueRecoveryAlgorithmType::Cascading => {
let time = get_schedule_time_to_retry_mit_payments(
state.store.as_ref(),
&payment_intent.merchant_id,
retry_count,
)
.await
.ok_or(errors::ProcessTrackerError::EApiErrorResponse)?;
scheduled_time = Some(time);
}
RevenueRecoveryAlgorithmType::Smart => {
scheduled_time = get_best_psp_token_available_for_smart_retry(
state,
connector_customer_id,
payment_intent,
)
.await
.change_context(errors::ProcessTrackerError::EApiErrorResponse)?;
}
}
let delayed_schedule_time =
scheduled_time.map(|time| add_random_delay_to_schedule_time(state, time));
let _ = update_token_expiry_based_on_schedule_time(
state,
connector_customer_id,
delayed_schedule_time,
)
.await;
Ok(delayed_schedule_time)
}
#[cfg(feature = "v2")]
pub async fn get_best_psp_token_available_for_smart_retry(
state: &SessionState,
connector_customer_id: &str,
payment_intent: &PaymentIntent,
) -> CustomResult<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
// Lock using payment_id
let locked = RedisTokenManager::lock_connector_customer_status(
state,
connector_customer_id,
&payment_intent.id,
)
.await
.change_context(errors::ProcessTrackerError::ERedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
match !locked {
true => Ok(None),
false => {
// Get existing tokens from Redis
let existing_tokens =
RedisTokenManager::get_connector_customer_payment_processor_tokens(
state,
connector_customer_id,
)
.await
.change_context(errors::ProcessTrackerError::ERedisError(
errors::RedisError::RedisConnectionError.into(),
))?;
// TODO: Insert into payment_intent_feature_metadata (DB operation)
let result = RedisTokenManager::get_tokens_with_retry_metadata(state, &existing_tokens);
let best_token_time = call_decider_for_payment_processor_tokens_select_closet_time(
state,
&result,
payment_intent,
connector_customer_id,
)
.await
.change_context(errors::ProcessTrackerError::EApiErrorResponse)?;
Ok(best_token_time)
}
}
}
#[cfg(feature = "v2")]
pub async fn calculate_smart_retry_time(
state: &SessionState,
payment_intent: &PaymentIntent,
token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,
) -> Result<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
let wait_hours = token_with_retry_info.retry_wait_time_hours;
let current_time = time::OffsetDateTime::now_utc();
let future_time = current_time + time::Duration::hours(wait_hours);
// Timestamp after which retry can be done without penalty
let future_timestamp = Some(prost_types::Timestamp {
seconds: future_time.unix_timestamp(),
nanos: 0,
});
get_schedule_time_for_smart_retry(
state,
payment_intent,
future_timestamp,
token_with_retry_info,
)
.await
}
#[cfg(feature = "v2")]
async fn process_token_for_retry(
state: &SessionState,
token_with_retry_info: &PaymentProcessorTokenWithRetryInfo,
payment_intent: &PaymentIntent,
) -> Result<Option<ScheduledToken>, errors::ProcessTrackerError> {
let token_status: &PaymentProcessorTokenStatus = &token_with_retry_info.token_status;
let inserted_by_attempt_id = &token_status.inserted_by_attempt_id;
let skip = token_status.is_hard_decline.unwrap_or(false);
match skip {
true => {
logger::info!(
"Skipping decider call due to hard decline token inserted by attempt_id: {}",
inserted_by_attempt_id.get_string_repr()
);
Ok(None)
}
false => {
let schedule_time =
calculate_smart_retry_time(state, payment_intent, token_with_retry_info).await?;
Ok(schedule_time.map(|schedule_time| ScheduledToken {
token_details: token_status.payment_processor_token_details.clone(),
schedule_time,
}))
}
}
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn call_decider_for_payment_processor_tokens_select_closet_time(
state: &SessionState,
processor_tokens: &HashMap<String, PaymentProcessorTokenWithRetryInfo>,
payment_intent: &PaymentIntent,
connector_customer_id: &str,
) -> CustomResult<Option<time::PrimitiveDateTime>, errors::ProcessTrackerError> {
tracing::debug!("Filtered payment attempts based on payment tokens",);
let mut tokens_with_schedule_time: Vec<ScheduledToken> = Vec::new();
for token_with_retry_info in processor_tokens.values() {
let token_details = &token_with_retry_info
.token_status
.payment_processor_token_details;
let error_code = token_with_retry_info.token_status.error_code.clone();
match error_code {
None => {
let utc_schedule_time =
time::OffsetDateTime::now_utc() + time::Duration::minutes(1);
let schedule_time = time::PrimitiveDateTime::new(
utc_schedule_time.date(),
utc_schedule_time.time(),
);
tokens_with_schedule_time = vec![ScheduledToken {
token_details: token_details.clone(),
schedule_time,
}];
tracing::debug!(
"Found payment processor token with no error code scheduling it for {schedule_time}",
);
break;
}
Some(_) => {
process_token_for_retry(state, token_with_retry_info, payment_intent)
.await?
.map(|token_with_schedule_time| {
tokens_with_schedule_time.push(token_with_schedule_time)
});
}
}
}
let best_token = tokens_with_schedule_time
.iter()
.min_by_key(|token| token.schedule_time)
.cloned();
match best_token {
None => {
RedisTokenManager::unlock_connector_customer_status(state, connector_customer_id)
.await
.change_context(errors::ProcessTrackerError::EApiErrorResponse)?;
tracing::debug!("No payment processor tokens available for scheduling");
Ok(None)
}
Some(token) => {
tracing::debug!("Found payment processor token with least schedule time");
RedisTokenManager::update_payment_processor_token_schedule_time(
state,
connector_customer_id,
&token.token_details.payment_processor_token,
Some(token.schedule_time),
)
.await
.change_context(errors::ProcessTrackerError::EApiErrorResponse)?;
Ok(Some(token.schedule_time))
}
}
}
#[cfg(feature = "v2")]
pub async fn check_hard_decline(
state: &SessionState,
payment_attempt: &payment_attempt::PaymentAttempt,
) -> Result<bool, error_stack::Report<storage_impl::errors::RecoveryError>> {
let error_message = payment_attempt
.error
.as_ref()
.map(|details| details.message.clone());
let error_code = payment_attempt
.error
.as_ref()
.map(|details| details.code.clone());
let connector_name = payment_attempt
.connector
.clone()
.ok_or(storage_impl::errors::RecoveryError::ValueNotFound)
.attach_printable("unable to derive payment connector from payment attempt")?;
let gsm_record = payments::helpers::get_gsm_record(
state,
error_code,
error_message,
connector_name,
REVENUE_RECOVERY.to_string(),
)
.await;
let is_hard_decline = gsm_record
.and_then(|record| record.error_category)
.map(|category| category == common_enums::ErrorCategory::HardDecline)
.unwrap_or(false);
Ok(is_hard_decline)
}
#[cfg(feature = "v2")]
pub fn add_random_delay_to_schedule_time(
state: &SessionState,
schedule_time: time::PrimitiveDateTime,
) -> time::PrimitiveDateTime {
let mut rng = rand::thread_rng();
let delay_limit = state
.conf
.revenue_recovery
.recovery_timestamp
.max_random_schedule_delay_in_seconds;
let random_secs = rng.gen_range(1..=delay_limit);
logger::info!("Adding random delay of {random_secs} seconds to schedule time");
schedule_time + time::Duration::seconds(random_secs)
}
|
crates/router/src/workflows/revenue_recovery.rs
|
router
|
full_file
| null | null | null | 6,037
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentVoid for for Ebanx
// File: crates/hyperswitch_connectors/src/connectors/ebanx.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Ebanx
|
crates/hyperswitch_connectors/src/connectors/ebanx.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Ebanx
|
api::PaymentVoid for
| 0
| 0
| null | null |
// File: crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs
// Module: hyperswitch_connectors
// Public functions: 2
// Public structs: 32
use api_models::webhooks::IncomingWebhookEvent;
use cards::CardNumber;
use common_enums::enums;
use common_utils::{
pii::{self, SecretSerdeValue},
request::Method,
types::MinorUnit,
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{
BankRedirectData, BankTransferData, Card as CardData, CryptoData, GiftCardData,
PayLaterData, PaymentMethodData, VoucherData, WalletData,
},
router_data::{ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
CompleteAuthorizeData, PaymentsAuthorizeData, PaymentsPreProcessingData, ResponseId,
},
router_response_types::{PaymentsResponseData, RedirectForm, RefundsResponseData},
types::{PaymentsPreProcessingRouterData, RefundsRouterData},
};
use hyperswitch_interfaces::errors;
use masking::Secret;
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{
PaymentsPreprocessingResponseRouterData, RefundsResponseRouterData, ResponseRouterData,
},
utils::{
self, to_connector_meta, PaymentsAuthorizeRequestData,
PaymentsCompleteAuthorizeRequestData, PaymentsPreProcessingRequestData, RouterData as _,
},
};
type Error = error_stack::Report<errors::ConnectorError>;
trait Shift4AuthorizePreprocessingCommon {
fn is_automatic_capture(&self) -> Result<bool, Error>;
fn get_router_return_url(&self) -> Option<String>;
fn get_email_optional(&self) -> Option<pii::Email>;
fn get_complete_authorize_url(&self) -> Option<String>;
fn get_currency_required(&self) -> Result<enums::Currency, Error>;
fn get_metadata(&self) -> Result<Option<serde_json::Value>, Error>;
fn get_payment_method_data_required(&self) -> Result<PaymentMethodData, Error>;
}
pub struct Shift4RouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> TryFrom<(MinorUnit, T)> for Shift4RouterData<T> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from((amount, item): (MinorUnit, T)) -> Result<Self, Self::Error> {
Ok(Self {
amount,
router_data: item,
})
}
}
impl Shift4AuthorizePreprocessingCommon for PaymentsAuthorizeData {
fn get_email_optional(&self) -> Option<pii::Email> {
self.email.clone()
}
fn get_complete_authorize_url(&self) -> Option<String> {
self.complete_authorize_url.clone()
}
fn get_currency_required(
&self,
) -> Result<enums::Currency, error_stack::Report<errors::ConnectorError>> {
Ok(self.currency)
}
fn get_payment_method_data_required(
&self,
) -> Result<PaymentMethodData, error_stack::Report<errors::ConnectorError>> {
Ok(self.payment_method_data.clone())
}
fn is_automatic_capture(&self) -> Result<bool, Error> {
self.is_auto_capture()
}
fn get_router_return_url(&self) -> Option<String> {
self.router_return_url.clone()
}
fn get_metadata(
&self,
) -> Result<Option<serde_json::Value>, error_stack::Report<errors::ConnectorError>> {
Ok(self.metadata.clone())
}
}
impl Shift4AuthorizePreprocessingCommon for PaymentsPreProcessingData {
fn get_email_optional(&self) -> Option<pii::Email> {
self.email.clone()
}
fn get_complete_authorize_url(&self) -> Option<String> {
self.complete_authorize_url.clone()
}
fn get_currency_required(&self) -> Result<enums::Currency, Error> {
self.get_currency()
}
fn get_payment_method_data_required(&self) -> Result<PaymentMethodData, Error> {
self.payment_method_data.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "payment_method_data",
}
.into(),
)
}
fn is_automatic_capture(&self) -> Result<bool, Error> {
self.is_auto_capture()
}
fn get_router_return_url(&self) -> Option<String> {
self.router_return_url.clone()
}
fn get_metadata(
&self,
) -> Result<Option<serde_json::Value>, error_stack::Report<errors::ConnectorError>> {
Ok(None)
}
}
#[derive(Debug, Serialize)]
pub struct Shift4PaymentsRequest {
amount: MinorUnit,
currency: enums::Currency,
captured: bool,
metadata: Option<serde_json::Value>,
#[serde(flatten)]
payment_method: Shift4PaymentMethod,
}
#[derive(Debug, Serialize)]
#[serde(untagged)]
pub enum Shift4PaymentMethod {
CardsNon3DSRequest(Box<CardsNon3DSRequest>),
BankRedirectRequest(Box<BankRedirectRequest>),
Cards3DSRequest(Box<Cards3DSRequest>),
VoucherRequest(Box<VoucherRequest>),
WalletRequest(Box<WalletRequest>),
PayLaterRequest(Box<PayLaterRequest>),
CryptoRequest(Box<CryptoRequest>),
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct WalletRequest {
flow: Flow,
payment_method: PaymentMethod,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PayLaterRequest {
flow: Flow,
payment_method: PaymentMethod,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CryptoRequest {
flow: Flow,
payment_method: PaymentMethod,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct VoucherRequest {
flow: Flow,
payment_method: PaymentMethod,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct BankRedirectRequest {
payment_method: PaymentMethod,
flow: Flow,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Cards3DSRequest {
#[serde(rename = "card[number]")]
pub card_number: CardNumber,
#[serde(rename = "card[expMonth]")]
pub card_exp_month: Secret<String>,
#[serde(rename = "card[expYear]")]
pub card_exp_year: Secret<String>,
return_url: String,
}
#[serde_with::skip_serializing_none]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardsNon3DSRequest {
card: CardPayment,
description: Option<String>,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Flow {
pub return_url: String,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PaymentMethodType {
Eps,
Giropay,
Ideal,
Sofort,
Boleto,
Trustly,
Alipay,
Wechatpay,
Blik,
KlarnaDebitRisk,
Bitpay,
Paysera,
Skrill,
}
#[derive(Debug, Serialize)]
pub struct PaymentMethod {
#[serde(rename = "type")]
method_type: PaymentMethodType,
billing: Billing,
}
#[derive(Debug, Serialize)]
pub struct Billing {
name: Option<Secret<String>>,
email: Option<pii::Email>,
address: Option<Address>,
#[serde(skip_serializing_if = "Option::is_none")]
vat: Option<Secret<String>>,
}
#[derive(Debug, Serialize)]
pub struct Address {
line1: Option<Secret<String>>,
line2: Option<Secret<String>>,
zip: Option<Secret<String>>,
state: Option<Secret<String>>,
city: Option<String>,
country: Option<api_models::enums::CountryAlpha2>,
}
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
pub struct DeviceData;
#[derive(Default, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Card {
pub number: CardNumber,
pub exp_month: Secret<String>,
pub exp_year: Secret<String>,
pub cardholder_name: Secret<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(untagged)]
pub enum CardPayment {
RawCard(Box<Card>),
CardToken(Secret<String>),
}
impl<T, Req> TryFrom<&Shift4RouterData<&RouterData<T, Req, PaymentsResponseData>>>
for Shift4PaymentsRequest
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
item: &Shift4RouterData<&RouterData<T, Req, PaymentsResponseData>>,
) -> Result<Self, Self::Error> {
let submit_for_settlement = item.router_data.request.is_automatic_capture()?;
let amount = item.amount.to_owned();
let currency = item.router_data.request.get_currency_required()?;
let metadata = item.router_data.request.get_metadata()?;
let payment_method = Shift4PaymentMethod::try_from(item.router_data)?;
Ok(Self {
amount,
currency,
captured: submit_for_settlement,
metadata,
payment_method,
})
}
}
impl TryFrom<&PayLaterData> for PaymentMethodType {
type Error = Error;
fn try_from(value: &PayLaterData) -> Result<Self, Self::Error> {
match value {
PayLaterData::KlarnaRedirect { .. } => Ok(Self::KlarnaDebitRisk),
PayLaterData::AffirmRedirect { .. }
| PayLaterData::AfterpayClearpayRedirect { .. }
| PayLaterData::PayBrightRedirect { .. }
| PayLaterData::WalleyRedirect { .. }
| PayLaterData::AlmaRedirect { .. }
| PayLaterData::AtomeRedirect { .. }
| PayLaterData::FlexitiRedirect { .. }
| PayLaterData::KlarnaSdk { .. }
| PayLaterData::BreadpayRedirect { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
}
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &PayLaterData)>
for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, pay_later_data): (&RouterData<T, Req, PaymentsResponseData>, &PayLaterData),
) -> Result<Self, Self::Error> {
let flow = Flow::try_from(item.request.get_router_return_url())?;
let method_type = PaymentMethodType::try_from(pay_later_data)?;
let billing = Billing::try_from(item)?;
let payment_method = PaymentMethod {
method_type,
billing,
};
Ok(Self::BankRedirectRequest(Box::new(BankRedirectRequest {
payment_method,
flow,
})))
}
}
impl<T, Req> TryFrom<&RouterData<T, Req, PaymentsResponseData>> for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(item: &RouterData<T, Req, PaymentsResponseData>) -> Result<Self, Self::Error> {
match item.request.get_payment_method_data_required()? {
PaymentMethodData::Card(ref ccard) => Self::try_from((item, ccard)),
PaymentMethodData::BankRedirect(ref redirect) => Self::try_from((item, redirect)),
PaymentMethodData::Wallet(ref wallet_data) => Self::try_from((item, wallet_data)),
PaymentMethodData::BankTransfer(ref bank_transfer_data) => {
Self::try_from(bank_transfer_data.as_ref())
}
PaymentMethodData::Voucher(ref voucher_data) => Self::try_from((item, voucher_data)),
PaymentMethodData::GiftCard(ref giftcard_data) => {
Self::try_from(giftcard_data.as_ref())
}
PaymentMethodData::PayLater(ref pay_later_data) => {
Self::try_from((item, pay_later_data))
}
PaymentMethodData::Crypto(ref crypto_data) => Self::try_from((item, crypto_data)),
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into())
}
}
}
}
impl TryFrom<&WalletData> for PaymentMethodType {
type Error = Error;
fn try_from(value: &WalletData) -> Result<Self, Self::Error> {
match value {
WalletData::AliPayRedirect { .. } => Ok(Self::Alipay),
WalletData::WeChatPayRedirect { .. } => Ok(Self::Wechatpay),
WalletData::Paysera(_) => Ok(Self::Paysera),
WalletData::Skrill(_) => Ok(Self::Skrill),
WalletData::AliPayQr(_)
| WalletData::AmazonPay(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::GooglePay(_)
| WalletData::BluecodeRedirect {}
| WalletData::PaypalRedirect(_)
| WalletData::MbWayRedirect(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
}
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &WalletData)>
for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, wallet_data): (&RouterData<T, Req, PaymentsResponseData>, &WalletData),
) -> Result<Self, Self::Error> {
let flow = Flow::try_from(item.request.get_router_return_url())?;
let method_type = PaymentMethodType::try_from(wallet_data)?;
let billing = Billing::try_from(item)?;
let payment_method = PaymentMethod {
method_type,
billing,
};
Ok(Self::WalletRequest(Box::new(WalletRequest {
payment_method,
flow,
})))
}
}
impl TryFrom<&BankTransferData> for Shift4PaymentMethod {
type Error = Error;
fn try_from(bank_transfer_data: &BankTransferData) -> Result<Self, Self::Error> {
match bank_transfer_data {
BankTransferData::MultibancoBankTransfer { .. }
| BankTransferData::AchBankTransfer { .. }
| BankTransferData::SepaBankTransfer { .. }
| BankTransferData::BacsBankTransfer { .. }
| BankTransferData::PermataBankTransfer { .. }
| BankTransferData::BcaBankTransfer { .. }
| BankTransferData::BniVaBankTransfer { .. }
| BankTransferData::BriVaBankTransfer { .. }
| BankTransferData::CimbVaBankTransfer { .. }
| BankTransferData::DanamonVaBankTransfer { .. }
| BankTransferData::MandiriVaBankTransfer { .. }
| BankTransferData::Pix { .. }
| BankTransferData::Pse {}
| BankTransferData::InstantBankTransfer {}
| BankTransferData::InstantBankTransferFinland { .. }
| BankTransferData::InstantBankTransferPoland { .. }
| BankTransferData::IndonesianBankTransfer { .. }
| BankTransferData::LocalBankTransfer { .. } => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into())
}
}
}
}
impl TryFrom<&VoucherData> for PaymentMethodType {
type Error = Error;
fn try_from(value: &VoucherData) -> Result<Self, Self::Error> {
match value {
VoucherData::Boleto { .. } => Ok(Self::Boleto),
VoucherData::Alfamart { .. }
| VoucherData::Indomaret { .. }
| VoucherData::Efecty
| VoucherData::PagoEfectivo
| VoucherData::RedCompra
| VoucherData::Oxxo
| VoucherData::RedPagos
| VoucherData::SevenEleven { .. }
| VoucherData::Lawson { .. }
| VoucherData::MiniStop { .. }
| VoucherData::FamilyMart { .. }
| VoucherData::Seicomart { .. }
| VoucherData::PayEasy { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
}
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &VoucherData)>
for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, voucher_data): (&RouterData<T, Req, PaymentsResponseData>, &VoucherData),
) -> Result<Self, Self::Error> {
let mut billing = Billing::try_from(item)?;
match voucher_data {
VoucherData::Boleto(boleto_data) => {
billing.vat = boleto_data.social_security_number.clone();
}
_ => {
billing.vat = None;
}
};
let method_type = PaymentMethodType::try_from(voucher_data)?;
let payment_method_details = PaymentMethod {
method_type,
billing,
};
let flow = Flow::try_from(item.request.get_router_return_url())?;
Ok(Self::VoucherRequest(Box::new(VoucherRequest {
payment_method: payment_method_details,
flow,
})))
}
}
impl TryFrom<&GiftCardData> for Shift4PaymentMethod {
type Error = Error;
fn try_from(gift_card_data: &GiftCardData) -> Result<Self, Self::Error> {
match gift_card_data {
GiftCardData::Givex(_)
| GiftCardData::PaySafeCard {}
| GiftCardData::BhnCardNetwork(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
}
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &CardData)> for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, card): (&RouterData<T, Req, PaymentsResponseData>, &CardData),
) -> Result<Self, Self::Error> {
let card_object = Card {
number: card.card_number.clone(),
exp_month: card.card_exp_month.clone(),
exp_year: card.card_exp_year.clone(),
cardholder_name: item
.get_optional_billing_full_name()
.unwrap_or(Secret::new("".to_string())),
};
if item.is_three_ds() {
Ok(Self::Cards3DSRequest(Box::new(Cards3DSRequest {
card_number: card_object.number,
card_exp_month: card_object.exp_month,
card_exp_year: card_object.exp_year,
return_url: item
.request
.get_complete_authorize_url()
.clone()
.ok_or_else(|| errors::ConnectorError::RequestEncodingFailed)?,
})))
} else {
Ok(Self::CardsNon3DSRequest(Box::new(CardsNon3DSRequest {
card: CardPayment::RawCard(Box::new(card_object)),
description: item.description.clone(),
})))
}
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &BankRedirectData)>
for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, redirect_data): (&RouterData<T, Req, PaymentsResponseData>, &BankRedirectData),
) -> Result<Self, Self::Error> {
let flow = Flow::try_from(item.request.get_router_return_url())?;
let method_type = PaymentMethodType::try_from(redirect_data)?;
let billing = Billing::try_from(item)?;
let payment_method = PaymentMethod {
method_type,
billing,
};
Ok(Self::BankRedirectRequest(Box::new(BankRedirectRequest {
payment_method,
flow,
})))
}
}
impl TryFrom<&CryptoData> for PaymentMethodType {
type Error = Error;
fn try_from(_value: &CryptoData) -> Result<Self, Self::Error> {
Ok(Self::Bitpay)
}
}
impl<T, Req> TryFrom<(&RouterData<T, Req, PaymentsResponseData>, &CryptoData)>
for Shift4PaymentMethod
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(
(item, redirect_data): (&RouterData<T, Req, PaymentsResponseData>, &CryptoData),
) -> Result<Self, Self::Error> {
let flow = Flow::try_from(item.request.get_router_return_url())?;
let method_type = PaymentMethodType::try_from(redirect_data)?;
let billing = Billing::try_from(item)?;
let payment_method = PaymentMethod {
method_type,
billing,
};
Ok(Self::CryptoRequest(Box::new(CryptoRequest {
payment_method,
flow,
})))
}
}
impl<T> TryFrom<&Shift4RouterData<&RouterData<T, CompleteAuthorizeData, PaymentsResponseData>>>
for Shift4PaymentsRequest
{
type Error = Error;
fn try_from(
item: &Shift4RouterData<&RouterData<T, CompleteAuthorizeData, PaymentsResponseData>>,
) -> Result<Self, Self::Error> {
match &item.router_data.request.payment_method_data {
Some(PaymentMethodData::Card(_)) => {
let card_token: Shift4CardToken =
to_connector_meta(item.router_data.request.connector_meta.clone())?;
let metadata = item.router_data.request.metadata.clone();
Ok(Self {
amount: item.amount.to_owned(),
currency: item.router_data.request.currency,
metadata,
payment_method: Shift4PaymentMethod::CardsNon3DSRequest(Box::new(
CardsNon3DSRequest {
card: CardPayment::CardToken(card_token.id),
description: item.router_data.description.clone(),
},
)),
captured: item.router_data.request.is_auto_capture()?,
})
}
Some(PaymentMethodData::Wallet(_))
| Some(PaymentMethodData::GiftCard(_))
| Some(PaymentMethodData::CardRedirect(_))
| Some(PaymentMethodData::PayLater(_))
| Some(PaymentMethodData::BankDebit(_))
| Some(PaymentMethodData::BankRedirect(_))
| Some(PaymentMethodData::BankTransfer(_))
| Some(PaymentMethodData::Crypto(_))
| Some(PaymentMethodData::MandatePayment)
| Some(PaymentMethodData::Voucher(_))
| Some(PaymentMethodData::Reward)
| Some(PaymentMethodData::RealTimePayment(_))
| Some(PaymentMethodData::MobilePayment(_))
| Some(PaymentMethodData::Upi(_))
| Some(PaymentMethodData::OpenBanking(_))
| Some(PaymentMethodData::CardToken(_))
| Some(PaymentMethodData::NetworkToken(_))
| Some(PaymentMethodData::CardDetailsForNetworkTransactionId(_))
| None => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into()),
}
}
}
impl TryFrom<&BankRedirectData> for PaymentMethodType {
type Error = Error;
fn try_from(value: &BankRedirectData) -> Result<Self, Self::Error> {
match value {
BankRedirectData::Eps { .. } => Ok(Self::Eps),
BankRedirectData::Giropay { .. } => Ok(Self::Giropay),
BankRedirectData::Ideal { .. } => Ok(Self::Ideal),
BankRedirectData::Sofort { .. } => Ok(Self::Sofort),
BankRedirectData::Trustly { .. } => Ok(Self::Trustly),
BankRedirectData::Blik { .. } => Ok(Self::Blik),
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::Bizum {}
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Shift4"),
)
.into())
}
}
}
}
impl TryFrom<Option<String>> for Flow {
type Error = Error;
fn try_from(router_return_url: Option<String>) -> Result<Self, Self::Error> {
Ok(Self {
return_url: router_return_url.ok_or(errors::ConnectorError::RequestEncodingFailed)?,
})
}
}
impl<T, Req> TryFrom<&RouterData<T, Req, PaymentsResponseData>> for Billing
where
Req: Shift4AuthorizePreprocessingCommon,
{
type Error = Error;
fn try_from(item: &RouterData<T, Req, PaymentsResponseData>) -> Result<Self, Self::Error> {
let billing_details = item.get_optional_billing();
let address_details_model = billing_details.as_ref().and_then(|b| b.address.as_ref());
let address = get_address_details(address_details_model);
Ok(Self {
name: item.get_optional_billing_full_name(),
email: item.request.get_email_optional(),
address,
vat: None,
})
}
}
fn get_address_details(
address_details: Option<&hyperswitch_domain_models::address::AddressDetails>,
) -> Option<Address> {
address_details.map(|address| Address {
line1: address.line1.clone(),
line2: address.line1.clone(),
zip: address.zip.clone(),
state: address.state.clone(),
city: address.city.clone(),
country: address.country,
})
}
// Auth Struct
pub struct Shift4AuthType {
pub(super) api_key: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for Shift4AuthType {
type Error = Error;
fn try_from(item: &ConnectorAuthType) -> Result<Self, Self::Error> {
if let ConnectorAuthType::HeaderKey { api_key } = item {
Ok(Self {
api_key: api_key.to_owned(),
})
} else {
Err(errors::ConnectorError::FailedToObtainAuthType)?
}
}
}
// PaymentsResponse
#[derive(Debug, Clone, Default, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Shift4PaymentStatus {
Successful,
Failed,
#[default]
Pending,
}
fn get_status(
captured: bool,
next_action: Option<&NextAction>,
payment_status: Shift4PaymentStatus,
) -> enums::AttemptStatus {
match payment_status {
Shift4PaymentStatus::Successful => {
if captured {
enums::AttemptStatus::Charged
} else {
enums::AttemptStatus::Authorized
}
}
Shift4PaymentStatus::Failed => enums::AttemptStatus::Failure,
Shift4PaymentStatus::Pending => match next_action {
Some(NextAction::Redirect) => enums::AttemptStatus::AuthenticationPending,
Some(NextAction::Wait) | Some(NextAction::None) | None => enums::AttemptStatus::Pending,
},
}
}
#[derive(Debug, Deserialize)]
pub struct Shift4WebhookObjectEventType {
#[serde(rename = "type")]
pub event_type: Shift4WebhookEvent,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum Shift4WebhookEvent {
ChargeSucceeded,
ChargeFailed,
ChargeUpdated,
ChargeCaptured,
ChargeRefunded,
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize)]
pub struct Shift4WebhookObjectData {
pub id: String,
pub refunds: Option<Vec<RefundIdObject>>,
}
#[derive(Debug, Deserialize)]
pub struct RefundIdObject {
pub id: String,
}
#[derive(Debug, Deserialize)]
pub struct Shift4WebhookObjectId {
#[serde(rename = "type")]
pub event_type: Shift4WebhookEvent,
pub data: Shift4WebhookObjectData,
}
#[derive(Debug, Deserialize)]
pub struct Shift4WebhookObjectResource {
pub data: serde_json::Value,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct Shift4NonThreeDsResponse {
pub id: String,
pub currency: String,
pub amount: u32,
pub status: Shift4PaymentStatus,
pub captured: bool,
pub refunded: bool,
pub flow: Option<FlowResponse>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct Shift4ThreeDsResponse {
pub enrolled: bool,
pub version: Option<String>,
#[serde(rename = "redirectUrl")]
pub redirect_url: Option<Url>,
pub token: Token,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct Token {
pub id: Secret<String>,
pub created: i64,
#[serde(rename = "objectType")]
pub object_type: String,
pub first6: String,
pub last4: String,
pub fingerprint: Secret<String>,
pub brand: String,
#[serde(rename = "type")]
pub token_type: String,
pub country: String,
pub used: bool,
#[serde(rename = "threeDSecureInfo")]
pub three_d_secure_info: ThreeDSecureInfo,
}
#[derive(Default, Debug, Deserialize, Serialize)]
pub struct ThreeDSecureInfo {
pub amount: MinorUnit,
pub currency: String,
pub enrolled: bool,
#[serde(rename = "liabilityShift")]
pub liability_shift: Option<String>,
pub version: String,
#[serde(rename = "authenticationFlow")]
pub authentication_flow: Option<SecretSerdeValue>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct FlowResponse {
pub next_action: Option<NextAction>,
pub redirect: Option<Redirect>,
pub return_url: Option<Url>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Redirect {
pub redirect_url: Option<Url>,
}
#[derive(Debug, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum NextAction {
Redirect,
Wait,
None,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct Shift4CardToken {
pub id: Secret<String>,
}
impl TryFrom<PaymentsPreprocessingResponseRouterData<Shift4ThreeDsResponse>>
for PaymentsPreProcessingRouterData
{
type Error = Error;
fn try_from(
item: PaymentsPreprocessingResponseRouterData<Shift4ThreeDsResponse>,
) -> Result<Self, Self::Error> {
let redirection_data = item
.response
.redirect_url
.map(|url| RedirectForm::from((url, Method::Get)));
Ok(Self {
status: if redirection_data.is_some() {
enums::AttemptStatus::AuthenticationPending
} else {
enums::AttemptStatus::Pending
},
request: PaymentsPreProcessingData {
enrolled_for_3ds: item.response.enrolled,
..item.data.request
},
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::NoResponseId,
redirection_data: Box::new(redirection_data),
mandate_reference: Box::new(None),
connector_metadata: Some(
serde_json::to_value(Shift4CardToken {
id: item.response.token.id,
})
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?,
),
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
impl<T, F> TryFrom<ResponseRouterData<F, Shift4NonThreeDsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = Error;
fn try_from(
item: ResponseRouterData<F, Shift4NonThreeDsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let connector_id = ResponseId::ConnectorTransactionId(item.response.id.clone());
Ok(Self {
status: get_status(
item.response.captured,
item.response
.flow
.as_ref()
.and_then(|flow| flow.next_action.as_ref()),
item.response.status,
),
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: connector_id,
redirection_data: Box::new(
item.response
.flow
.and_then(|flow| flow.redirect)
.and_then(|redirect| redirect.redirect_url)
.map(|url| RedirectForm::from((url, Method::Get))),
),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.id),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
// REFUND :
// Type definition for RefundRequest
#[derive(Default, Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Shift4RefundRequest {
charge_id: String,
amount: MinorUnit,
}
impl<F> TryFrom<&Shift4RouterData<&RefundsRouterData<F>>> for Shift4RefundRequest {
type Error = Error;
fn try_from(item: &Shift4RouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
Ok(Self {
charge_id: item.router_data.request.connector_transaction_id.clone(),
amount: item.amount.to_owned(),
})
}
}
impl From<Shift4RefundStatus> for enums::RefundStatus {
fn from(item: Shift4RefundStatus) -> Self {
match item {
Shift4RefundStatus::Successful => Self::Success,
Shift4RefundStatus::Failed => Self::Failure,
Shift4RefundStatus::Processing => Self::Pending,
}
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize)]
pub struct RefundResponse {
pub id: String,
pub amount: i64,
pub currency: String,
pub charge: String,
pub status: Shift4RefundStatus,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum Shift4RefundStatus {
Successful,
Processing,
#[default]
Failed,
}
impl TryFrom<RefundsResponseRouterData<Execute, RefundResponse>> for RefundsRouterData<Execute> {
type Error = Error;
fn try_from(
item: RefundsResponseRouterData<Execute, RefundResponse>,
|
crates/hyperswitch_connectors/src/connectors/shift4/transformers.rs#chunk0
|
hyperswitch_connectors
|
chunk
| null | null | null | 8,187
| null | null | null | null | null | null | null |
// Trait: AuthInfo
// File: crates/router/src/services/authentication.rs
// Module: router
pub trait AuthInfo
|
crates/router/src/services/authentication.rs
|
router
|
trait_definition
| null | null | null | 25
| null | null |
AuthInfo
| null | null | null | null |
// Struct: MerchantDetails
// File: crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct MerchantDetails
|
crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs
|
hyperswitch_domain_models
|
struct_definition
|
MerchantDetails
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Trait: VaultingDataInterface
// File: crates/hyperswitch_domain_models/src/vault.rs
// Module: hyperswitch_domain_models
pub trait VaultingDataInterface
|
crates/hyperswitch_domain_models/src/vault.rs
|
hyperswitch_domain_models
|
trait_definition
| null | null | null | 37
| null | null |
VaultingDataInterface
| null | null | null | null |
// Implementation: impl Payouts
// File: crates/diesel_models/src/query/payouts.rs
// Module: diesel_models
// Methods: 5 total (0 public)
impl Payouts
|
crates/diesel_models/src/query/payouts.rs
|
diesel_models
|
impl_block
| null | null | null | 42
| null |
Payouts
| null | 5
| 0
| null | null |
// Implementation: impl FromStr for for AciStatus
// File: crates/hyperswitch_connectors/src/connectors/aci/transformers.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)
impl FromStr for for AciStatus
|
crates/hyperswitch_connectors/src/connectors/aci/transformers.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
AciStatus
|
FromStr for
| 1
| 0
| null | null |
}
PaymentMethodData::Voucher(ref voucher_data) => {
AdyenPaymentRequest::try_from((item, voucher_data))
}
PaymentMethodData::GiftCard(ref gift_card_data) => {
AdyenPaymentRequest::try_from((item, gift_card_data.as_ref()))
}
PaymentMethodData::NetworkToken(ref token_data) => {
AdyenPaymentRequest::try_from((item, token_data))
}
PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
))?
}
},
}
}
}
impl TryFrom<&PaymentsPreProcessingRouterData> for AdyenBalanceRequest<'_> {
type Error = Error;
fn try_from(item: &PaymentsPreProcessingRouterData) -> Result<Self, Self::Error> {
let payment_method = match &item.request.payment_method_data {
Some(PaymentMethodData::GiftCard(gift_card_data)) => match gift_card_data.as_ref() {
GiftCardData::Givex(gift_card_data) => {
let balance_pm = BalancePmData {
number: gift_card_data.number.clone(),
cvc: gift_card_data.cvc.clone(),
};
Ok(AdyenPaymentMethod::PaymentMethodBalance(Box::new(
balance_pm,
)))
}
GiftCardData::PaySafeCard {} | GiftCardData::BhnCardNetwork(_) => {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Balance".to_string(),
connector: "adyen".to_string(),
})
}
},
_ => Err(errors::ConnectorError::FlowNotSupported {
flow: "Balance".to_string(),
connector: "adyen".to_string(),
}),
}?;
let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
payment_method,
merchant_account: auth_type.merchant_account,
})
}
}
impl TryFrom<&PaymentsGiftCardBalanceCheckRouterData> for AdyenBalanceRequest<'_> {
type Error = Error;
fn try_from(item: &PaymentsGiftCardBalanceCheckRouterData) -> Result<Self, Self::Error> {
let payment_method = match &item.request.payment_method_data {
PaymentMethodData::GiftCard(gift_card_data) => match gift_card_data.as_ref() {
GiftCardData::Givex(gift_card_data) => {
let balance_pm = BalancePmData {
number: gift_card_data.number.clone(),
cvc: gift_card_data.cvc.clone(),
};
Ok(AdyenPaymentMethod::PaymentMethodBalance(Box::new(
balance_pm,
)))
}
GiftCardData::PaySafeCard {} | GiftCardData::BhnCardNetwork(_) => {
Err(errors::ConnectorError::FlowNotSupported {
flow: "Balance".to_string(),
connector: "adyen".to_string(),
})
}
},
_ => Err(errors::ConnectorError::FlowNotSupported {
flow: "Balance".to_string(),
connector: "adyen".to_string(),
}),
}?;
let auth_type = AdyenAuthType::try_from(&item.connector_auth_type)?;
Ok(Self {
payment_method,
merchant_account: auth_type.merchant_account,
})
}
}
impl From<&PaymentsAuthorizeRouterData> for AdyenShopperInteraction {
fn from(item: &PaymentsAuthorizeRouterData) -> Self {
match item.request.off_session {
Some(true) => Self::ContinuedAuthentication,
_ => match item.request.payment_channel {
Some(common_enums::PaymentChannel::Ecommerce)
| None
| Some(common_enums::PaymentChannel::Other(_)) => Self::Ecommerce,
Some(common_enums::PaymentChannel::MailOrder)
| Some(common_enums::PaymentChannel::TelephoneOrder) => Self::Moto,
},
}
}
}
type RecurringDetails = (Option<AdyenRecurringModel>, Option<bool>, Option<String>);
fn get_recurring_processing_model(
item: &PaymentsAuthorizeRouterData,
) -> Result<RecurringDetails, Error> {
let shopper_reference = match item.get_connector_customer_id() {
Ok(connector_customer_id) => Some(connector_customer_id),
Err(_) => {
let customer_id = item.get_customer_id()?;
Some(format!(
"{}_{}",
item.merchant_id.get_string_repr(),
customer_id.get_string_repr()
))
}
};
match (item.request.setup_future_usage, item.request.off_session) {
(Some(storage_enums::FutureUsage::OffSession), _) => {
let store_payment_method = item.request.is_mandate_payment();
Ok((
Some(AdyenRecurringModel::UnscheduledCardOnFile),
Some(store_payment_method),
shopper_reference,
))
}
(_, Some(true)) => Ok((
Some(AdyenRecurringModel::UnscheduledCardOnFile),
None,
shopper_reference,
)),
_ => Ok((None, None, None)),
}
}
fn get_browser_info(item: &PaymentsAuthorizeRouterData) -> Result<Option<AdyenBrowserInfo>, Error> {
if item.auth_type == storage_enums::AuthenticationType::ThreeDs
|| item.payment_method == storage_enums::PaymentMethod::Card
|| item.payment_method == storage_enums::PaymentMethod::BankRedirect
|| item.request.payment_method_type == Some(storage_enums::PaymentMethodType::GoPay)
|| item.request.payment_method_type == Some(storage_enums::PaymentMethodType::GooglePay)
{
let info = item.request.get_browser_info()?;
Ok(Some(AdyenBrowserInfo {
accept_header: info.get_accept_header()?,
language: info.get_language()?,
screen_height: info.get_screen_height()?,
screen_width: info.get_screen_width()?,
color_depth: info.get_color_depth()?,
user_agent: info.get_user_agent()?,
time_zone_offset: info.get_time_zone()?,
java_enabled: info.get_java_enabled()?,
}))
} else {
Ok(None)
}
}
fn get_additional_data(item: &PaymentsAuthorizeRouterData) -> Option<AdditionalData> {
let (authorisation_type, manual_capture) = match item.request.capture_method {
Some(storage_enums::CaptureMethod::Manual) | Some(enums::CaptureMethod::ManualMultiple) => {
(Some(AuthType::PreAuth), Some("true".to_string()))
}
_ => (None, None),
};
let riskdata = item.request.metadata.clone().and_then(get_risk_data);
let execute_three_d = if matches!(item.auth_type, storage_enums::AuthenticationType::ThreeDs) {
Some("true".to_string())
} else {
Some("false".to_string())
};
Some(AdditionalData {
authorisation_type,
manual_capture,
execute_three_d,
network_tx_reference: None,
recurring_detail_reference: None,
recurring_shopper_reference: None,
recurring_processing_model: None,
riskdata,
..AdditionalData::default()
})
}
fn get_channel_type(pm_type: Option<storage_enums::PaymentMethodType>) -> Option<Channel> {
pm_type.as_ref().and_then(|pmt| match pmt {
storage_enums::PaymentMethodType::GoPay | storage_enums::PaymentMethodType::Vipps => {
Some(Channel::Web)
}
_ => None,
})
}
fn get_amount_data(item: &AdyenRouterData<&PaymentsAuthorizeRouterData>) -> Amount {
Amount {
currency: item.router_data.request.currency,
value: item.amount.to_owned(),
}
}
pub fn get_address_info(
address: Option<&hyperswitch_domain_models::address::Address>,
) -> Option<Result<Address, error_stack::Report<errors::ConnectorError>>> {
address.and_then(|add| {
add.address.as_ref().map(
|a| -> Result<Address, error_stack::Report<errors::ConnectorError>> {
Ok(Address {
city: a.get_city()?.to_owned(),
country: a.get_country()?.to_owned(),
house_number_or_name: a.get_line1()?.to_owned(),
postal_code: a.get_zip()?.to_owned(),
state_or_province: a.state.clone(),
street: a.get_optional_line2().to_owned(),
})
},
)
})
}
fn get_line_items(item: &AdyenRouterData<&PaymentsAuthorizeRouterData>) -> Vec<LineItem> {
let order_details = item.router_data.request.order_details.clone();
match order_details {
Some(od) => od
.iter()
.enumerate()
.map(|(i, data)| LineItem {
amount_including_tax: Some(data.amount),
amount_excluding_tax: Some(data.amount),
description: Some(data.product_name.clone()),
id: Some(format!("Items #{i}")),
tax_amount: None,
quantity: Some(data.quantity),
})
.collect(),
None => {
let line_item = LineItem {
amount_including_tax: Some(item.amount.to_owned()),
amount_excluding_tax: Some(item.amount.to_owned()),
description: item.router_data.description.clone(),
id: Some(String::from("Items #1")),
tax_amount: None,
quantity: Some(1),
};
vec![line_item]
}
}
}
fn get_telephone_number(item: &PaymentsAuthorizeRouterData) -> Option<Secret<String>> {
let phone = item
.get_optional_billing()
.and_then(|billing| billing.phone.as_ref());
phone.as_ref().and_then(|phone| {
phone.number.as_ref().and_then(|number| {
phone
.country_code
.as_ref()
.map(|cc| Secret::new(format!("{}{}", cc, number.peek())))
})
})
}
fn get_shopper_name(
address: Option<&hyperswitch_domain_models::address::Address>,
) -> Option<ShopperName> {
let billing = address.and_then(|billing| billing.address.as_ref());
Some(ShopperName {
first_name: billing.and_then(|a| a.first_name.clone()),
last_name: billing.and_then(|a| a.last_name.clone()),
})
}
fn get_country_code(
address: Option<&hyperswitch_domain_models::address::Address>,
) -> Option<storage_enums::CountryAlpha2> {
address.and_then(|billing| billing.address.as_ref().and_then(|address| address.country))
}
fn get_social_security_number(voucher_data: &VoucherData) -> Option<Secret<String>> {
match voucher_data {
VoucherData::Boleto(boleto_data) => boleto_data.social_security_number.clone(),
VoucherData::Alfamart { .. }
| VoucherData::Indomaret { .. }
| VoucherData::Efecty
| VoucherData::PagoEfectivo
| VoucherData::RedCompra
| VoucherData::Oxxo
| VoucherData::RedPagos
| VoucherData::SevenEleven { .. }
| VoucherData::Lawson { .. }
| VoucherData::MiniStop { .. }
| VoucherData::FamilyMart { .. }
| VoucherData::Seicomart { .. }
| VoucherData::PayEasy { .. } => None,
}
}
fn build_shopper_reference(item: &PaymentsAuthorizeRouterData) -> Option<String> {
match item.get_connector_customer_id() {
Ok(connector_customer_id) => Some(connector_customer_id),
Err(_) => match item.get_customer_id() {
Ok(customer_id) => Some(format!(
"{}_{}",
item.merchant_id.get_string_repr(),
customer_id.get_string_repr()
)),
Err(_) => None,
},
}
}
impl TryFrom<(&BankDebitData, &PaymentsAuthorizeRouterData)> for AdyenPaymentMethod<'_> {
type Error = Error;
fn try_from(
(bank_debit_data, item): (&BankDebitData, &PaymentsAuthorizeRouterData),
) -> Result<Self, Self::Error> {
match bank_debit_data {
BankDebitData::AchBankDebit {
account_number,
routing_number,
..
} => Ok(AdyenPaymentMethod::AchDirectDebit(Box::new(
AchDirectDebitData {
bank_account_number: account_number.clone(),
bank_location_id: routing_number.clone(),
owner_name: item.get_billing_full_name()?,
},
))),
BankDebitData::SepaBankDebit { iban, .. } => Ok(AdyenPaymentMethod::SepaDirectDebit(
Box::new(SepaDirectDebitData {
owner_name: item.get_billing_full_name()?,
iban_number: iban.clone(),
}),
)),
BankDebitData::BacsBankDebit {
account_number,
sort_code,
..
} => {
let testing_data = item
.request
.get_connector_testing_data()
.map(AdyenTestingData::try_from)
.transpose()?;
let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name);
Ok(AdyenPaymentMethod::BacsDirectDebit(Box::new(
BacsDirectDebitData {
bank_account_number: account_number.clone(),
bank_location_id: sort_code.clone(),
holder_name: test_holder_name.unwrap_or(item.get_billing_full_name()?),
},
)))
}
BankDebitData::BecsBankDebit { .. } => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
)
.into()),
}
}
}
impl TryFrom<(&VoucherData, &PaymentsAuthorizeRouterData)> for AdyenPaymentMethod<'_> {
type Error = Error;
fn try_from(
(voucher_data, item): (&VoucherData, &PaymentsAuthorizeRouterData),
) -> Result<Self, Self::Error> {
match voucher_data {
VoucherData::Boleto { .. } => Ok(AdyenPaymentMethod::BoletoBancario),
VoucherData::Alfamart(_) => Ok(AdyenPaymentMethod::Alfamart(Box::new(
DokuBankData::try_from(item)?,
))),
VoucherData::Indomaret(_) => Ok(AdyenPaymentMethod::Indomaret(Box::new(
DokuBankData::try_from(item)?,
))),
VoucherData::Oxxo => Ok(AdyenPaymentMethod::Oxxo),
VoucherData::SevenEleven(_) => Ok(AdyenPaymentMethod::SevenEleven(Box::new(
JCSVoucherData::try_from(item)?,
))),
VoucherData::Lawson(_)
| VoucherData::MiniStop(_)
| VoucherData::FamilyMart(_)
| VoucherData::Seicomart(_)
| VoucherData::PayEasy(_) => Ok(AdyenPaymentMethod::JapaneseConvenienceStores(
Box::new(JCSVoucherData::try_from(item)?),
)),
VoucherData::Efecty
| VoucherData::PagoEfectivo
| VoucherData::RedCompra
| VoucherData::RedPagos => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
)
.into()),
}
}
}
impl TryFrom<&GiftCardData> for AdyenPaymentMethod<'_> {
type Error = Error;
fn try_from(gift_card_data: &GiftCardData) -> Result<Self, Self::Error> {
match gift_card_data {
GiftCardData::PaySafeCard {} => Ok(AdyenPaymentMethod::PaySafeCard),
GiftCardData::Givex(givex_data) => {
let gift_card_pm = AdyenGiftCardData {
brand: GiftCardBrand::Givex,
number: givex_data.number.clone(),
cvc: givex_data.cvc.clone(),
};
Ok(AdyenPaymentMethod::AdyenGiftCard(Box::new(gift_card_pm)))
}
GiftCardData::BhnCardNetwork(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
)
.into()),
}
}
}
fn get_adyen_card_network(card_network: common_enums::CardNetwork) -> Option<CardBrand> {
match card_network {
common_enums::CardNetwork::Visa => Some(CardBrand::Visa),
common_enums::CardNetwork::Mastercard => Some(CardBrand::MC),
common_enums::CardNetwork::CartesBancaires => Some(CardBrand::Cartebancaire),
common_enums::CardNetwork::AmericanExpress => Some(CardBrand::Amex),
common_enums::CardNetwork::JCB => Some(CardBrand::Jcb),
common_enums::CardNetwork::DinersClub => Some(CardBrand::Diners),
common_enums::CardNetwork::Discover => Some(CardBrand::Discover),
common_enums::CardNetwork::UnionPay => Some(CardBrand::Cup),
common_enums::CardNetwork::RuPay => Some(CardBrand::Rupay),
common_enums::CardNetwork::Maestro => Some(CardBrand::Maestro),
common_enums::CardNetwork::Star => Some(CardBrand::Star),
common_enums::CardNetwork::Accel => Some(CardBrand::Accel),
common_enums::CardNetwork::Pulse => Some(CardBrand::Pulse),
common_enums::CardNetwork::Nyce => Some(CardBrand::Nyce),
common_enums::CardNetwork::Interac => None,
}
}
impl TryFrom<(&Card, Option<Secret<String>>)> for AdyenPaymentMethod<'_> {
type Error = Error;
fn try_from(
(card, card_holder_name): (&Card, Option<Secret<String>>),
) -> Result<Self, Self::Error> {
let adyen_card = AdyenCard {
number: card.card_number.clone(),
expiry_month: card.card_exp_month.clone(),
expiry_year: card.get_expiry_year_4_digit(),
cvc: Some(card.card_cvc.clone()),
holder_name: card_holder_name,
brand: card.card_network.clone().and_then(get_adyen_card_network),
network_payment_reference: None,
};
Ok(AdyenPaymentMethod::AdyenCard(Box::new(adyen_card)))
}
}
impl TryFrom<&storage_enums::PaymentMethodType> for PaymentType {
type Error = Error;
fn try_from(item: &storage_enums::PaymentMethodType) -> Result<Self, Self::Error> {
match item {
storage_enums::PaymentMethodType::Credit
| storage_enums::PaymentMethodType::Debit
| storage_enums::PaymentMethodType::Klarna
| storage_enums::PaymentMethodType::BancontactCard
| storage_enums::PaymentMethodType::Blik
| storage_enums::PaymentMethodType::Eps
| storage_enums::PaymentMethodType::Ideal
| storage_enums::PaymentMethodType::OnlineBankingCzechRepublic
| storage_enums::PaymentMethodType::OnlineBankingFinland
| storage_enums::PaymentMethodType::OnlineBankingPoland
| storage_enums::PaymentMethodType::OnlineBankingSlovakia
| storage_enums::PaymentMethodType::Trustly
| storage_enums::PaymentMethodType::GooglePay
| storage_enums::PaymentMethodType::AliPay
| storage_enums::PaymentMethodType::ApplePay
| storage_enums::PaymentMethodType::AliPayHk
| storage_enums::PaymentMethodType::MbWay
| storage_enums::PaymentMethodType::MobilePay
| storage_enums::PaymentMethodType::WeChatPay
| storage_enums::PaymentMethodType::SamsungPay
| storage_enums::PaymentMethodType::Affirm
| storage_enums::PaymentMethodType::AfterpayClearpay
| storage_enums::PaymentMethodType::PayBright
| storage_enums::PaymentMethodType::Walley => Ok(Self::Scheme),
storage_enums::PaymentMethodType::Sepa => Ok(Self::SepaDirectDebit),
storage_enums::PaymentMethodType::Bacs => Ok(Self::BacsDirectDebit),
storage_enums::PaymentMethodType::Ach => Ok(Self::AchDirectDebit),
storage_enums::PaymentMethodType::Paypal => Ok(Self::Paypal),
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
))?,
}
}
}
impl TryFrom<&utils::CardIssuer> for CardBrand {
type Error = Error;
fn try_from(card_issuer: &utils::CardIssuer) -> Result<Self, Self::Error> {
match card_issuer {
utils::CardIssuer::AmericanExpress => Ok(Self::Amex),
utils::CardIssuer::Master => Ok(Self::MC),
utils::CardIssuer::Visa => Ok(Self::Visa),
utils::CardIssuer::Maestro => Ok(Self::Maestro),
utils::CardIssuer::Discover => Ok(Self::Discover),
utils::CardIssuer::DinersClub => Ok(Self::Diners),
utils::CardIssuer::JCB => Ok(Self::Jcb),
utils::CardIssuer::CarteBlanche => Ok(Self::Cartebancaire),
utils::CardIssuer::CartesBancaires => Ok(Self::Cartebancaire),
utils::CardIssuer::UnionPay => Ok(Self::Cup),
}
}
}
impl TryFrom<(&WalletData, &PaymentsAuthorizeRouterData)> for AdyenPaymentMethod<'_> {
type Error = Error;
fn try_from(value: (&WalletData, &PaymentsAuthorizeRouterData)) -> Result<Self, Self::Error> {
let (wallet_data, item) = value;
match wallet_data {
WalletData::GooglePay(data) => {
let gpay_data = AdyenGPay {
google_pay_token: Secret::new(
data.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "gpay wallet_token",
})?
.to_owned(),
),
};
Ok(AdyenPaymentMethod::Gpay(Box::new(gpay_data)))
}
WalletData::ApplePay(data) => {
if let Some(PaymentMethodToken::ApplePayDecrypt(apple_pay_decrypte)) =
item.payment_method_token.clone()
{
let expiry_year_4_digit = apple_pay_decrypte.get_four_digit_expiry_year();
let exp_month = apple_pay_decrypte.get_expiry_month().change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_month",
},
)?;
let apple_pay_decrypted_data = AdyenApplePayDecryptData {
number: apple_pay_decrypte.application_primary_account_number,
expiry_month: exp_month,
expiry_year: expiry_year_4_digit,
brand: data.payment_method.network.clone(),
payment_type: PaymentType::Scheme,
};
Ok(AdyenPaymentMethod::ApplePayDecrypt(Box::new(
apple_pay_decrypted_data,
)))
} else {
let apple_pay_encrypted_data = data
.payment_data
.get_encrypted_apple_pay_payment_data_mandatory()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay encrypted data",
})?;
let apple_pay_data = AdyenApplePay {
apple_pay_token: Secret::new(apple_pay_encrypted_data.to_string()),
};
Ok(AdyenPaymentMethod::ApplePay(Box::new(apple_pay_data)))
}
}
WalletData::PaypalRedirect(_) => Ok(AdyenPaymentMethod::AdyenPaypal),
WalletData::AliPayRedirect(_) => Ok(AdyenPaymentMethod::AliPay),
WalletData::AliPayHkRedirect(_) => Ok(AdyenPaymentMethod::AliPayHk),
WalletData::GoPayRedirect(_) => {
let go_pay_data = GoPayData {};
Ok(AdyenPaymentMethod::GoPay(Box::new(go_pay_data)))
}
WalletData::KakaoPayRedirect(_) => {
let kakao_pay_data = KakaoPayData {};
Ok(AdyenPaymentMethod::Kakaopay(Box::new(kakao_pay_data)))
}
WalletData::GcashRedirect(_) => {
let gcash_data = GcashData {};
Ok(AdyenPaymentMethod::Gcash(Box::new(gcash_data)))
}
WalletData::MomoRedirect(_) => {
let momo_data = MomoData {};
Ok(AdyenPaymentMethod::Momo(Box::new(momo_data)))
}
WalletData::TouchNGoRedirect(_) => {
let touch_n_go_data = TouchNGoData {};
Ok(AdyenPaymentMethod::TouchNGo(Box::new(touch_n_go_data)))
}
WalletData::MbWayRedirect(_) => {
let phone_details = item.get_billing_phone()?;
let mbway_data = MbwayData {
telephone_number: phone_details.get_number_with_country_code()?,
};
Ok(AdyenPaymentMethod::Mbway(Box::new(mbway_data)))
}
WalletData::MobilePayRedirect(_) => Ok(AdyenPaymentMethod::MobilePay),
WalletData::WeChatPayRedirect(_) => Ok(AdyenPaymentMethod::WeChatPayWeb),
WalletData::SamsungPay(samsung_data) => {
let data = SamsungPayPmData {
samsung_pay_token: samsung_data.payment_credential.token_data.data.to_owned(),
};
Ok(AdyenPaymentMethod::SamsungPay(Box::new(data)))
}
WalletData::Paze(_) => match item.payment_method_token.clone() {
Some(PaymentMethodToken::PazeDecrypt(paze_decrypted_data)) => {
let data = AdyenPazeData {
number: paze_decrypted_data.token.payment_token,
expiry_month: paze_decrypted_data.token.token_expiration_month,
expiry_year: paze_decrypted_data.token.token_expiration_year,
cvc: None,
holder_name: paze_decrypted_data
.billing_address
.name
.or(item.get_optional_billing_full_name()),
brand: Some(paze_decrypted_data.payment_card_network.clone())
.and_then(get_adyen_card_network),
network_payment_reference: None,
};
Ok(AdyenPaymentMethod::AdyenPaze(Box::new(data)))
}
_ => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Cybersource"),
)
.into()),
},
WalletData::TwintRedirect { .. } => Ok(AdyenPaymentMethod::Twint),
WalletData::VippsRedirect { .. } => Ok(AdyenPaymentMethod::Vipps),
WalletData::DanaRedirect { .. } => Ok(AdyenPaymentMethod::Dana),
WalletData::SwishQr(_) => Ok(AdyenPaymentMethod::Swish),
WalletData::AliPayQr(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::BluecodeRedirect {}
| WalletData::AmazonPay(_)
| WalletData::PaypalSdk(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
)
.into()),
}
}
}
pub fn check_required_field<'a, T>(
field: &'a Option<T>,
message: &'static str,
) -> Result<&'a T, errors::ConnectorError> {
field
.as_ref()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: message,
})
}
impl
TryFrom<(
&PayLaterData,
&Option<storage_enums::CountryAlpha2>,
&Option<Email>,
&Option<String>,
&Option<ShopperName>,
&Option<Secret<String>>,
&Option<Address>,
&Option<Address>,
)> for AdyenPaymentMethod<'_>
{
type Error = Error;
fn try_from(
value: (
&PayLaterData,
&Option<storage_enums::CountryAlpha2>,
&Option<Email>,
&Option<String>,
&Option<ShopperName>,
&Option<Secret<String>>,
&Option<Address>,
&Option<Address>,
),
) -> Result<Self, Self::Error> {
let (
pay_later_data,
country_code,
shopper_email,
shopper_reference,
shopper_name,
telephone_number,
billing_address,
delivery_address,
) = value;
match pay_later_data {
PayLaterData::KlarnaRedirect { .. } => {
check_required_field(shopper_email, "email")?;
check_required_field(shopper_reference, "customer_id")?;
check_required_field(country_code, "billing.country")?;
Ok(AdyenPaymentMethod::AdyenKlarna)
}
PayLaterData::AffirmRedirect { .. } => {
check_required_field(shopper_email, "email")?;
check_required_field(shopper_name, "billing.first_name, billing.last_name")?;
check_required_field(telephone_number, "billing.phone")?;
check_required_field(billing_address, "billing")?;
Ok(AdyenPaymentMethod::AdyenAffirm)
}
PayLaterData::AfterpayClearpayRedirect { .. } => {
check_required_field(shopper_email, "email")?;
check_required_field(shopper_name, "billing.first_name, billing.last_name")?;
check_required_field(delivery_address, "shipping")?;
check_required_field(billing_address, "billing")?;
if let Some(country) = country_code {
match country {
storage_enums::CountryAlpha2::IT
| storage_enums::CountryAlpha2::FR
| storage_enums::CountryAlpha2::ES
| storage_enums::CountryAlpha2::GB => Ok(AdyenPaymentMethod::ClearPay),
_ => Ok(AdyenPaymentMethod::AfterPay),
}
} else {
Err(errors::ConnectorError::MissingRequiredField {
field_name: "country",
})?
}
}
PayLaterData::PayBrightRedirect { .. } => {
check_required_field(shopper_name, "billing.first_name, billing.last_name")?;
check_required_field(telephone_number, "billing.phone")?;
check_required_field(shopper_email, "email")?;
check_required_field(billing_address, "billing")?;
check_required_field(delivery_address, "shipping")?;
check_required_field(country_code, "billing.country")?;
Ok(AdyenPaymentMethod::PayBright)
}
PayLaterData::WalleyRedirect { .. } => {
//[TODO: Line items specific sub-fields are mandatory]
check_required_field(telephone_number, "billing.phone")?;
check_required_field(shopper_email, "email")?;
Ok(AdyenPaymentMethod::Walley)
}
PayLaterData::AlmaRedirect { .. } => {
check_required_field(telephone_number, "billing.phone")?;
check_required_field(shopper_email, "email")?;
check_required_field(billing_address, "billing")?;
check_required_field(delivery_address, "shipping")?;
Ok(AdyenPaymentMethod::AlmaPayLater)
}
PayLaterData::AtomeRedirect { .. } => {
check_required_field(shopper_email, "email")?;
check_required_field(shopper_name, "billing.first_name, billing.last_name")?;
check_required_field(telephone_number, "billing.phone")?;
check_required_field(billing_address, "billing")?;
Ok(AdyenPaymentMethod::Atome)
}
PayLaterData::KlarnaSdk { .. }
| PayLaterData::BreadpayRedirect {}
| PayLaterData::FlexitiRedirect {} => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Adyen"),
)
.into()),
}
}
}
impl TryFrom<(&BankRedirectData, &PaymentsAuthorizeRouterData)> for AdyenPaymentMethod<'_> {
type Error = Error;
fn try_from(
(bank_redirect_data, item): (&BankRedirectData, &PaymentsAuthorizeRouterData),
) -> Result<Self, Self::Error> {
match bank_redirect_data {
BankRedirectData::BancontactCard {
card_number,
card_exp_month,
card_exp_year,
..
} => {
let testing_data = item
.request
.get_connector_testing_data()
.map(AdyenTestingData::try_from)
.transpose()?;
let test_holder_name = testing_data.and_then(|test_data| test_data.holder_name);
Ok(AdyenPaymentMethod::BancontactCard(Box::new(AdyenCard {
brand: Some(CardBrand::Bcmc),
number: card_number
.as_ref()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "bancontact_card.card_number",
})?
.clone(),
expiry_month: card_exp_month
.as_ref()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "bancontact_card.card_exp_month",
})?
.clone(),
expiry_year: card_exp_year
.as_ref()
.ok_or(errors::ConnectorError::MissingRequiredField {
field_name: "bancontact_card.card_exp_year",
})?
.clone(),
holder_name: test_holder_name.or(Some(item.get_billing_full_name()?)),
cvc: None,
network_payment_reference: None,
})))
}
BankRedirectData::Bizum { .. } => Ok(AdyenPaymentMethod::Bizum),
BankRedirectData::Blik { blik_code } => {
Ok(AdyenPaymentMethod::Blik(Box::new(BlikRedirectionData {
blik_code: Secret::new(blik_code.clone().ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "blik_code",
},
)?),
})))
}
BankRedirectData::Eps { bank_name, .. } => Ok(AdyenPaymentMethod::Eps(Box::new(
BankRedirectionWithIssuer {
issuer: Some(
AdyenTestBankNames::try_from(&bank_name.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "eps.bank_name",
},
)?)?
.0,
),
},
))),
BankRedirectData::Ideal { .. } => Ok(AdyenPaymentMethod::Ideal),
BankRedirectData::OnlineBankingCzechRepublic { issuer } => {
Ok(AdyenPaymentMethod::OnlineBankingCzechRepublic(Box::new(
OnlineBankingCzechRepublicData {
issuer: OnlineBankingCzechRepublicBanks::try_from(issuer)?,
},
)))
}
BankRedirectData::OnlineBankingFinland { .. } => {
Ok(AdyenPaymentMethod::OnlineBankingFinland)
}
BankRedirectData::OnlineBankingPoland { issuer } => Ok(
AdyenPaymentMethod::OnlineBankingPoland(Box::new(OnlineBankingPolandData {
issuer: OnlineBankingPolandBanks::try_from(issuer)?,
})),
),
BankRedirectData::OnlineBankingSlovakia { issuer } => Ok(
AdyenPaymentMethod::OnlineBankingSlovakia(Box::new(OnlineBankingSlovakiaData {
issuer: OnlineBankingSlovakiaBanks::try_from(issuer)?,
})),
),
BankRedirectData::OnlineBankingFpx { issuer } => Ok(
AdyenPaymentMethod::OnlineBankingFpx(Box::new(OnlineBankingFpxData {
issuer: OnlineBankingFpxIssuer::try_from(issuer)?,
})),
),
BankRedirectData::OnlineBankingThailand { issuer } => Ok(
AdyenPaymentMethod::OnlineBankingThailand(Box::new(OnlineBankingThailandData {
issuer: OnlineBankingThailandIssuer::try_from(issuer)?,
})),
),
BankRedirectData::OpenBankingUk { issuer, .. } => Ok(
AdyenPaymentMethod::OpenBankingUK(Box::new(OpenBankingUKData {
issuer: match issuer {
Some(bank_name) => Some(OpenBankingUKIssuer::try_from(bank_name)?),
|
crates/hyperswitch_connectors/src/connectors/adyen/transformers.rs#chunk2
|
hyperswitch_connectors
|
chunk
| null | null | null | 8,192
| null | null | null | null | null | null | null |
// Struct: RefundRequest
// File: crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RefundRequest
|
crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RefundRequest
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Function: reopen_calculate_workflow_on_payment_failure
// File: crates/router/src/core/revenue_recovery/types.rs
// Module: router
// Documentation: Reopen calculate workflow when payment fails
pub fn reopen_calculate_workflow_on_payment_failure(
state: &SessionState,
process: &storage::ProcessTracker,
profile: &domain::Profile,
merchant_context: domain::MerchantContext,
payment_intent: &PaymentIntent,
revenue_recovery_payment_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
latest_attempt_id: &id_type::GlobalAttemptId,
) -> RecoveryResult<()>
|
crates/router/src/core/revenue_recovery/types.rs
|
router
|
function_signature
| null | null | null | 128
|
reopen_calculate_workflow_on_payment_failure
| null | null | null | null | null | null |
// Function: setup
// File: crates/router_env/src/logger/setup.rs
// Module: router_env
pub fn setup(
config: &config::Log,
service_name: &str,
crates_to_filter: impl AsRef<[&'static str]>,
) -> error_stack::Result<TelemetryGuard, ConfigError>
|
crates/router_env/src/logger/setup.rs
|
router_env
|
function_signature
| null | null | null | 70
|
setup
| null | null | null | null | null | null |
// Struct: ExchangeRates
// File: crates/currency_conversion/src/types.rs
// Module: currency_conversion
// Implementations: 1
pub struct ExchangeRates
|
crates/currency_conversion/src/types.rs
|
currency_conversion
|
struct_definition
|
ExchangeRates
| 1
|
[] | 34
| null | null | null | null | null | null | null |
// Function: new
// File: crates/api_models/src/routing.rs
// Module: api_models
pub fn new(
profile_id: common_utils::id_type::ProfileId,
euclid_algorithm_id: common_utils::id_type::RoutingId,
decision_engine_algorithm_id: String,
is_active_rule: bool,
) -> Self
|
crates/api_models/src/routing.rs
|
api_models
|
function_signature
| null | null | null | 73
|
new
| null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/ebanx.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 1
pub mod transformers;
use api_models::webhooks::{IncomingWebhookEvent, ObjectReferenceId};
#[cfg(feature = "payouts")]
use common_utils::request::RequestContent;
#[cfg(feature = "payouts")]
use common_utils::request::{Method, Request, RequestBuilder};
#[cfg(feature = "payouts")]
use common_utils::types::{AmountConvertor, FloatMajorUnit, FloatMajorUnitForConnector};
use common_utils::{errors::CustomResult, ext_traits::BytesExt};
use error_stack::{report, ResultExt};
#[cfg(feature = "payouts")]
use hyperswitch_domain_models::{
router_data::RouterData,
router_flow_types::{PoCancel, PoCreate, PoEligibility, PoFulfill, PoQuote, PoRecipient},
types::{PayoutsData, PayoutsResponseData, PayoutsRouterData},
};
use hyperswitch_domain_models::{
router_data::{AccessToken, ErrorResponse},
router_flow_types::{
AccessTokenAuth, Authorize, Capture, Execute, PSync, PaymentMethodToken, RSync, Session,
SetupMandate, Void,
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentsResponseData, RefundsResponseData, SupportedPaymentMethods,
},
};
#[cfg(feature = "payouts")]
use hyperswitch_interfaces::types::{PayoutCancelType, PayoutCreateType, PayoutFulfillType};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors::ConnectorError,
events::connector_api_logs::ConnectorEvent,
types::Response,
webhooks::{IncomingWebhook, IncomingWebhookRequestDetails},
};
#[cfg(feature = "payouts")]
use masking::Maskable;
#[cfg(feature = "payouts")]
use router_env::{instrument, tracing};
use transformers as ebanx;
#[cfg(feature = "payouts")]
use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount};
#[derive(Clone)]
pub struct Ebanx {
#[cfg(feature = "payouts")]
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
impl Ebanx {
pub fn new() -> &'static Self {
&Self {
#[cfg(feature = "payouts")]
amount_converter: &FloatMajorUnitForConnector,
}
}
}
impl api::Payment for Ebanx {}
impl api::PaymentSession for Ebanx {}
impl api::ConnectorAccessToken for Ebanx {}
impl api::MandateSetup for Ebanx {}
impl api::PaymentAuthorize for Ebanx {}
impl api::PaymentSync for Ebanx {}
impl api::PaymentCapture for Ebanx {}
impl api::PaymentVoid for Ebanx {}
impl api::Refund for Ebanx {}
impl api::RefundExecute for Ebanx {}
impl api::RefundSync for Ebanx {}
impl api::PaymentToken for Ebanx {}
impl api::Payouts for Ebanx {}
#[cfg(feature = "payouts")]
impl api::PayoutCancel for Ebanx {}
#[cfg(feature = "payouts")]
impl api::PayoutCreate for Ebanx {}
#[cfg(feature = "payouts")]
impl api::PayoutEligibility for Ebanx {}
#[cfg(feature = "payouts")]
impl api::PayoutQuote for Ebanx {}
#[cfg(feature = "payouts")]
impl api::PayoutRecipient for Ebanx {}
#[cfg(feature = "payouts")]
impl api::PayoutFulfill for Ebanx {}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Ebanx
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
#[cfg(feature = "payouts")]
fn build_headers(
&self,
_req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let header = vec![(
headers::CONTENT_TYPE.to_string(),
self.common_get_content_type().to_string().into(),
)];
Ok(header)
}
}
impl ConnectorCommon for Ebanx {
fn id(&self) -> &'static str {
"ebanx"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Base
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.ebanx.base_url.as_ref()
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
let response: ebanx::EbanxErrorResponse =
res.response
.parse_struct("EbanxErrorResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.status_code,
message: response.code,
reason: response.message,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoCreate, PayoutsData, PayoutsResponseData> for Ebanx {
fn get_url(
&self,
_req: &PayoutsRouterData<PoCreate>,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!("{}ws/payout/create", connectors.ebanx.base_url))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoCreate>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoCreate>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.source_currency,
)?;
let connector_router_data = ebanx::EbanxRouterData::from((amount, req));
let connector_req = ebanx::EbanxPayoutCreateRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoCreate>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutCreateType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutCreateType::get_headers(self, req, connectors)?)
.set_body(PayoutCreateType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &PayoutsRouterData<PoCreate>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoCreate>, ConnectorError> {
let response: ebanx::EbanxPayoutResponse = res
.response
.parse_struct("EbanxPayoutResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoFulfill, PayoutsData, PayoutsResponseData> for Ebanx {
fn get_url(
&self,
_req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!("{}ws/payout/commit", connectors.ebanx.base_url,))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, connectors)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoFulfill>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let amount = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.source_currency,
)?;
let connector_router_data = ebanx::EbanxRouterData::from((amount, req));
let connector_req = ebanx::EbanxPayoutFulfillRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoFulfill>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&PayoutFulfillType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutFulfillType::get_headers(self, req, connectors)?)
.set_body(PayoutFulfillType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoFulfill>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoFulfill>, ConnectorError> {
let response: ebanx::EbanxFulfillResponse = res
.response
.parse_struct("EbanxFulfillResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoCancel, PayoutsData, PayoutsResponseData> for Ebanx {
fn get_url(
&self,
_req: &PayoutsRouterData<PoCancel>,
connectors: &Connectors,
) -> CustomResult<String, ConnectorError> {
Ok(format!("{}ws/payout/cancel", connectors.ebanx.base_url,))
}
fn get_headers(
&self,
req: &PayoutsRouterData<PoCancel>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
self.build_headers(req, _connectors)
}
fn get_request_body(
&self,
req: &PayoutsRouterData<PoCancel>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, ConnectorError> {
let connector_req = ebanx::EbanxPayoutCancelRequest::try_from(req)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PayoutsRouterData<PoCancel>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Put)
.url(&PayoutCancelType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PayoutCancelType::get_headers(self, req, connectors)?)
.set_body(PayoutCancelType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
#[instrument(skip_all)]
fn handle_response(
&self,
data: &PayoutsRouterData<PoCancel>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PayoutsRouterData<PoCancel>, ConnectorError> {
let response: ebanx::EbanxCancelResponse = res
.response
.parse_struct("EbanxCancelResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoQuote, PayoutsData, PayoutsResponseData> for Ebanx {}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoRecipient, PayoutsData, PayoutsResponseData> for Ebanx {}
#[cfg(feature = "payouts")]
impl ConnectorIntegration<PoEligibility, PayoutsData, PayoutsResponseData> for Ebanx {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Ebanx
{
// Not Implemented (R)
}
impl ConnectorValidation for Ebanx {
//TODO: implement functions when support enabled
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Ebanx {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Ebanx {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Ebanx {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Ebanx {}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Ebanx {}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Ebanx {}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Ebanx {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Ebanx {}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Ebanx {}
impl IncomingWebhook for Ebanx {
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
}
static EBANX_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Ebanx",
description: "EBANX payout connector for cross-border disbursements and local currency payouts across Latin America, Africa, and emerging markets",
connector_type: common_enums::HyperswitchConnectorCategory::PayoutProcessor,
integration_status: common_enums::ConnectorIntegrationStatus::Sandbox,
};
impl ConnectorSpecifications for Ebanx {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&EBANX_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
None
}
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::enums::EventClass]> {
None
}
}
|
crates/hyperswitch_connectors/src/connectors/ebanx.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 3,816
| null | null | null | null | null | null | null |
// Struct: DatatransAuthType
// File: crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DatatransAuthType
|
crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
DatatransAuthType
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Function: get_email
// File: crates/router/src/types/domain/user.rs
// Module: router
pub fn get_email(&self) -> pii::Email
|
crates/router/src/types/domain/user.rs
|
router
|
function_signature
| null | null | null | 33
|
get_email
| null | null | null | null | null | null |
// Struct: Event
// File: crates/diesel_models/src/events.rs
// Module: diesel_models
// Implementations: 0
pub struct Event
|
crates/diesel_models/src/events.rs
|
diesel_models
|
struct_definition
|
Event
| 0
|
[] | 32
| null | null | null | null | null | null | null |
// Struct: SubmitEvidenceRequestData
// File: crates/hyperswitch_domain_models/src/router_request_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct SubmitEvidenceRequestData
|
crates/hyperswitch_domain_models/src/router_request_types.rs
|
hyperswitch_domain_models
|
struct_definition
|
SubmitEvidenceRequestData
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// File: crates/router/src/types/api/routing.rs
// Module: router
// Public structs: 3
pub use api_models::{
enums as api_enums,
routing::{
ConnectorVolumeSplit, RoutableChoiceKind, RoutableConnectorChoice, RoutingAlgorithmKind,
RoutingAlgorithmRef, RoutingConfigRequest, RoutingDictionary, RoutingDictionaryRecord,
StaticRoutingAlgorithm, StraightThroughAlgorithm,
},
};
use super::types::api as api_oss;
pub struct SessionRoutingChoice {
pub connector: api_oss::ConnectorData,
pub payment_method_type: api_enums::PaymentMethodType,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct ConnectorVolumeSplitV0 {
pub connector: RoutableConnectorChoice,
pub split: u8,
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "snake_case")]
pub enum RoutingAlgorithmV0 {
Single(Box<RoutableConnectorChoice>),
Priority(Vec<RoutableConnectorChoice>),
VolumeSplit(Vec<ConnectorVolumeSplitV0>),
Custom { timestamp: i64 },
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub struct FrmRoutingAlgorithm {
pub data: String,
#[serde(rename = "type")]
pub algorithm_type: String,
}
|
crates/router/src/types/api/routing.rs
|
router
|
full_file
| null | null | null | 292
| null | null | null | null | null | null | null |
// Function: update_by_user_email
// File: crates/diesel_models/src/query/user.rs
// Module: diesel_models
pub fn update_by_user_email(
conn: &PgPooledConn,
user_email: &pii::Email,
user_update: UserUpdate,
) -> StorageResult<Self>
|
crates/diesel_models/src/query/user.rs
|
diesel_models
|
function_signature
| null | null | null | 65
|
update_by_user_email
| null | null | null | null | null | null |
// Implementation: impl api::PaymentsPreProcessing for for Adyen
// File: crates/hyperswitch_connectors/src/connectors/adyen.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentsPreProcessing for for Adyen
|
crates/hyperswitch_connectors/src/connectors/adyen.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Adyen
|
api::PaymentsPreProcessing for
| 0
| 0
| null | null |
// Struct: DigitalvirgoConsentStatus
// File: crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DigitalvirgoConsentStatus
|
crates/hyperswitch_connectors/src/connectors/digitalvirgo/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
DigitalvirgoConsentStatus
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// Function: construct_mandate_revoke_router_data
// File: crates/router/src/core/mandate/utils.rs
// Module: router
pub fn construct_mandate_revoke_router_data(
state: &SessionState,
merchant_connector_account: helpers::MerchantConnectorAccountType,
merchant_context: &domain::MerchantContext,
mandate: Mandate,
) -> CustomResult<types::MandateRevokeRouterData, errors::ApiErrorResponse>
|
crates/router/src/core/mandate/utils.rs
|
router
|
function_signature
| null | null | null | 96
|
construct_mandate_revoke_router_data
| null | null | null | null | null | null |
// Implementation: impl ConnectorSpecifications for for Fiuu
// File: crates/hyperswitch_connectors/src/connectors/fiuu.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)
impl ConnectorSpecifications for for Fiuu
|
crates/hyperswitch_connectors/src/connectors/fiuu.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 56
| null |
Fiuu
|
ConnectorSpecifications for
| 3
| 0
| null | null |
// Function: payments_redirect_response_with_creds_identifier
// File: crates/router/src/routes/payments.rs
// Module: router
pub fn payments_redirect_response_with_creds_identifier(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
path: web::Path<(
common_utils::id_type::PaymentId,
common_utils::id_type::MerchantId,
String,
String,
)
|
crates/router/src/routes/payments.rs
|
router
|
function_signature
| null | null | null | 93
|
payments_redirect_response_with_creds_identifier
| null | null | null | null | null | null |
// Implementation: impl api::PaymentToken for for Gigadat
// File: crates/hyperswitch_connectors/src/connectors/gigadat.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentToken for for Gigadat
|
crates/hyperswitch_connectors/src/connectors/gigadat.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Gigadat
|
api::PaymentToken for
| 0
| 0
| null | null |
// Function: update_profile_active_algorithm_ref
// File: crates/router/src/core/routing/helpers.rs
// Module: router
pub fn update_profile_active_algorithm_ref(
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
current_business_profile: domain::Profile,
algorithm_id: routing_types::RoutingAlgorithmRef,
transaction_type: &storage::enums::TransactionType,
) -> RouterResult<()>
|
crates/router/src/core/routing/helpers.rs
|
router
|
function_signature
| null | null | null | 101
|
update_profile_active_algorithm_ref
| null | null | null | null | null | null |
// Struct: Error
// File: crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Error
|
crates/hyperswitch_connectors/src/connectors/powertranz/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
Error
| 0
|
[] | 44
| null | null | null | null | null | null | null |
// Struct: NmiWebhookObject
// File: crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NmiWebhookObject
|
crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NmiWebhookObject
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Struct: MerchantIdAndProfileIdAuth
// File: crates/router/src/services/authentication.rs
// Module: router
// Implementations: 0
pub struct MerchantIdAndProfileIdAuth
|
crates/router/src/services/authentication.rs
|
router
|
struct_definition
|
MerchantIdAndProfileIdAuth
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Function: send_recon_request
// File: crates/router/src/core/recon.rs
// Module: router
pub fn send_recon_request(
state: SessionState,
auth_data: authentication::AuthenticationDataWithUser,
) -> RouterResponse<recon_api::ReconStatusResponse>
|
crates/router/src/core/recon.rs
|
router
|
function_signature
| null | null | null | 62
|
send_recon_request
| null | null | null | null | null | null |
// Struct: GoPayRedirection
// File: crates/hyperswitch_domain_models/src/payment_method_data.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct GoPayRedirection
|
crates/hyperswitch_domain_models/src/payment_method_data.rs
|
hyperswitch_domain_models
|
struct_definition
|
GoPayRedirection
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Function: from_transaction_response
// File: crates/hyperswitch_connectors/src/connectors/celero/transformers.rs
// Module: hyperswitch_connectors
pub fn from_transaction_response(response: &CeleroCardResponse, msg: String) -> Self
|
crates/hyperswitch_connectors/src/connectors/celero/transformers.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 55
|
from_transaction_response
| null | null | null | null | null | null |
// Implementation: impl api::PaymentCapture for for Forte
// File: crates/hyperswitch_connectors/src/connectors/forte.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentCapture for for Forte
|
crates/hyperswitch_connectors/src/connectors/forte.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Forte
|
api::PaymentCapture for
| 0
| 0
| null | null |
// Struct: ApplePayCryptogramData
// File: crates/common_types/src/payments.rs
// Module: common_types
// Implementations: 0
// Documentation: This struct represents the cryptogram data for Apple Pay transactions
pub struct ApplePayCryptogramData
|
crates/common_types/src/payments.rs
|
common_types
|
struct_definition
|
ApplePayCryptogramData
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// Function: find_by_customer_id_merchant_id
// File: crates/diesel_models/src/query/payment_method.rs
// Module: diesel_models
pub fn find_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: &common_utils::id_type::CustomerId,
merchant_id: &common_utils::id_type::MerchantId,
limit: Option<i64>,
) -> StorageResult<Vec<Self>>
|
crates/diesel_models/src/query/payment_method.rs
|
diesel_models
|
function_signature
| null | null | null | 92
|
find_by_customer_id_merchant_id
| null | null | null | null | null | null |
// Struct: UasConfirmationRequestData
// File: crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct UasConfirmationRequestData
|
crates/hyperswitch_domain_models/src/router_request_types/unified_authentication_service.rs
|
hyperswitch_domain_models
|
struct_definition
|
UasConfirmationRequestData
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Struct: DDCResponse
// File: crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DDCResponse
|
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
|
hyperswitch_connectors
|
struct_definition
|
DDCResponse
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Struct: SyncIntegrityObject
// File: crates/hyperswitch_domain_models/src/router_request_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct SyncIntegrityObject
|
crates/hyperswitch_domain_models/src/router_request_types.rs
|
hyperswitch_domain_models
|
struct_definition
|
SyncIntegrityObject
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Implementation: impl Responder
// File: crates/router/src/analytics.rs
// Module: router
// Methods: 0 total (0 public)
impl Responder
|
crates/router/src/analytics.rs
|
router
|
impl_block
| null | null | null | 35
| null |
Responder
| null | 0
| 0
| null | null |
// Struct: Opennode
// File: crates/hyperswitch_connectors/src/connectors/opennode.rs
// Module: hyperswitch_connectors
// Implementations: 17
// Traits: api::Payment, api::PaymentSession, api::PaymentToken, api::ConnectorAccessToken, api::MandateSetup, api::PaymentAuthorize, api::PaymentSync, api::PaymentCapture, api::PaymentVoid, api::Refund, api::RefundExecute, api::RefundSync, ConnectorCommon, ConnectorValidation, IncomingWebhook, ConnectorSpecifications
pub struct Opennode
|
crates/hyperswitch_connectors/src/connectors/opennode.rs
|
hyperswitch_connectors
|
struct_definition
|
Opennode
| 17
|
[
"api::Payment",
"api::PaymentSession",
"api::PaymentToken",
"api::ConnectorAccessToken",
"api::MandateSetup",
"api::PaymentAuthorize",
"api::PaymentSync",
"api::PaymentCapture",
"api::PaymentVoid",
"api::Refund",
"api::RefundExecute",
"api::RefundSync",
"ConnectorCommon",
"ConnectorValidation",
"IncomingWebhook",
"ConnectorSpecifications"
] | 124
| null | null | null | null | null | null | null |
// Function: list_payment_methods_core
// File: crates/router/src/core/payment_methods.rs
// Module: router
pub fn list_payment_methods_core(
state: &SessionState,
merchant_context: &domain::MerchantContext,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<payment_methods::CustomerPaymentMethodsListResponse>
|
crates/router/src/core/payment_methods.rs
|
router
|
function_signature
| null | null | null | 73
|
list_payment_methods_core
| null | null | null | null | null | null |
// Implementation: impl api::ConnectorTransactionId for for ConnectorEnum
// File: crates/hyperswitch_interfaces/src/connector_integration_interface.rs
// Module: hyperswitch_interfaces
// Methods: 1 total (0 public)
impl api::ConnectorTransactionId for for ConnectorEnum
|
crates/hyperswitch_interfaces/src/connector_integration_interface.rs
|
hyperswitch_interfaces
|
impl_block
| null | null | null | 57
| null |
ConnectorEnum
|
api::ConnectorTransactionId for
| 1
| 0
| null | null |
// Function: profile_retrieve
// File: crates/router/src/routes/profiles.rs
// Module: router
pub fn profile_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::ProfileId>,
) -> HttpResponse
|
crates/router/src/routes/profiles.rs
|
router
|
function_signature
| null | null | null | 62
|
profile_retrieve
| null | null | null | null | null | null |
// Struct: WisePayoutsWebhookData
// File: crates/hyperswitch_connectors/src/connectors/wise/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct WisePayoutsWebhookData
|
crates/hyperswitch_connectors/src/connectors/wise/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
WisePayoutsWebhookData
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// Function: authorize_postprocessing_steps
// File: crates/router/src/core/payments/flows/authorize_flow.rs
// Module: router
pub fn authorize_postprocessing_steps<F: Clone>(
state: &SessionState,
router_data: &types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>,
confirm: bool,
connector: &api::ConnectorData,
) -> RouterResult<types::RouterData<F, types::PaymentsAuthorizeData, types::PaymentsResponseData>>
|
crates/router/src/core/payments/flows/authorize_flow.rs
|
router
|
function_signature
| null | null | null | 106
|
authorize_postprocessing_steps
| null | null | null | null | null | null |
// Implementation: impl api::Refund for for Coingate
// File: crates/hyperswitch_connectors/src/connectors/coingate.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Refund for for Coingate
|
crates/hyperswitch_connectors/src/connectors/coingate.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Coingate
|
api::Refund for
| 0
| 0
| null | null |
// Implementation: impl ConnectorCommon for for Itaubank
// File: crates/hyperswitch_connectors/src/connectors/itaubank.rs
// Module: hyperswitch_connectors
// Methods: 5 total (0 public)
impl ConnectorCommon for for Itaubank
|
crates/hyperswitch_connectors/src/connectors/itaubank.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Itaubank
|
ConnectorCommon for
| 5
| 0
| null | null |
// Function: handle_unified_connector_service_response_for_payment_repeat
// File: crates/router/src/core/unified_connector_service.rs
// Module: router
pub fn handle_unified_connector_service_response_for_payment_repeat(
response: payments_grpc::PaymentServiceRepeatEverythingResponse,
) -> UnifiedConnectorServiceResult
|
crates/router/src/core/unified_connector_service.rs
|
router
|
function_signature
| null | null | null | 62
|
handle_unified_connector_service_response_for_payment_repeat
| null | null | null | null | null | null |
// Implementation: impl ApiEventMetric for for AuthenticationSyncPostUpdateRequest
// File: crates/api_models/src/authentication.rs
// Module: api_models
// Methods: 1 total (0 public)
impl ApiEventMetric for for AuthenticationSyncPostUpdateRequest
|
crates/api_models/src/authentication.rs
|
api_models
|
impl_block
| null | null | null | 52
| null |
AuthenticationSyncPostUpdateRequest
|
ApiEventMetric for
| 1
| 0
| null | null |
// Function: get_merchant_tax_registration_id
// File: crates/hyperswitch_domain_models/src/merchant_account.rs
// Module: hyperswitch_domain_models
// Documentation: Extract merchant_tax_registration_id from merchant_details
pub fn get_merchant_tax_registration_id(&self) -> Option<Secret<String>>
|
crates/hyperswitch_domain_models/src/merchant_account.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 63
|
get_merchant_tax_registration_id
| null | null | null | null | null | null |
// File: crates/common_utils/src/id_type/api_key.rs
// Module: common_utils
// Public functions: 1
crate::id_type!(
ApiKeyId,
"A type for key_id that can be used for API key IDs"
);
crate::impl_id_type_methods!(ApiKeyId, "key_id");
// This is to display the `ApiKeyId` as ApiKeyId(abcd)
crate::impl_debug_id_type!(ApiKeyId);
crate::impl_try_from_cow_str_id_type!(ApiKeyId, "key_id");
crate::impl_serializable_secret_id_type!(ApiKeyId);
crate::impl_queryable_id_type!(ApiKeyId);
crate::impl_to_sql_from_sql_id_type!(ApiKeyId);
impl ApiKeyId {
/// Generate Api Key Id from prefix
pub fn generate_key_id(prefix: &'static str) -> Self {
Self(crate::generate_ref_id_with_default_length(prefix))
}
}
impl crate::events::ApiEventMetric for ApiKeyId {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::ApiKey {
key_id: self.clone(),
})
}
}
impl crate::events::ApiEventMetric for (super::MerchantId, ApiKeyId) {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::ApiKey {
key_id: self.1.clone(),
})
}
}
impl crate::events::ApiEventMetric for (&super::MerchantId, &ApiKeyId) {
fn get_api_event_type(&self) -> Option<crate::events::ApiEventsType> {
Some(crate::events::ApiEventsType::ApiKey {
key_id: self.1.clone(),
})
}
}
crate::impl_default_id_type!(ApiKeyId, "key");
|
crates/common_utils/src/id_type/api_key.rs
|
common_utils
|
full_file
| null | null | null | 392
| null | null | null | null | null | null | null |
// Function: validate_connectors_in_routing_config
// File: crates/router/src/core/routing/helpers.rs
// Module: router
pub fn validate_connectors_in_routing_config(&self) -> RouterResult<()>
|
crates/router/src/core/routing/helpers.rs
|
router
|
function_signature
| null | null | null | 42
|
validate_connectors_in_routing_config
| null | null | null | null | null | null |
// Struct: MinimalRoleInfo
// File: crates/api_models/src/user_role/role.rs
// Module: api_models
// Implementations: 0
pub struct MinimalRoleInfo
|
crates/api_models/src/user_role/role.rs
|
api_models
|
struct_definition
|
MinimalRoleInfo
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// Struct: RefundResponse
// File: crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RefundResponse
|
crates/hyperswitch_connectors/src/connectors/paysafe/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RefundResponse
| 0
|
[] | 48
| null | null | null | null | null | null | null |
// File: crates/api_models/src/payments/trait_impls.rs
// Module: api_models
#[cfg(feature = "v1")]
use common_enums::enums;
#[cfg(feature = "v1")]
use common_utils::errors;
#[cfg(feature = "v1")]
use crate::payments;
#[cfg(feature = "v1")]
impl crate::ValidateFieldAndGet<payments::PaymentsRequest>
for common_types::primitive_wrappers::RequestExtendedAuthorizationBool
{
fn validate_field_and_get(
&self,
request: &payments::PaymentsRequest,
) -> errors::CustomResult<Self, errors::ValidationError>
where
Self: Sized,
{
match request.capture_method{
Some(enums::CaptureMethod::Automatic)
| Some(enums::CaptureMethod::Scheduled)
| Some(enums::CaptureMethod::SequentialAutomatic)
| None => Err(error_stack::report!(errors::ValidationError::InvalidValue { message: "request_extended_authorization must be sent only if capture method is manual or manual_multiple".to_string() })),
Some(enums::CaptureMethod::Manual)
| Some(enums::CaptureMethod::ManualMultiple) => Ok(*self)
}
}
}
|
crates/api_models/src/payments/trait_impls.rs
|
api_models
|
full_file
| null | null | null | 254
| null | null | null | null | null | null | null |
// Struct: RefundResponse
// File: crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RefundResponse
|
crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RefundResponse
| 0
|
[] | 47
| 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.