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
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
// Struct: PaymentsRequest
// File: crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaymentsRequest
|
crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymentsRequest
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Trait: PayoutsInterface
// File: crates/hyperswitch_domain_models/src/payouts/payouts.rs
// Module: hyperswitch_domain_models
pub trait PayoutsInterface
|
crates/hyperswitch_domain_models/src/payouts/payouts.rs
|
hyperswitch_domain_models
|
trait_definition
| null | null | null | 41
| null | null |
PayoutsInterface
| null | null | null | null |
// Function: get_payapl_webhooks_event
// File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
// Module: hyperswitch_connectors
pub fn get_payapl_webhooks_event(
event: PaypalWebhookEventType,
outcome: Option<OutcomeCode>,
) -> IncomingWebhookEvent
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
function_signature
| null | null | null | 69
|
get_payapl_webhooks_event
| null | null | null | null | null | null |
// Struct: CybersourceAuthSetupRequest
// File: crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CybersourceAuthSetupRequest
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CybersourceAuthSetupRequest
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// Function: server
// File: crates/router/src/compatibility/stripe/app.rs
// Module: router
pub fn server(state: routes::AppState) -> Scope
|
crates/router/src/compatibility/stripe/app.rs
|
router
|
function_signature
| null | null | null | 35
|
server
| null | null | null | null | null | null |
// Implementation: impl webhooks::IncomingWebhook for for Noon
// File: crates/hyperswitch_connectors/src/connectors/noon.rs
// Module: hyperswitch_connectors
// Methods: 6 total (0 public)
impl webhooks::IncomingWebhook for for Noon
|
crates/hyperswitch_connectors/src/connectors/noon.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Noon
|
webhooks::IncomingWebhook for
| 6
| 0
| null | null |
// Function: list_routing_configs
// File: crates/openapi/src/routes/routing.rs
// Module: openapi
pub fn list_routing_configs()
|
crates/openapi/src/routes/routing.rs
|
openapi
|
function_signature
| null | null | null | 31
|
list_routing_configs
| null | null | null | null | null | null |
// Function: update_by_merchant_id_customer_id
// File: crates/diesel_models/src/query/address.rs
// Module: diesel_models
pub fn update_by_merchant_id_customer_id(
conn: &PgPooledConn,
customer_id: &common_utils::id_type::CustomerId,
merchant_id: &common_utils::id_type::MerchantId,
address: AddressUpdateInternal,
) -> StorageResult<Vec<Self>>
|
crates/diesel_models/src/query/address.rs
|
diesel_models
|
function_signature
| null | null | null | 90
|
update_by_merchant_id_customer_id
| null | null | null | null | null | null |
// Struct: CustomerUpdateRequest
// File: crates/api_models/src/customers.rs
// Module: api_models
// Implementations: 2
pub struct CustomerUpdateRequest
|
crates/api_models/src/customers.rs
|
api_models
|
struct_definition
|
CustomerUpdateRequest
| 2
|
[] | 36
| null | null | null | null | null | null | null |
// Struct: FrmMetricsBucketValue
// File: crates/api_models/src/analytics/frm.rs
// Module: api_models
// Implementations: 0
pub struct FrmMetricsBucketValue
|
crates/api_models/src/analytics/frm.rs
|
api_models
|
struct_definition
|
FrmMetricsBucketValue
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Module Structure
// File: crates/masking/src/serde.rs
// Module: masking
// Public exports:
pub use erased_serde::Serialize as ErasedSerialize;
pub use serde::{de, Deserialize, Serialize, Serializer};
|
crates/masking/src/serde.rs
|
masking
|
module_structure
| null | null | null | 48
| null | null | null | null | null | 0
| 2
|
// Function: apple_pay_merchant_registration
// File: crates/router/src/routes/verification.rs
// Module: router
pub fn apple_pay_merchant_registration(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<verifications::ApplepayMerchantVerificationRequest>,
path: web::Path<common_utils::id_type::MerchantId>,
) -> impl Responder
|
crates/router/src/routes/verification.rs
|
router
|
function_signature
| null | null | null | 85
|
apple_pay_merchant_registration
| null | null | null | null | null | null |
// Function: internal_payments_operation_core
// File: crates/router/src/core/payments.rs
// Module: router
pub fn internal_payments_operation_core<F, Req, Op, FData, D>(
state: &SessionState,
req_state: ReqState,
merchant_context: domain::MerchantContext,
profile: &domain::Profile,
operation: Op,
req: Req,
get_tracker_response: operations::GetTrackerResponse<D>,
call_connector_action: CallConnectorAction,
header_payload: HeaderPayload,
) -> RouterResult<(
D,
Req,
Option<u16>,
Option<u128>,
common_types::domain::ConnectorResponseData,
)>
where
F: Send + Clone + Sync,
Req: Send + Sync + Authenticate,
Op: Operation<F, Req, Data = D> + Send + Sync,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
// To create connector flow specific interface data
D: ConstructFlowSpecificData<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>: Feature<F, FData>,
// To construct connector flow specific api
dyn api::Connector:
services::api::ConnectorIntegration<F, FData, router_types::PaymentsResponseData>,
RouterData<F, FData, router_types::PaymentsResponseData>:
hyperswitch_domain_models::router_data::TrackerPostUpdateObjects<F, FData, D>,
// To perform router related operation for PaymentResponse
PaymentResponse: Operation<F, FData, Data = D>,
FData: Send + Sync + Clone,
|
crates/router/src/core/payments.rs
|
router
|
function_signature
| null | null | null | 364
|
internal_payments_operation_core
| null | null | null | null | null | null |
// Function: store_payout_method_data_in_locker
// File: crates/router/src/core/payment_methods/vault.rs
// Module: router
pub fn store_payout_method_data_in_locker(
state: &routes::SessionState,
token_id: Option<String>,
payout_method: &api::PayoutMethodData,
customer_id: Option<id_type::CustomerId>,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<String>
|
crates/router/src/core/payment_methods/vault.rs
|
router
|
function_signature
| null | null | null | 99
|
store_payout_method_data_in_locker
| null | null | null | null | null | null |
// Implementation: impl api::ConnectorAccessToken for for Datatrans
// File: crates/hyperswitch_connectors/src/connectors/datatrans.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::ConnectorAccessToken for for Datatrans
|
crates/hyperswitch_connectors/src/connectors/datatrans.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Datatrans
|
api::ConnectorAccessToken for
| 0
| 0
| null | null |
// Function: payment_method_session_create
// File: crates/openapi/src/routes/payment_method.rs
// Module: openapi
pub fn payment_method_session_create()
|
crates/openapi/src/routes/payment_method.rs
|
openapi
|
function_signature
| null | null | null | 33
|
payment_method_session_create
| null | null | null | null | null | null |
// Struct: StripePayoutResponse
// File: crates/router/src/compatibility/stripe/webhooks.rs
// Module: router
// Implementations: 0
pub struct StripePayoutResponse
|
crates/router/src/compatibility/stripe/webhooks.rs
|
router
|
struct_definition
|
StripePayoutResponse
| 0
|
[] | 41
| null | null | null | null | null | null | null |
// Struct: AddAcceptLanguageHeader
// File: crates/router/src/middleware.rs
// Module: router
// Implementations: 0
// Documentation: Middleware for Adding Accept-Language header based on query params
pub struct AddAcceptLanguageHeader
|
crates/router/src/middleware.rs
|
router
|
struct_definition
|
AddAcceptLanguageHeader
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Function: delete_decision_manager_config
// File: crates/router/src/routes/routing.rs
// Module: router
pub fn delete_decision_manager_config(
state: web::Data<AppState>,
req: HttpRequest,
) -> impl Responder
|
crates/router/src/routes/routing.rs
|
router
|
function_signature
| null | null | null | 50
|
delete_decision_manager_config
| null | null | null | null | null | null |
// Struct: CardResponseObject
// File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CardResponseObject
|
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CardResponseObject
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Function: validate_adyen_charge_refund
// File: crates/router/src/core/utils/refunds_validator.rs
// Module: router
pub fn validate_adyen_charge_refund(
adyen_split_payment_response: &common_types::domain::AdyenSplitData,
adyen_split_refund_request: &common_types::domain::AdyenSplitData,
) -> RouterResult<()>
|
crates/router/src/core/utils/refunds_validator.rs
|
router
|
function_signature
| null | null | null | 81
|
validate_adyen_charge_refund
| null | null | null | null | null | null |
// File: crates/common_enums/src/enums/ui.rs
// Module: common_enums
use std::fmt;
use serde::{de::Visitor, Deserialize, Deserializer, Serialize};
use utoipa::ToSchema;
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "lowercase")]
pub enum ElementPosition {
Left,
#[default]
#[serde(rename = "top left")]
TopLeft,
Top,
#[serde(rename = "top right")]
TopRight,
Right,
#[serde(rename = "bottom right")]
BottomRight,
Bottom,
#[serde(rename = "bottom left")]
BottomLeft,
Center,
}
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq, strum::Display, strum::EnumString, ToSchema)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
pub enum ElementSize {
Variants(SizeVariants),
Percentage(u32),
Pixels(u32),
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum SizeVariants {
#[default]
Cover,
Contain,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum PaymentLinkDetailsLayout {
#[default]
Layout1,
Layout2,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum PaymentLinkSdkLabelType {
#[default]
Above,
Floating,
Never,
}
#[derive(
Clone,
Copy,
Debug,
Default,
Eq,
Hash,
PartialEq,
Serialize,
Deserialize,
strum::Display,
strum::EnumString,
ToSchema,
)]
#[router_derive::diesel_enum(storage_type = "db_enum")]
#[serde(rename_all = "lowercase")]
#[strum(serialize_all = "lowercase")]
pub enum PaymentLinkShowSdkTerms {
Always,
#[default]
Auto,
Never,
}
impl<'de> Deserialize<'de> for ElementSize {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where
D: Deserializer<'de>,
{
struct ElementSizeVisitor;
impl Visitor<'_> for ElementSizeVisitor {
type Value = ElementSize;
fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
formatter.write_str("a string with possible values - contain, cover or values in percentage or pixels. For eg: 48px or 50%")
}
fn visit_str<E>(self, value: &str) -> Result<ElementSize, E>
where
E: serde::de::Error,
{
if let Some(percent) = value.strip_suffix('%') {
percent
.parse::<u32>()
.map(ElementSize::Percentage)
.map_err(E::custom)
} else if let Some(px) = value.strip_suffix("px") {
px.parse::<u32>()
.map(ElementSize::Pixels)
.map_err(E::custom)
} else {
match value {
"cover" => Ok(ElementSize::Variants(SizeVariants::Cover)),
"contain" => Ok(ElementSize::Variants(SizeVariants::Contain)),
_ => Err(E::custom("invalid size variant")),
}
}
}
}
deserializer.deserialize_str(ElementSizeVisitor)
}
}
impl Serialize for ElementSize {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::ser::Serializer,
{
match self {
Self::Variants(variant) => serializer.serialize_str(variant.to_string().as_str()),
Self::Pixels(pixel_count) => {
serializer.serialize_str(format!("{pixel_count}px").as_str())
}
Self::Percentage(pixel_count) => {
serializer.serialize_str(format!("{pixel_count}%").as_str())
}
}
}
}
|
crates/common_enums/src/enums/ui.rs
|
common_enums
|
full_file
| null | null | null | 1,107
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/paytm.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 1
pub mod transformers;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMinorUnit, StringMinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, Response},
webhooks,
};
use lazy_static::lazy_static;
use transformers as paytm;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Paytm {
amount_converter: &'static (dyn AmountConvertor<Output = StringMinorUnit> + Sync),
}
impl Paytm {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
impl api::Payment for Paytm {}
impl api::PaymentSession for Paytm {}
impl api::ConnectorAccessToken for Paytm {}
impl api::MandateSetup for Paytm {}
impl api::PaymentAuthorize for Paytm {}
impl api::PaymentSync for Paytm {}
impl api::PaymentCapture for Paytm {}
impl api::PaymentVoid for Paytm {}
impl api::Refund for Paytm {}
impl api::RefundExecute for Paytm {}
impl api::RefundSync for Paytm {}
impl api::PaymentToken for Paytm {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Paytm
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Paytm
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
self.get_content_type().to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Paytm {
fn id(&self) -> &'static str {
"paytm"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.paytm.base_url.as_ref()
}
fn get_auth_header(
&self,
_auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
// This method is not implemented for Paytm, as it will always call the UCS service which has the logic to create headers.
Err(errors::ConnectorError::NotImplemented("get_auth_header method".to_string()).into())
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: paytm::PaytmErrorResponse =
res.response
.parse_struct("PaytmErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
message: response.message,
reason: response.reason,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Paytm {
fn validate_mandate_payment(
&self,
_pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
match pm_data {
PaymentMethodData::Card(_) => Err(errors::ConnectorError::NotImplemented(
"validate_mandate_payment does not support cards".to_string(),
)
.into()),
_ => Ok(()),
}
}
fn validate_psync_reference_id(
&self,
_data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
Ok(())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Paytm {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Paytm {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Paytm {}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Paytm {
fn get_headers(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = paytm::PaytmRouterData::from((amount, req));
let connector_req = paytm::PaytmPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: paytm::PaytmPaymentsResponse = res
.response
.parse_struct("Paytm PaymentsAuthorizeResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<PSync, PaymentsSyncData, PaymentsResponseData> for Paytm {
fn get_headers(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: paytm::PaytmPaymentsResponse = res
.response
.parse_struct("paytm PaymentsSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Capture, PaymentsCaptureData, PaymentsResponseData> for Paytm {
fn get_headers(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
_req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_request_body method".to_string()).into())
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: paytm::PaytmPaymentsResponse = res
.response
.parse_struct("Paytm PaymentsCaptureResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Void, PaymentsCancelData, PaymentsResponseData> for Paytm {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Paytm {
fn get_headers(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = paytm::PaytmRouterData::from((refund_amount, req));
let connector_req = paytm::PaytmRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: paytm::RefundResponse = res
.response
.parse_struct("paytm RefundResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<RSync, RefundsData, RefundsResponseData> for Paytm {
fn get_headers(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
self.build_headers(req, connectors)
}
fn get_content_type(&self) -> &'static str {
self.common_get_content_type()
}
fn get_url(
&self,
_req: &RefundSyncRouterData,
_connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Err(errors::ConnectorError::NotImplemented("get_url method".to_string()).into())
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: paytm::RefundResponse = res
.response
.parse_struct("paytm RefundSyncResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
#[async_trait::async_trait]
impl webhooks::IncomingWebhook for Paytm {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
lazy_static! {
static ref PAYTM_SUPPORTED_PAYMENT_METHODS: SupportedPaymentMethods = {
let supported_capture_methods = vec![enums::CaptureMethod::Automatic];
let mut paytm_supported_payment_methods = SupportedPaymentMethods::new();
paytm_supported_payment_methods.add(
enums::PaymentMethod::Upi,
enums::PaymentMethodType::UpiCollect,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::NotSupported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
paytm_supported_payment_methods.add(
enums::PaymentMethod::Upi,
enums::PaymentMethodType::UpiIntent,
PaymentMethodDetails{
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::NotSupported,
supported_capture_methods,
specific_features: None,
},
);
paytm_supported_payment_methods
};
static ref PAYTM_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "PAYTM",
description:
"Paytm is an Indian multinational fintech company specializing in digital payments and financial services. Initially known for its mobile wallet, it has expanded to include a payment bank, e-commerce, ticketing, and wealth management services.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static ref PAYTM_SUPPORTED_WEBHOOK_FLOWS: Vec<enums::EventClass> = Vec::new();
}
impl ConnectorSpecifications for Paytm {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&*PAYTM_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*PAYTM_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&*PAYTM_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/paytm.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 4,866
| null | null | null | null | null | null | null |
// File: crates/test_utils/tests/connectors/bluesnap_wh_ui.rs
// Module: test_utils
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct BluesnapSeleniumTest;
impl SeleniumTest for BluesnapSeleniumTest {
fn get_connector_name(&self) -> String {
"bluesnap".to_string()
}
}
async fn should_make_webhook(web_driver: WebDriver) -> Result<(), WebDriverError> {
let conn = BluesnapSeleniumTest {};
conn.make_webhook_test(
web_driver,
&format!("{CHECKOUT_BASE_URL}/saved/199"),
vec![
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
10,
"succeeded",
)
.await?;
Ok(())
}
#[test]
fn should_make_webhook_test() {
tester!(should_make_webhook);
}
|
crates/test_utils/tests/connectors/bluesnap_wh_ui.rs
|
test_utils
|
full_file
| null | null | null | 211
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorSpecifications for for HyperswitchVault
// File: crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs
// Module: hyperswitch_connectors
// Methods: 1 total (0 public)
impl ConnectorSpecifications for for HyperswitchVault
|
crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
HyperswitchVault
|
ConnectorSpecifications for
| 1
| 0
| null | null |
// Implementation: impl api::PaymentSync for for Nomupay
// File: crates/hyperswitch_connectors/src/connectors/nomupay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSync for for Nomupay
|
crates/hyperswitch_connectors/src/connectors/nomupay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 61
| null |
Nomupay
|
api::PaymentSync for
| 0
| 0
| null | null |
// Function: find_by_merchant_id_merchant_connector_id
// File: crates/diesel_models/src/query/merchant_connector_account.rs
// Module: diesel_models
pub fn find_by_merchant_id_merchant_connector_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
merchant_connector_id: &common_utils::id_type::MerchantConnectorAccountId,
) -> StorageResult<Self>
|
crates/diesel_models/src/query/merchant_connector_account.rs
|
diesel_models
|
function_signature
| null | null | null | 92
|
find_by_merchant_id_merchant_connector_id
| null | null | null | null | null | null |
// Struct: StaxRouterData
// File: crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct StaxRouterData<T>
|
crates/hyperswitch_connectors/src/connectors/stax/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
StaxRouterData
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Struct: MifinityPsyncPayload
// File: crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct MifinityPsyncPayload
|
crates/hyperswitch_connectors/src/connectors/mifinity/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
MifinityPsyncPayload
| 0
|
[] | 54
| null | null | null | null | null | null | null |
// Struct: LabelWithBucketNameEventRequest
// File: crates/router/src/core/payments/routing/utils.rs
// Module: router
// Implementations: 0
pub struct LabelWithBucketNameEventRequest
|
crates/router/src/core/payments/routing/utils.rs
|
router
|
struct_definition
|
LabelWithBucketNameEventRequest
| 0
|
[] | 44
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSync for for Powertranz
// File: crates/hyperswitch_connectors/src/connectors/powertranz.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSync for for Powertranz
|
crates/hyperswitch_connectors/src/connectors/powertranz.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Powertranz
|
api::PaymentSync for
| 0
| 0
| null | null |
// Struct: FraudCheckFulfillmentData
// File: crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct FraudCheckFulfillmentData
|
crates/hyperswitch_domain_models/src/router_request_types/fraud_check.rs
|
hyperswitch_domain_models
|
struct_definition
|
FraudCheckFulfillmentData
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Struct: StripeConnectPayoutCreateResponse
// File: crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct StripeConnectPayoutCreateResponse
|
crates/hyperswitch_connectors/src/connectors/stripe/transformers/connect.rs
|
hyperswitch_connectors
|
struct_definition
|
StripeConnectPayoutCreateResponse
| 0
|
[] | 54
| null | null | null | null | null | null | null |
// Function: is_success
// File: crates/common_enums/src/enums.rs
// Module: common_enums
pub fn is_success(self) -> bool
|
crates/common_enums/src/enums.rs
|
common_enums
|
function_signature
| null | null | null | 33
|
is_success
| null | null | null | null | null | null |
// File: crates/router/src/types/storage/customers.rs
// Module: router
pub use diesel_models::customers::{Customer, CustomerNew, CustomerUpdateInternal};
#[cfg(feature = "v2")]
pub use crate::types::domain::CustomerGeneralUpdate;
pub use crate::types::domain::CustomerUpdate;
|
crates/router/src/types/storage/customers.rs
|
router
|
full_file
| null | null | null | 64
| null | null | null | null | null | null | null |
// Struct: RouterDataV2
// File: crates/hyperswitch_domain_models/src/router_data_v2.rs
// Module: hyperswitch_domain_models
// Implementations: 1
// Traits: Deref
pub struct RouterDataV2<Flow, ResourceCommonData, FlowSpecificRequest, FlowSpecificResponse>
|
crates/hyperswitch_domain_models/src/router_data_v2.rs
|
hyperswitch_domain_models
|
struct_definition
|
RouterDataV2
| 1
|
[
"Deref"
] | 67
| null | null | null | null | null | null | null |
// Function: get_frm_metrics_info
// File: crates/analytics/src/utils.rs
// Module: analytics
pub fn get_frm_metrics_info() -> Vec<NameDescription>
|
crates/analytics/src/utils.rs
|
analytics
|
function_signature
| null | null | null | 36
|
get_frm_metrics_info
| null | null | null | null | null | null |
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?;
match business_profile {
Some(business_profile) => {
core_utils::validate_profile_id_from_auth_layer(
authentication_profile_id,
&business_profile,
)?;
let routing_algo_ref: routing_types::RoutingAlgorithmRef = match transaction_type {
enums::TransactionType::Payment => business_profile.routing_algorithm.clone(),
#[cfg(feature = "payouts")]
enums::TransactionType::Payout => business_profile.payout_routing_algorithm.clone(),
enums::TransactionType::ThreeDsAuthentication => {
business_profile.three_ds_decision_rule_algorithm.clone()
}
}
.map(|val| val.parse_value("RoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize routing algorithm ref from merchant account")?
.unwrap_or_default();
let timestamp = common_utils::date_time::now_unix_timestamp();
match routing_algo_ref.algorithm_id {
Some(algorithm_id) => {
let routing_algorithm: routing_types::RoutingAlgorithmRef =
routing_types::RoutingAlgorithmRef {
algorithm_id: None,
timestamp,
config_algo_id: routing_algo_ref.config_algo_id.clone(),
surcharge_config_algo_id: routing_algo_ref.surcharge_config_algo_id,
};
let record = db
.find_routing_algorithm_by_profile_id_algorithm_id(
&profile_id,
&algorithm_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let response = record.foreign_into();
helpers::update_profile_active_algorithm_ref(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
business_profile,
routing_algorithm,
&transaction_type,
)
.await?;
metrics::ROUTING_UNLINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(response))
}
None => Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already inactive".to_string(),
})?,
}
}
None => Err(errors::ApiErrorResponse::InvalidRequestData {
message: "The business_profile is not present".to_string(),
}
.into()),
}
}
#[cfg(feature = "v2")]
pub async fn update_default_fallback_routing(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: common_utils::id_type::ProfileId,
updated_list_of_connectors: Vec<routing_types::RoutableConnectorChoice>,
) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {
metrics::ROUTING_UPDATE_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")?;
let profile_wrapper = admin::ProfileWrapper::new(profile);
let default_list_of_connectors =
profile_wrapper.get_default_fallback_list_of_connector_under_profile()?;
utils::when(
default_list_of_connectors.len() != updated_list_of_connectors.len(),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "current config and updated config have different lengths".to_string(),
})
},
)?;
let existing_set_of_default_connectors: FxHashSet<String> = FxHashSet::from_iter(
default_list_of_connectors
.iter()
.map(|conn_choice| conn_choice.to_string()),
);
let updated_set_of_default_connectors: FxHashSet<String> = FxHashSet::from_iter(
updated_list_of_connectors
.iter()
.map(|conn_choice| conn_choice.to_string()),
);
let symmetric_diff_between_existing_and_updated_connectors: Vec<String> =
existing_set_of_default_connectors
.symmetric_difference(&updated_set_of_default_connectors)
.cloned()
.collect();
utils::when(
!symmetric_diff_between_existing_and_updated_connectors.is_empty(),
|| {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector mismatch between old and new configs ({})",
symmetric_diff_between_existing_and_updated_connectors.join(", ")
),
})
},
)?;
profile_wrapper
.update_default_fallback_routing_of_connectors_under_profile(
db,
&updated_list_of_connectors,
key_manager_state,
merchant_context.get_merchant_key_store(),
)
.await?;
metrics::ROUTING_UPDATE_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(
updated_list_of_connectors,
))
}
#[cfg(feature = "v1")]
pub async fn update_default_routing_config(
state: SessionState,
merchant_context: domain::MerchantContext,
updated_config: Vec<routing_types::RoutableConnectorChoice>,
transaction_type: &enums::TransactionType,
) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {
metrics::ROUTING_UPDATE_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let default_config = helpers::get_merchant_default_config(
db,
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr(),
transaction_type,
)
.await?;
utils::when(default_config.len() != updated_config.len(), || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "current config and updated config have different lengths".to_string(),
})
})?;
let existing_set: FxHashSet<String> =
FxHashSet::from_iter(default_config.iter().map(|c| c.to_string()));
let updated_set: FxHashSet<String> =
FxHashSet::from_iter(updated_config.iter().map(|c| c.to_string()));
let symmetric_diff: Vec<String> = existing_set
.symmetric_difference(&updated_set)
.cloned()
.collect();
utils::when(!symmetric_diff.is_empty(), || {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"connector mismatch between old and new configs ({})",
symmetric_diff.join(", ")
),
})
})?;
helpers::update_merchant_default_config(
db,
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr(),
updated_config.clone(),
transaction_type,
)
.await?;
metrics::ROUTING_UPDATE_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(updated_config))
}
#[cfg(feature = "v2")]
pub async fn retrieve_default_fallback_algorithm_for_profile(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: common_utils::id_type::ProfileId,
) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {
metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")?;
let connectors_choice = admin::ProfileWrapper::new(profile)
.get_default_fallback_list_of_connector_under_profile()?;
metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(connectors_choice))
}
#[cfg(feature = "v1")]
pub async fn retrieve_default_routing_config(
state: SessionState,
profile_id: Option<common_utils::id_type::ProfileId>,
merchant_context: domain::MerchantContext,
transaction_type: &enums::TransactionType,
) -> RouterResponse<Vec<routing_types::RoutableConnectorChoice>> {
metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let id = profile_id
.map(|profile_id| profile_id.get_string_repr().to_owned())
.unwrap_or_else(|| {
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr()
.to_string()
});
helpers::get_merchant_default_config(db, &id, transaction_type)
.await
.map(|conn_choice| {
metrics::ROUTING_RETRIEVE_DEFAULT_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
service_api::ApplicationResponse::Json(conn_choice)
})
}
#[cfg(feature = "v2")]
pub async fn retrieve_routing_config_under_profile(
state: SessionState,
merchant_context: domain::MerchantContext,
query_params: RoutingRetrieveQuery,
profile_id: common_utils::id_type::ProfileId,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::LinkedRoutingConfigRetrieveResponse> {
metrics::ROUTING_RETRIEVE_LINK_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")?;
let record = db
.list_routing_algorithm_metadata_by_profile_id(
business_profile.get_id(),
i64::from(query_params.limit.unwrap_or_default()),
i64::from(query_params.offset.unwrap_or_default()),
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let active_algorithms = record
.into_iter()
.filter(|routing_rec| &routing_rec.algorithm_for == transaction_type)
.map(|routing_algo| routing_algo.foreign_into())
.collect::<Vec<_>>();
metrics::ROUTING_RETRIEVE_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(
routing_types::LinkedRoutingConfigRetrieveResponse::ProfileBased(active_algorithms),
))
}
#[cfg(feature = "v1")]
pub async fn retrieve_linked_routing_config(
state: SessionState,
merchant_context: domain::MerchantContext,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
query_params: routing_types::RoutingRetrieveLinkQuery,
transaction_type: enums::TransactionType,
) -> RouterResponse<routing_types::LinkedRoutingConfigRetrieveResponse> {
metrics::ROUTING_RETRIEVE_LINK_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let merchant_key_store = merchant_context.get_merchant_key_store();
let merchant_id = merchant_context.get_merchant_account().get_id();
// Get business profiles
let business_profiles = if let Some(profile_id) = query_params.profile_id {
core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_key_store,
Some(&profile_id),
merchant_id,
)
.await?
.map(|profile| vec![profile])
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?
} else {
let business_profile = db
.list_profile_by_merchant_id(key_manager_state, merchant_key_store, merchant_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
core_utils::filter_objects_based_on_profile_id_list(
authentication_profile_id.map(|profile_id| vec![profile_id]),
business_profile,
)
};
let mut active_algorithms = Vec::new();
for business_profile in business_profiles {
let profile_id = business_profile.get_id();
// Handle static routing algorithm
let routing_ref: routing_types::RoutingAlgorithmRef = match transaction_type {
enums::TransactionType::Payment => &business_profile.routing_algorithm,
#[cfg(feature = "payouts")]
enums::TransactionType::Payout => &business_profile.payout_routing_algorithm,
enums::TransactionType::ThreeDsAuthentication => {
&business_profile.three_ds_decision_rule_algorithm
}
}
.clone()
.map(|val| val.parse_value("RoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize routing algorithm ref from merchant account")?
.unwrap_or_default();
if let Some(algorithm_id) = routing_ref.algorithm_id {
let record = db
.find_routing_algorithm_metadata_by_algorithm_id_profile_id(
&algorithm_id,
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let hs_records: Vec<routing_types::RoutingDictionaryRecord> =
vec![record.foreign_into()];
let de_records = retrieve_decision_engine_active_rules(
&state,
&transaction_type,
profile_id.clone(),
hs_records.clone(),
)
.await;
compare_and_log_result(
de_records.clone(),
hs_records.clone(),
"list_active_routing".to_string(),
);
active_algorithms.append(
&mut select_routing_result(&state, &business_profile, hs_records, de_records).await,
);
}
// Handle dynamic routing algorithms
let dynamic_routing_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize dynamic routing algorithm ref from business profile",
)?
.unwrap_or_default();
// Collect all dynamic algorithm IDs
let mut dynamic_algorithm_ids = Vec::new();
if let Some(sba) = &dynamic_routing_ref.success_based_algorithm {
if let Some(id) = &sba.algorithm_id_with_timestamp.algorithm_id {
dynamic_algorithm_ids.push(id.clone());
}
}
if let Some(era) = &dynamic_routing_ref.elimination_routing_algorithm {
if let Some(id) = &era.algorithm_id_with_timestamp.algorithm_id {
dynamic_algorithm_ids.push(id.clone());
}
}
if let Some(cbr) = &dynamic_routing_ref.contract_based_routing {
if let Some(id) = &cbr.algorithm_id_with_timestamp.algorithm_id {
dynamic_algorithm_ids.push(id.clone());
}
}
// Fetch all dynamic algorithms
for algorithm_id in dynamic_algorithm_ids {
let record = db
.find_routing_algorithm_metadata_by_algorithm_id_profile_id(
&algorithm_id,
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
if record.algorithm_for == transaction_type {
active_algorithms.push(record.foreign_into());
}
}
}
metrics::ROUTING_RETRIEVE_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(
routing_types::LinkedRoutingConfigRetrieveResponse::ProfileBased(active_algorithms),
))
}
pub async fn retrieve_decision_engine_active_rules(
state: &SessionState,
transaction_type: &enums::TransactionType,
profile_id: common_utils::id_type::ProfileId,
hs_records: Vec<routing_types::RoutingDictionaryRecord>,
) -> Vec<routing_types::RoutingDictionaryRecord> {
let mut de_records =
list_de_euclid_active_routing_algorithm(state, profile_id.get_string_repr().to_owned())
.await
.map_err(|e| {
router_env::logger::error!(?e, "Failed to list DE Euclid active routing algorithm");
})
.ok() // Avoid throwing error if Decision Engine is not available or other errors thrown
.unwrap_or_default();
// Use Hs records to list the dynamic algorithms as DE is not supporting dynamic algorithms in HS standard
let mut dynamic_algos = hs_records
.into_iter()
.filter(|record| record.kind == routing_types::RoutingAlgorithmKind::Dynamic)
.collect::<Vec<_>>();
de_records.append(&mut dynamic_algos);
de_records
.into_iter()
.filter(|r| r.algorithm_for == Some(*transaction_type))
.collect::<Vec<_>>()
}
// List all the default fallback algorithms under all the profile under a merchant
pub async fn retrieve_default_routing_config_for_profiles(
state: SessionState,
merchant_context: domain::MerchantContext,
transaction_type: &enums::TransactionType,
) -> RouterResponse<Vec<routing_types::ProfileDefaultRoutingConfig>> {
metrics::ROUTING_RETRIEVE_CONFIG_FOR_PROFILE.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let all_profiles = db
.list_profile_by_merchant_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().get_id(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)
.attach_printable("error retrieving all business profiles for merchant")?;
let retrieve_config_futures = all_profiles
.iter()
.map(|prof| {
helpers::get_merchant_default_config(
db,
prof.get_id().get_string_repr(),
transaction_type,
)
})
.collect::<Vec<_>>();
let configs = futures::future::join_all(retrieve_config_futures)
.await
.into_iter()
.collect::<Result<Vec<_>, _>>()?;
let default_configs = configs
.into_iter()
.zip(all_profiles.iter().map(|prof| prof.get_id().to_owned()))
.map(
|(config, profile_id)| routing_types::ProfileDefaultRoutingConfig {
profile_id,
connectors: config,
},
)
.collect::<Vec<_>>();
metrics::ROUTING_RETRIEVE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(default_configs))
}
pub async fn update_default_routing_config_for_profile(
state: SessionState,
merchant_context: domain::MerchantContext,
updated_config: Vec<routing_types::RoutableConnectorChoice>,
profile_id: common_utils::id_type::ProfileId,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::ProfileDefaultRoutingConfig> {
metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let default_config = helpers::get_merchant_default_config(
db,
business_profile.get_id().get_string_repr(),
transaction_type,
)
.await?;
utils::when(default_config.len() != updated_config.len(), || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "current config and updated config have different lengths".to_string(),
})
})?;
let existing_set = FxHashSet::from_iter(
default_config
.iter()
.map(|c| (c.connector.to_string(), c.merchant_connector_id.as_ref())),
);
let updated_set = FxHashSet::from_iter(
updated_config
.iter()
.map(|c| (c.connector.to_string(), c.merchant_connector_id.as_ref())),
);
let symmetric_diff = existing_set
.symmetric_difference(&updated_set)
.cloned()
.collect::<Vec<_>>();
utils::when(!symmetric_diff.is_empty(), || {
let error_str = symmetric_diff
.into_iter()
.map(|(connector, ident)| format!("'{connector}:{ident:?}'"))
.collect::<Vec<_>>()
.join(", ");
Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!("connector mismatch between old and new configs ({error_str})"),
})
})?;
helpers::update_merchant_default_config(
db,
business_profile.get_id().get_string_repr(),
updated_config.clone(),
transaction_type,
)
.await?;
metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(
routing_types::ProfileDefaultRoutingConfig {
profile_id: business_profile.get_id().to_owned(),
connectors: updated_config,
},
))
}
// Toggle the specific routing type as well as add the default configs in RoutingAlgorithm table
// and update the same in business profile table.
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn toggle_specific_dynamic_routing(
state: SessionState,
merchant_context: domain::MerchantContext,
feature_to_enable: routing::DynamicRoutingFeatures,
profile_id: common_utils::id_type::ProfileId,
dynamic_routing_type: routing::DynamicRoutingType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(
1,
router_env::metric_attributes!(
("profile_id", profile_id.clone()),
("algorithm_type", dynamic_routing_type.to_string())
),
);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize dynamic routing algorithm ref from business profile",
)?
.unwrap_or_default();
match feature_to_enable {
routing::DynamicRoutingFeatures::Metrics
| routing::DynamicRoutingFeatures::DynamicConnectorSelection => {
// occurs when algorithm is already present in the db
// 1. If present with same feature then return response as already enabled
// 2. Else update the feature and persist the same on db
// 3. If not present in db then create a new default entry
Box::pin(helpers::enable_dynamic_routing_algorithm(
&state,
merchant_context.get_merchant_key_store().clone(),
business_profile,
feature_to_enable,
dynamic_routing_algo_ref,
dynamic_routing_type,
None,
))
.await
}
routing::DynamicRoutingFeatures::None => {
// disable specific dynamic routing for the requested profile
helpers::disable_dynamic_routing_algorithm(
&state,
merchant_context.get_merchant_key_store().clone(),
business_profile,
dynamic_routing_algo_ref,
dynamic_routing_type,
)
.await
}
}
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn create_specific_dynamic_routing(
state: SessionState,
merchant_context: domain::MerchantContext,
feature_to_enable: routing::DynamicRoutingFeatures,
profile_id: common_utils::id_type::ProfileId,
dynamic_routing_type: routing::DynamicRoutingType,
payload: routing_types::DynamicRoutingPayload,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(
1,
router_env::metric_attributes!(
("profile_id", profile_id.clone()),
("algorithm_type", dynamic_routing_type.to_string())
),
);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize dynamic routing algorithm ref from business profile",
)?
.unwrap_or_default();
match feature_to_enable {
routing::DynamicRoutingFeatures::Metrics
| routing::DynamicRoutingFeatures::DynamicConnectorSelection => {
Box::pin(helpers::enable_dynamic_routing_algorithm(
&state,
merchant_context.get_merchant_key_store().clone(),
business_profile,
feature_to_enable,
dynamic_routing_algo_ref,
dynamic_routing_type,
Some(payload),
))
.await
}
routing::DynamicRoutingFeatures::None => {
// disable specific dynamic routing for the requested profile
helpers::disable_dynamic_routing_algorithm(
&state,
merchant_context.get_merchant_key_store().clone(),
business_profile,
dynamic_routing_algo_ref,
dynamic_routing_type,
)
.await
}
}
}
#[cfg(feature = "v1")]
pub async fn configure_dynamic_routing_volume_split(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: common_utils::id_type::ProfileId,
routing_info: routing::RoutingVolumeSplit,
) -> RouterResponse<routing::RoutingVolumeSplit> {
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.clone())),
);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
utils::when(
routing_info.split > crate::consts::DYNAMIC_ROUTING_MAX_VOLUME,
|| {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "Dynamic routing volume split should be less than 100".to_string(),
})
},
)?;
let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let mut dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize dynamic routing algorithm ref from business profile",
)?
.unwrap_or_default();
dynamic_routing_algo_ref.update_volume_split(Some(routing_info.split));
helpers::update_business_profile_active_dynamic_algorithm_ref(
db,
&((&state).into()),
merchant_context.get_merchant_key_store(),
business_profile.clone(),
dynamic_routing_algo_ref.clone(),
)
.await?;
Ok(service_api::ApplicationResponse::Json(routing_info))
}
#[cfg(feature = "v1")]
pub async fn retrieve_dynamic_routing_volume_split(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: common_utils::id_type::ProfileId,
) -> RouterResponse<routing_types::RoutingVolumeSplitResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")
.change_context(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
let dynamic_routing_algo_ref: routing_types::DynamicRoutingAlgorithmRef = business_profile
.dynamic_routing_algorithm
.clone()
.map(|val| val.parse_value("DynamicRoutingAlgorithmRef"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize dynamic routing algorithm ref from business profile",
)?
.unwrap_or_default();
let resp = routing_types::RoutingVolumeSplitResponse {
split: dynamic_routing_algo_ref
.dynamic_routing_volume_split
.unwrap_or_default(),
};
Ok(service_api::ApplicationResponse::Json(resp))
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn success_based_routing_update_configs(
state: SessionState,
request: routing_types::SuccessBasedRoutingConfig,
algorithm_id: common_utils::id_type::RoutingId,
profile_id: common_utils::id_type::ProfileId,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(
1,
router_env::metric_attributes!(
("profile_id", profile_id.clone()),
(
"algorithm_type",
routing::DynamicRoutingType::SuccessRateBasedRouting.to_string()
)
),
);
let db = state.store.as_ref();
let dynamic_routing_algo_to_update = db
.find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let mut config_to_update: routing::SuccessBasedRoutingConfig = dynamic_routing_algo_to_update
.algorithm_data
.parse_value::<routing::SuccessBasedRoutingConfig>("SuccessBasedRoutingConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("unable to deserialize algorithm data from routing table into SuccessBasedRoutingConfig")?;
config_to_update.update(request);
let updated_algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = RoutingAlgorithm {
algorithm_id: updated_algorithm_id,
profile_id: dynamic_routing_algo_to_update.profile_id,
merchant_id: dynamic_routing_algo_to_update.merchant_id,
name: dynamic_routing_algo_to_update.name,
description: dynamic_routing_algo_to_update.description,
kind: dynamic_routing_algo_to_update.kind,
algorithm_data: serde_json::json!(config_to_update.clone()),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: dynamic_routing_algo_to_update.algorithm_for,
decision_engine_routing_id: None,
};
let record = db
.insert_routing_algorithm(algo)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to insert record in routing algorithm table")?;
// redact cache for success based routing configs
let cache_key = format!(
"{}_{}",
profile_id.get_string_repr(),
algorithm_id.get_string_repr()
);
let cache_entries_to_redact = vec![cache::CacheKind::SuccessBasedDynamicRoutingCache(
cache_key.into(),
)];
let _ = cache::redact_from_redis_and_publish(
state.store.get_cache_store().as_ref(),
cache_entries_to_redact,
)
.await
.map_err(|e| router_env::logger::error!("unable to publish into the redact channel for evicting the success based routing config cache {e:?}"));
let new_record = record.foreign_into();
metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.clone())),
);
if !state.conf.open_router.dynamic_routing_enabled {
state
.grpc_client
.dynamic_routing
.as_ref()
.async_map(|dr_client| async {
dr_client
.success_rate_client
.invalidate_success_rate_routing_keys(
profile_id.get_string_repr().into(),
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate the routing keys")
})
.await
.transpose()?;
}
Ok(service_api::ApplicationResponse::Json(new_record))
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn elimination_routing_update_configs(
state: SessionState,
request: routing_types::EliminationRoutingConfig,
algorithm_id: common_utils::id_type::RoutingId,
profile_id: common_utils::id_type::ProfileId,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE.add(
1,
router_env::metric_attributes!(
("profile_id", profile_id.clone()),
(
"algorithm_type",
routing::DynamicRoutingType::EliminationRouting.to_string()
)
),
);
let db = state.store.as_ref();
let dynamic_routing_algo_to_update = db
.find_routing_algorithm_by_profile_id_algorithm_id(&profile_id, &algorithm_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let mut config_to_update: routing::EliminationRoutingConfig = dynamic_routing_algo_to_update
.algorithm_data
.parse_value::<routing::EliminationRoutingConfig>("EliminationRoutingConfig")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"unable to deserialize algorithm data from routing table into EliminationRoutingConfig",
)?;
config_to_update.update(request);
let updated_algorithm_id = common_utils::generate_routing_id_of_default_length();
let timestamp = common_utils::date_time::now();
let algo = RoutingAlgorithm {
algorithm_id: updated_algorithm_id,
profile_id: dynamic_routing_algo_to_update.profile_id,
merchant_id: dynamic_routing_algo_to_update.merchant_id,
name: dynamic_routing_algo_to_update.name,
description: dynamic_routing_algo_to_update.description,
kind: dynamic_routing_algo_to_update.kind,
algorithm_data: serde_json::json!(config_to_update),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: dynamic_routing_algo_to_update.algorithm_for,
decision_engine_routing_id: None,
};
let record = db
.insert_routing_algorithm(algo)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to insert record in routing algorithm table")?;
// redact cache for elimination routing configs
let cache_key = format!(
"{}_{}",
profile_id.get_string_repr(),
algorithm_id.get_string_repr()
);
let cache_entries_to_redact = vec![cache::CacheKind::EliminationBasedDynamicRoutingCache(
cache_key.into(),
)];
cache::redact_from_redis_and_publish(
state.store.get_cache_store().as_ref(),
cache_entries_to_redact,
)
.await
.map_err(|e| router_env::logger::error!("unable to publish into the redact channel for evicting the elimination routing config cache {e:?}")).ok();
let new_record = record.foreign_into();
metrics::ROUTING_UPDATE_CONFIG_FOR_PROFILE_SUCCESS_RESPONSE.add(
1,
router_env::metric_attributes!(("profile_id", profile_id.clone())),
);
if !state.conf.open_router.dynamic_routing_enabled {
state
.grpc_client
.dynamic_routing
.as_ref()
.async_map(|dr_client| async {
dr_client
.elimination_based_client
.invalidate_elimination_bucket(
profile_id.get_string_repr().into(),
state.get_grpc_headers(),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate the elimination routing keys")
})
.await
.transpose()?;
}
Ok(service_api::ApplicationResponse::Json(new_record))
}
#[cfg(all(feature = "v1", feature = "dynamic_routing"))]
pub async fn contract_based_dynamic_routing_setup(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: common_utils::id_type::ProfileId,
feature_to_enable: routing_types::DynamicRoutingFeatures,
config: Option<routing_types::ContractBasedRoutingConfig>,
) -> RouterResult<service_api::ApplicationResponse<routing_types::RoutingDictionaryRecord>> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let business_profile: domain::Profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
|
crates/router/src/core/routing.rs#chunk1
|
router
|
chunk
| null | null | null | 8,190
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentSync for for Paysafe
// File: crates/hyperswitch_connectors/src/connectors/paysafe.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSync for for Paysafe
|
crates/hyperswitch_connectors/src/connectors/paysafe.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Paysafe
|
api::PaymentSync for
| 0
| 0
| null | null |
// Implementation: impl GpayTokenizationData
// File: crates/common_types/src/payments.rs
// Module: common_types
// Methods: 3 total (3 public)
impl GpayTokenizationData
|
crates/common_types/src/payments.rs
|
common_types
|
impl_block
| null | null | null | 43
| null |
GpayTokenizationData
| null | 3
| 3
| null | null |
// Function: clone_connector
// File: crates/router/src/routes/user.rs
// Module: router
pub fn clone_connector(
state: web::Data<AppState>,
req: HttpRequest,
json_payload: web::Json<user_api::CloneConnectorRequest>,
) -> HttpResponse
|
crates/router/src/routes/user.rs
|
router
|
function_signature
| null | null | null | 58
|
clone_connector
| null | null | null | null | null | null |
// Implementation: impl api::RefundExecute for for Forte
// File: crates/hyperswitch_connectors/src/connectors/forte.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Forte
|
crates/hyperswitch_connectors/src/connectors/forte.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Forte
|
api::RefundExecute for
| 0
| 0
| null | null |
// Function: update_from_request
// File: crates/hyperswitch_domain_models/src/payments.rs
// Module: hyperswitch_domain_models
pub fn update_from_request(self, req: &api_models::payments::AmountDetailsUpdate) -> Self
|
crates/hyperswitch_domain_models/src/payments.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 51
|
update_from_request
| null | null | null | null | null | null |
// Struct: ErrorData
// File: crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ErrorData
|
crates/hyperswitch_connectors/src/connectors/riskified/transformers/api.rs
|
hyperswitch_connectors
|
struct_definition
|
ErrorData
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Trait: AuthServiceConnector
// File: crates/pm_auth/src/types/api.rs
// Module: pm_auth
pub trait AuthServiceConnector: AuthService + Send + Debug + PaymentInitiation
|
crates/pm_auth/src/types/api.rs
|
pm_auth
|
trait_definition
| null | null | null | 37
| null | null |
AuthServiceConnector
| null | null | null | null |
// Implementation: impl ExchangeRates
// File: crates/currency_conversion/src/types.rs
// Module: currency_conversion
// Methods: 3 total (3 public)
impl ExchangeRates
|
crates/currency_conversion/src/types.rs
|
currency_conversion
|
impl_block
| null | null | null | 37
| null |
ExchangeRates
| null | 3
| 3
| null | null |
// Function: server
// File: crates/router/src/routes/app.rs
// Module: router
pub fn server(state: AppState) -> Scope
|
crates/router/src/routes/app.rs
|
router
|
function_signature
| null | null | null | 29
|
server
| null | null | null | null | null | null |
// Implementation: impl ConnectorPostAuthentication for for Gpayments
// File: crates/hyperswitch_connectors/src/connectors/gpayments.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl ConnectorPostAuthentication for for Gpayments
|
crates/hyperswitch_connectors/src/connectors/gpayments.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 55
| null |
Gpayments
|
ConnectorPostAuthentication for
| 0
| 0
| null | null |
// Function: api_key_revoke
// File: crates/router/src/routes/api_keys.rs
// Module: router
pub fn api_key_revoke(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::ApiKeyId,
)
|
crates/router/src/routes/api_keys.rs
|
router
|
function_signature
| null | null | null | 75
|
api_key_revoke
| null | null | null | null | null | null |
// File: crates/hyperswitch_domain_models/src/revenue_recovery.rs
// Module: hyperswitch_domain_models
// Public functions: 1
// Public structs: 4
use api_models::{payments as api_payments, webhooks};
use common_enums::enums as common_enums;
use common_types::primitive_wrappers;
use common_utils::{id_type, pii, types as util_types};
use time::PrimitiveDateTime;
use crate::{
payments,
router_response_types::revenue_recovery::{
BillingConnectorInvoiceSyncResponse, BillingConnectorPaymentsSyncResponse,
},
ApiModelToDieselModelConvertor,
};
/// Recovery payload is unified struct constructed from billing connectors
#[derive(Debug)]
pub struct RevenueRecoveryAttemptData {
/// transaction amount against invoice, accepted in minor unit.
pub amount: util_types::MinorUnit,
/// currency of the transaction
pub currency: common_enums::Currency,
/// merchant reference id at billing connector. ex: invoice_id
pub merchant_reference_id: id_type::PaymentReferenceId,
/// transaction id reference at payment connector
pub connector_transaction_id: Option<util_types::ConnectorTransactionId>,
/// error code sent by billing connector.
pub error_code: Option<String>,
/// error message sent by billing connector.
pub error_message: Option<String>,
/// mandate token at payment processor end.
pub processor_payment_method_token: String,
/// customer id at payment connector for which mandate is attached.
pub connector_customer_id: String,
/// Payment gateway identifier id at billing processor.
pub connector_account_reference_id: String,
/// timestamp at which transaction has been created at billing connector
pub transaction_created_at: Option<PrimitiveDateTime>,
/// transaction status at billing connector equivalent to payment attempt status.
pub status: common_enums::AttemptStatus,
/// payment method of payment attempt.
pub payment_method_type: common_enums::PaymentMethod,
/// payment method sub type of the payment attempt.
pub payment_method_sub_type: common_enums::PaymentMethodType,
/// This field can be returned for both approved and refused Mastercard payments.
/// This code provides additional information about the type of transaction or the reason why the payment failed.
/// If the payment failed, the network advice code gives guidance on if and when you can retry the payment.
pub network_advice_code: Option<String>,
/// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed.
pub network_decline_code: Option<String>,
/// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better.
pub network_error_message: Option<String>,
/// Number of attempts made for an invoice
pub retry_count: Option<u16>,
/// Time when next invoice will be generated which will be equal to the end time of the current invoice
pub invoice_next_billing_time: Option<PrimitiveDateTime>,
/// Time at which the invoice created
pub invoice_billing_started_at_time: Option<PrimitiveDateTime>,
/// stripe specific id used to validate duplicate attempts in revenue recovery flow
pub charge_id: Option<String>,
/// Additional card details
pub card_info: api_payments::AdditionalCardInfo,
}
/// This is unified struct for Revenue Recovery Invoice Data and it is constructed from billing connectors
#[derive(Debug, Clone)]
pub struct RevenueRecoveryInvoiceData {
/// invoice amount at billing connector
pub amount: util_types::MinorUnit,
/// currency of the amount.
pub currency: common_enums::Currency,
/// merchant reference id at billing connector. ex: invoice_id
pub merchant_reference_id: id_type::PaymentReferenceId,
/// billing address id of the invoice
pub billing_address: Option<api_payments::Address>,
/// Retry count of the invoice
pub retry_count: Option<u16>,
/// Ending date of the invoice or the Next billing time of the Subscription
pub next_billing_at: Option<PrimitiveDateTime>,
/// Invoice Starting Time
pub billing_started_at: Option<PrimitiveDateTime>,
/// metadata of the merchant
pub metadata: Option<pii::SecretSerdeValue>,
/// Allow partial authorization for this payment
pub enable_partial_authorization: Option<primitive_wrappers::EnablePartialAuthorizationBool>,
}
#[derive(Clone, Debug)]
pub struct RecoveryPaymentIntent {
pub payment_id: id_type::GlobalPaymentId,
pub status: common_enums::IntentStatus,
pub feature_metadata: Option<api_payments::FeatureMetadata>,
pub merchant_id: id_type::MerchantId,
pub merchant_reference_id: Option<id_type::PaymentReferenceId>,
pub invoice_amount: util_types::MinorUnit,
pub invoice_currency: common_enums::Currency,
pub created_at: Option<PrimitiveDateTime>,
pub billing_address: Option<api_payments::Address>,
}
#[derive(Clone, Debug)]
pub struct RecoveryPaymentAttempt {
pub attempt_id: id_type::GlobalAttemptId,
pub attempt_status: common_enums::AttemptStatus,
pub feature_metadata: Option<api_payments::PaymentAttemptFeatureMetadata>,
pub amount: util_types::MinorUnit,
pub network_advice_code: Option<String>,
pub network_decline_code: Option<String>,
pub error_code: Option<String>,
pub created_at: PrimitiveDateTime,
}
impl RecoveryPaymentAttempt {
pub fn get_attempt_triggered_by(&self) -> Option<common_enums::TriggeredBy> {
self.feature_metadata.as_ref().and_then(|metadata| {
metadata
.revenue_recovery
.as_ref()
.map(|recovery| recovery.attempt_triggered_by)
})
}
}
impl From<&RevenueRecoveryInvoiceData> for api_payments::AmountDetails {
fn from(data: &RevenueRecoveryInvoiceData) -> Self {
let amount = api_payments::AmountDetailsSetter {
order_amount: data.amount.into(),
currency: data.currency,
shipping_cost: None,
order_tax_amount: None,
skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip,
skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip,
surcharge_amount: None,
tax_on_surcharge: None,
};
Self::new(amount)
}
}
impl From<&RevenueRecoveryInvoiceData> for api_payments::PaymentsCreateIntentRequest {
fn from(data: &RevenueRecoveryInvoiceData) -> Self {
let amount_details = api_payments::AmountDetails::from(data);
Self {
amount_details,
merchant_reference_id: Some(data.merchant_reference_id.clone()),
routing_algorithm_id: None,
// Payments in the revenue recovery flow are always recurring transactions,
// so capture method will be always automatic.
capture_method: Some(common_enums::CaptureMethod::Automatic),
authentication_type: Some(common_enums::AuthenticationType::NoThreeDs),
billing: data.billing_address.clone(),
shipping: None,
customer_id: None,
customer_present: Some(common_enums::PresenceOfCustomerDuringPayment::Absent),
description: None,
return_url: None,
setup_future_usage: None,
apply_mit_exemption: None,
statement_descriptor: None,
order_details: None,
allowed_payment_method_types: None,
metadata: data.metadata.clone(),
connector_metadata: None,
feature_metadata: None,
payment_link_enabled: None,
payment_link_config: None,
request_incremental_authorization: None,
session_expiry: None,
frm_metadata: None,
request_external_three_ds_authentication: None,
force_3ds_challenge: None,
merchant_connector_details: None,
enable_partial_authorization: data.enable_partial_authorization,
}
}
}
impl From<&BillingConnectorInvoiceSyncResponse> for RevenueRecoveryInvoiceData {
fn from(data: &BillingConnectorInvoiceSyncResponse) -> Self {
Self {
amount: data.amount,
currency: data.currency,
merchant_reference_id: data.merchant_reference_id.clone(),
billing_address: data.billing_address.clone(),
retry_count: data.retry_count,
next_billing_at: data.ends_at,
billing_started_at: data.created_at,
metadata: None,
enable_partial_authorization: None,
}
}
}
impl
From<(
&BillingConnectorPaymentsSyncResponse,
&RevenueRecoveryInvoiceData,
)> for RevenueRecoveryAttemptData
{
fn from(
data: (
&BillingConnectorPaymentsSyncResponse,
&RevenueRecoveryInvoiceData,
),
) -> Self {
let billing_connector_payment_details = data.0;
let invoice_details = data.1;
Self {
amount: billing_connector_payment_details.amount,
currency: billing_connector_payment_details.currency,
merchant_reference_id: billing_connector_payment_details
.merchant_reference_id
.clone(),
connector_transaction_id: billing_connector_payment_details
.connector_transaction_id
.clone(),
error_code: billing_connector_payment_details.error_code.clone(),
error_message: billing_connector_payment_details.error_message.clone(),
processor_payment_method_token: billing_connector_payment_details
.processor_payment_method_token
.clone(),
connector_customer_id: billing_connector_payment_details
.connector_customer_id
.clone(),
connector_account_reference_id: billing_connector_payment_details
.connector_account_reference_id
.clone(),
transaction_created_at: billing_connector_payment_details.transaction_created_at,
status: billing_connector_payment_details.status,
payment_method_type: billing_connector_payment_details.payment_method_type,
payment_method_sub_type: billing_connector_payment_details.payment_method_sub_type,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
retry_count: invoice_details.retry_count,
invoice_next_billing_time: invoice_details.next_billing_at,
charge_id: billing_connector_payment_details.charge_id.clone(),
invoice_billing_started_at_time: invoice_details.billing_started_at,
card_info: billing_connector_payment_details.card_info.clone(),
}
}
}
impl From<&RevenueRecoveryAttemptData> for api_payments::PaymentAttemptAmountDetails {
fn from(data: &RevenueRecoveryAttemptData) -> Self {
Self {
net_amount: data.amount,
amount_to_capture: None,
surcharge_amount: None,
tax_on_surcharge: None,
amount_capturable: data.amount,
shipping_cost: None,
order_tax_amount: None,
}
}
}
impl From<&RevenueRecoveryAttemptData> for Option<api_payments::RecordAttemptErrorDetails> {
fn from(data: &RevenueRecoveryAttemptData) -> Self {
data.error_code
.as_ref()
.zip(data.error_message.clone())
.map(|(code, message)| api_payments::RecordAttemptErrorDetails {
code: code.to_string(),
message: message.to_string(),
network_advice_code: data.network_advice_code.clone(),
network_decline_code: data.network_decline_code.clone(),
network_error_message: data.network_error_message.clone(),
})
}
}
impl From<&payments::PaymentIntent> for RecoveryPaymentIntent {
fn from(payment_intent: &payments::PaymentIntent) -> Self {
Self {
payment_id: payment_intent.id.clone(),
status: payment_intent.status,
feature_metadata: payment_intent
.feature_metadata
.clone()
.map(|feature_metadata| feature_metadata.convert_back()),
merchant_reference_id: payment_intent.merchant_reference_id.clone(),
invoice_amount: payment_intent.amount_details.order_amount,
invoice_currency: payment_intent.amount_details.currency,
billing_address: payment_intent
.billing_address
.clone()
.map(|address| api_payments::Address::from(address.into_inner())),
merchant_id: payment_intent.merchant_id.clone(),
created_at: Some(payment_intent.created_at),
}
}
}
impl From<&payments::payment_attempt::PaymentAttempt> for RecoveryPaymentAttempt {
fn from(payment_attempt: &payments::payment_attempt::PaymentAttempt) -> Self {
Self {
attempt_id: payment_attempt.id.clone(),
attempt_status: payment_attempt.status,
feature_metadata: payment_attempt
.feature_metadata
.clone()
.map(
|feature_metadata| api_payments::PaymentAttemptFeatureMetadata {
revenue_recovery: feature_metadata.revenue_recovery.map(|recovery| {
api_payments::PaymentAttemptRevenueRecoveryData {
attempt_triggered_by: recovery.attempt_triggered_by,
charge_id: recovery.charge_id,
}
}),
},
),
amount: payment_attempt.amount_details.get_net_amount(),
network_advice_code: payment_attempt
.error
.clone()
.and_then(|error| error.network_advice_code),
network_decline_code: payment_attempt
.error
.clone()
.and_then(|error| error.network_decline_code),
error_code: payment_attempt
.error
.as_ref()
.map(|error| error.code.clone()),
created_at: payment_attempt.created_at,
}
}
}
|
crates/hyperswitch_domain_models/src/revenue_recovery.rs
|
hyperswitch_domain_models
|
full_file
| null | null | null | 2,772
| null | null | null | null | null | null | null |
// Struct: PayoutAttemptUpdateInternal
// File: crates/diesel_models/src/payout_attempt.rs
// Module: diesel_models
// Implementations: 1
// Traits: Default
pub struct PayoutAttemptUpdateInternal
|
crates/diesel_models/src/payout_attempt.rs
|
diesel_models
|
struct_definition
|
PayoutAttemptUpdateInternal
| 1
|
[
"Default"
] | 47
| null | null | null | null | null | null | null |
// Struct: PaymentMethodType
// File: crates/payment_methods/src/configs/settings.rs
// Module: payment_methods
// Implementations: 0
pub struct PaymentMethodType
|
crates/payment_methods/src/configs/settings.rs
|
payment_methods
|
struct_definition
|
PaymentMethodType
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// Implementation: impl WebhookEvents
// File: crates/router/src/routes/app.rs
// Module: router
// Methods: 1 total (1 public)
impl WebhookEvents
|
crates/router/src/routes/app.rs
|
router
|
impl_block
| null | null | null | 37
| null |
WebhookEvents
| null | 1
| 1
| null | null |
// Function: get_updated_vault_data
// File: crates/hyperswitch_domain_models/src/payments.rs
// Module: hyperswitch_domain_models
pub fn get_updated_vault_data(
existing_vault_data: Option<&Self>,
payment_method_data: &payment_method_data::PaymentMethodData,
) -> Option<Self>
|
crates/hyperswitch_domain_models/src/payments.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 70
|
get_updated_vault_data
| null | null | null | null | null | null |
// Struct: Multitenancy
// File: crates/drainer/src/settings.rs
// Module: drainer
// Implementations: 1
pub struct Multitenancy
|
crates/drainer/src/settings.rs
|
drainer
|
struct_definition
|
Multitenancy
| 1
|
[] | 35
| null | null | null | null | null | null | null |
// Function: update
// File: crates/diesel_models/src/query/payouts.rs
// Module: diesel_models
pub fn update(
self,
conn: &PgPooledConn,
payout_update: PayoutsUpdate,
) -> StorageResult<Self>
|
crates/diesel_models/src/query/payouts.rs
|
diesel_models
|
function_signature
| null | null | null | 57
|
update
| null | null | null | null | null | null |
// Implementation: impl api::PaymentsCompleteAuthorize for for Redsys
// File: crates/hyperswitch_connectors/src/connectors/redsys.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentsCompleteAuthorize for for Redsys
|
crates/hyperswitch_connectors/src/connectors/redsys.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Redsys
|
api::PaymentsCompleteAuthorize for
| 0
| 0
| null | null |
// Struct: Violations
// File: crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Violations
|
crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
Violations
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Implementation: impl Deref for for DisputePollingIntervalInHours
// File: crates/common_types/src/primitive_wrappers.rs
// Module: common_types
// Methods: 1 total (0 public)
impl Deref for for DisputePollingIntervalInHours
|
crates/common_types/src/primitive_wrappers.rs
|
common_types
|
impl_block
| null | null | null | 57
| null |
DisputePollingIntervalInHours
|
Deref for
| 1
| 0
| null | null |
// Struct: MandatePaymentRequest
// File: crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct MandatePaymentRequest
|
crates/hyperswitch_connectors/src/connectors/elavon/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
MandatePaymentRequest
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Function: number_of_digits_after_decimal_point
// File: crates/common_enums/src/enums.rs
// Module: common_enums
pub fn number_of_digits_after_decimal_point(self) -> u8
|
crates/common_enums/src/enums.rs
|
common_enums
|
function_signature
| null | null | null | 42
|
number_of_digits_after_decimal_point
| null | null | null | null | null | null |
// Function: get_filters_for_disputes
// File: crates/router/src/core/disputes.rs
// Module: router
pub fn get_filters_for_disputes(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
) -> RouterResponse<api_models::disputes::DisputeListFilters>
|
crates/router/src/core/disputes.rs
|
router
|
function_signature
| null | null | null | 85
|
get_filters_for_disputes
| null | null | null | null | null | null |
// Implementation: impl api::PaymentToken for for Katapult
// File: crates/hyperswitch_connectors/src/connectors/katapult.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentToken for for Katapult
|
crates/hyperswitch_connectors/src/connectors/katapult.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Katapult
|
api::PaymentToken for
| 0
| 0
| null | null |
// Function: api_key_retrieve
// File: crates/router/src/routes/api_keys.rs
// Module: router
pub fn api_key_retrieve(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::ApiKeyId,
)
|
crates/router/src/routes/api_keys.rs
|
router
|
function_signature
| null | null | null | 75
|
api_key_retrieve
| null | null | null | null | null | null |
// File: crates/router/src/services/authorization/permission_groups.rs
// Module: router
use std::{collections::HashMap, ops::Not};
use common_enums::{EntityType, ParentGroup, PermissionGroup, PermissionScope, Resource};
use strum::IntoEnumIterator;
use super::permissions::{self, ResourceExt};
pub trait PermissionGroupExt {
fn scope(&self) -> PermissionScope;
fn parent(&self) -> ParentGroup;
fn resources(&self) -> Vec<Resource>;
fn accessible_groups(&self) -> Vec<PermissionGroup>;
}
impl PermissionGroupExt for PermissionGroup {
fn scope(&self) -> PermissionScope {
match self {
Self::OperationsView
| Self::ConnectorsView
| Self::WorkflowsView
| Self::AnalyticsView
| Self::UsersView
| Self::MerchantDetailsView
| Self::AccountView
| Self::ReconOpsView
| Self::ReconReportsView
| Self::ThemeView => PermissionScope::Read,
Self::OperationsManage
| Self::ConnectorsManage
| Self::WorkflowsManage
| Self::UsersManage
| Self::MerchantDetailsManage
| Self::OrganizationManage
| Self::AccountManage
| Self::ReconOpsManage
| Self::ReconReportsManage
| Self::InternalManage
| Self::ThemeManage => PermissionScope::Write,
}
}
fn parent(&self) -> ParentGroup {
match self {
Self::OperationsView | Self::OperationsManage => ParentGroup::Operations,
Self::ConnectorsView | Self::ConnectorsManage => ParentGroup::Connectors,
Self::WorkflowsView | Self::WorkflowsManage => ParentGroup::Workflows,
Self::AnalyticsView => ParentGroup::Analytics,
Self::UsersView | Self::UsersManage => ParentGroup::Users,
Self::MerchantDetailsView
| Self::OrganizationManage
| Self::MerchantDetailsManage
| Self::AccountView
| Self::AccountManage => ParentGroup::Account,
Self::ThemeView | Self::ThemeManage => ParentGroup::Theme,
Self::ReconOpsView | Self::ReconOpsManage => ParentGroup::ReconOps,
Self::ReconReportsView | Self::ReconReportsManage => ParentGroup::ReconReports,
Self::InternalManage => ParentGroup::Internal,
}
}
fn resources(&self) -> Vec<Resource> {
self.parent().resources()
}
fn accessible_groups(&self) -> Vec<Self> {
match self {
Self::OperationsView => vec![Self::OperationsView, Self::ConnectorsView],
Self::OperationsManage => vec![
Self::OperationsView,
Self::OperationsManage,
Self::ConnectorsView,
],
Self::ConnectorsView => vec![Self::ConnectorsView],
Self::ConnectorsManage => vec![Self::ConnectorsView, Self::ConnectorsManage],
Self::WorkflowsView => vec![Self::WorkflowsView, Self::ConnectorsView],
Self::WorkflowsManage => vec![
Self::WorkflowsView,
Self::WorkflowsManage,
Self::ConnectorsView,
],
Self::AnalyticsView => vec![Self::AnalyticsView, Self::OperationsView],
Self::UsersView => vec![Self::UsersView],
Self::UsersManage => {
vec![Self::UsersView, Self::UsersManage]
}
Self::ReconOpsView => vec![Self::ReconOpsView],
Self::ReconOpsManage => vec![Self::ReconOpsView, Self::ReconOpsManage],
Self::ReconReportsView => vec![Self::ReconReportsView],
Self::ReconReportsManage => vec![Self::ReconReportsView, Self::ReconReportsManage],
Self::MerchantDetailsView => vec![Self::MerchantDetailsView],
Self::MerchantDetailsManage => {
vec![Self::MerchantDetailsView, Self::MerchantDetailsManage]
}
Self::OrganizationManage => vec![Self::OrganizationManage],
Self::AccountView => vec![Self::AccountView],
Self::AccountManage => vec![Self::AccountView, Self::AccountManage],
Self::InternalManage => vec![Self::InternalManage],
Self::ThemeView => vec![Self::ThemeView, Self::AccountView],
Self::ThemeManage => vec![Self::ThemeManage, Self::AccountView],
}
}
}
pub trait ParentGroupExt {
fn resources(&self) -> Vec<Resource>;
fn get_descriptions_for_groups(
entity_type: EntityType,
groups: Vec<PermissionGroup>,
) -> Option<HashMap<ParentGroup, String>>;
fn get_available_scopes(&self) -> Vec<PermissionScope>;
}
impl ParentGroupExt for ParentGroup {
fn resources(&self) -> Vec<Resource> {
match self {
Self::Operations => OPERATIONS.to_vec(),
Self::Connectors => CONNECTORS.to_vec(),
Self::Workflows => WORKFLOWS.to_vec(),
Self::Analytics => ANALYTICS.to_vec(),
Self::Users => USERS.to_vec(),
Self::Account => ACCOUNT.to_vec(),
Self::ReconOps => RECON_OPS.to_vec(),
Self::ReconReports => RECON_REPORTS.to_vec(),
Self::Internal => INTERNAL.to_vec(),
Self::Theme => THEME.to_vec(),
}
}
fn get_descriptions_for_groups(
entity_type: EntityType,
groups: Vec<PermissionGroup>,
) -> Option<HashMap<Self, String>> {
let descriptions_map = Self::iter()
.filter_map(|parent| {
if !groups.iter().any(|group| group.parent() == parent) {
return None;
}
let filtered_resources: Vec<_> = parent
.resources()
.into_iter()
.filter(|res| res.entities().iter().any(|entity| entity <= &entity_type))
.collect();
if filtered_resources.is_empty() {
return None;
}
let description = filtered_resources
.iter()
.map(|res| permissions::get_resource_name(*res, entity_type))
.collect::<Option<Vec<_>>>()?
.join(", ");
Some((parent, description))
})
.collect::<HashMap<_, _>>();
descriptions_map
.is_empty()
.not()
.then_some(descriptions_map)
}
fn get_available_scopes(&self) -> Vec<PermissionScope> {
PermissionGroup::iter()
.filter(|group| group.parent() == *self)
.map(|group| group.scope())
.collect()
}
}
pub static OPERATIONS: [Resource; 8] = [
Resource::Payment,
Resource::Refund,
Resource::Mandate,
Resource::Dispute,
Resource::Customer,
Resource::Payout,
Resource::Report,
Resource::Account,
];
pub static CONNECTORS: [Resource; 2] = [Resource::Connector, Resource::Account];
pub static WORKFLOWS: [Resource; 5] = [
Resource::Routing,
Resource::ThreeDsDecisionManager,
Resource::SurchargeDecisionManager,
Resource::Account,
Resource::RevenueRecovery,
];
pub static ANALYTICS: [Resource; 3] = [Resource::Analytics, Resource::Report, Resource::Account];
pub static USERS: [Resource; 2] = [Resource::User, Resource::Account];
pub static ACCOUNT: [Resource; 3] = [Resource::Account, Resource::ApiKey, Resource::WebhookEvent];
pub static RECON_OPS: [Resource; 8] = [
Resource::ReconToken,
Resource::ReconFiles,
Resource::ReconUpload,
Resource::RunRecon,
Resource::ReconConfig,
Resource::ReconAndSettlementAnalytics,
Resource::ReconReports,
Resource::Account,
];
pub static INTERNAL: [Resource; 1] = [Resource::InternalConnector];
pub static RECON_REPORTS: [Resource; 4] = [
Resource::ReconToken,
Resource::ReconAndSettlementAnalytics,
Resource::ReconReports,
Resource::Account,
];
pub static THEME: [Resource; 1] = [Resource::Theme];
|
crates/router/src/services/authorization/permission_groups.rs
|
router
|
full_file
| null | null | null | 1,786
| null | null | null | null | null | null | null |
// Function: find_by_merchant_id_connector_name
// File: crates/diesel_models/src/query/merchant_connector_account.rs
// Module: diesel_models
pub fn find_by_merchant_id_connector_name(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
connector_name: &str,
) -> StorageResult<Vec<Self>>
|
crates/diesel_models/src/query/merchant_connector_account.rs
|
diesel_models
|
function_signature
| null | null | null | 80
|
find_by_merchant_id_connector_name
| null | null | null | null | null | null |
// Struct: BankAccountIban
// File: crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BankAccountIban
|
crates/hyperswitch_connectors/src/connectors/worldline/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
BankAccountIban
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// File: crates/router/tests/connectors/gpayments.rs
// Module: router
use router::types;
use test_utils::connector_auth;
use crate::utils::{self, ConnectorActions};
#[derive(Clone, Copy)]
#[allow(dead_code)]
struct GpaymentsTest;
impl ConnectorActions for GpaymentsTest {}
impl utils::Connector for GpaymentsTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Gpayments;
utils::construct_connector_data_old(
Box::new(Gpayments::new()),
types::Connector::Threedsecureio,
// Added as Dummy connector as template code is added for future usage
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.gpayments
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"gpayments".to_string()
}
}
|
crates/router/tests/connectors/gpayments.rs
|
router
|
full_file
| null | null | null | 230
| null | null | null | null | null | null | null |
// Struct: BankOfAmericaPaymentsRequest
// File: crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BankOfAmericaPaymentsRequest
|
crates/hyperswitch_connectors/src/connectors/bankofamerica/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
BankOfAmericaPaymentsRequest
| 0
|
[] | 54
| null | null | null | null | null | null | null |
// File: crates/storage_impl/src/metrics.rs
// Module: storage_impl
use router_env::{counter_metric, gauge_metric, global_meter};
global_meter!(GLOBAL_METER, "ROUTER_API");
counter_metric!(KV_MISS, GLOBAL_METER); // No. of KV misses
// Metrics for KV
counter_metric!(KV_OPERATION_SUCCESSFUL, GLOBAL_METER);
counter_metric!(KV_OPERATION_FAILED, GLOBAL_METER);
counter_metric!(KV_PUSHED_TO_DRAINER, GLOBAL_METER);
counter_metric!(KV_FAILED_TO_PUSH_TO_DRAINER, GLOBAL_METER);
counter_metric!(KV_SOFT_KILL_ACTIVE_UPDATE, GLOBAL_METER);
// Metrics for In-memory cache
gauge_metric!(IN_MEMORY_CACHE_ENTRY_COUNT, GLOBAL_METER);
counter_metric!(IN_MEMORY_CACHE_HIT, GLOBAL_METER);
counter_metric!(IN_MEMORY_CACHE_MISS, GLOBAL_METER);
counter_metric!(IN_MEMORY_CACHE_EVICTION_COUNT, GLOBAL_METER);
|
crates/storage_impl/src/metrics.rs
|
storage_impl
|
full_file
| null | null | null | 192
| null | null | null | null | null | null | null |
// Struct: MandateRevokeFlowData
// File: crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct MandateRevokeFlowData
|
crates/hyperswitch_domain_models/src/router_data_v2/flow_common_types.rs
|
hyperswitch_domain_models
|
struct_definition
|
MandateRevokeFlowData
| 0
|
[] | 54
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorSpecifications for for Thunes
// File: crates/hyperswitch_connectors/src/connectors/thunes.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)
impl ConnectorSpecifications for for Thunes
|
crates/hyperswitch_connectors/src/connectors/thunes.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 53
| null |
Thunes
|
ConnectorSpecifications for
| 3
| 0
| null | null |
// Trait: PaymentIntentFilterAnalytics
// File: crates/analytics/src/payment_intents/filters.rs
// Module: analytics
pub trait PaymentIntentFilterAnalytics: LoadRow<PaymentIntentFilterRow>
|
crates/analytics/src/payment_intents/filters.rs
|
analytics
|
trait_definition
| null | null | null | 42
| null | null |
PaymentIntentFilterAnalytics
| null | null | null | null |
// Implementation: impl auth_service::AuthServiceLinkToken for for Plaid
// File: crates/pm_auth/src/connector/plaid.rs
// Module: pm_auth
// Methods: 0 total (0 public)
impl auth_service::AuthServiceLinkToken for for Plaid
|
crates/pm_auth/src/connector/plaid.rs
|
pm_auth
|
impl_block
| null | null | null | 55
| null |
Plaid
|
auth_service::AuthServiceLinkToken for
| 0
| 0
| null | null |
// Struct: AirwallexPaymentsRequest
// File: crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AirwallexPaymentsRequest
|
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
AirwallexPaymentsRequest
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Struct: RefundDistributionRow
// File: crates/analytics/src/refunds/distribution.rs
// Module: analytics
// Implementations: 0
pub struct RefundDistributionRow
|
crates/analytics/src/refunds/distribution.rs
|
analytics
|
struct_definition
|
RefundDistributionRow
| 0
|
[] | 39
| null | null | null | null | null | null | null |
// Function: get_sdk_event_metrics
// File: crates/analytics/src/lib.rs
// Module: analytics
pub fn get_sdk_event_metrics(
&self,
metric: &SdkEventMetrics,
dimensions: &[SdkEventDimensions],
publishable_key: &str,
filters: &SdkEventFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
) -> types::MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>>
|
crates/analytics/src/lib.rs
|
analytics
|
function_signature
| null | null | null | 104
|
get_sdk_event_metrics
| null | null | null | null | null | null |
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile,
platform_merchant_account: None,
};
Ok((
auth.clone(),
AuthenticationType::MerchantId {
merchant_id: auth.merchant_account.get_id().clone(),
},
))
}
}
/// InternalMerchantIdProfileIdAuth authentication which first tries to authenticate using `X-Internal-API-Key`,
/// `X-Merchant-Id` and `X-Profile-Id` headers. If any of these headers are missing,
/// it falls back to the provided authentication mechanism.
#[cfg(feature = "v1")]
pub struct InternalMerchantIdProfileIdAuth<F>(pub F);
#[cfg(feature = "v1")]
#[async_trait]
impl<A, F> AuthenticateAndFetch<AuthenticationData, A> for InternalMerchantIdProfileIdAuth<F>
where
A: SessionStateInfo + Sync + Send,
F: AuthenticateAndFetch<AuthenticationData, A> + Sync + Send,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
if !state.conf().internal_merchant_id_profile_id_auth.enabled {
return self.0.authenticate_and_fetch(request_headers, state).await;
}
let merchant_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)
.ok();
let internal_api_key = HeaderMapStruct::new(request_headers)
.get_header_value_by_key(headers::X_INTERNAL_API_KEY)
.map(|s| s.to_string());
let profile_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)
.ok();
if let (Some(internal_api_key), Some(merchant_id), Some(profile_id)) =
(internal_api_key, merchant_id, profile_id)
{
let config = state.conf();
if internal_api_key
!= *config
.internal_merchant_id_profile_id_auth
.internal_api_key
.peek()
{
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Internal API key authentication failed");
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let _profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile_id: Some(profile_id.clone()),
platform_merchant_account: None,
};
Ok((
auth.clone(),
AuthenticationType::InternalMerchantIdProfileId {
merchant_id,
profile_id: Some(profile_id),
},
))
} else {
Ok(self
.0
.authenticate_and_fetch(request_headers, state)
.await?)
}
}
}
#[derive(Debug)]
#[cfg(feature = "v2")]
pub struct MerchantIdAndProfileIdAuth {
pub merchant_id: id_type::MerchantId,
pub profile_id: id_type::ProfileId,
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for MerchantIdAndProfileIdAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
if state.conf().platform.enabled {
throw_error_if_platform_merchant_authentication_required(request_headers)?;
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&self.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&self.merchant_id,
&self.profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(key_manager_state, &self.merchant_id, &key_store)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile,
platform_merchant_account: None,
};
Ok((
auth.clone(),
AuthenticationType::MerchantId {
merchant_id: auth.merchant_account.get_id().clone(),
},
))
}
}
#[derive(Debug)]
#[cfg(feature = "v2")]
pub struct PublishableKeyAndProfileIdAuth {
pub publishable_key: String,
pub profile_id: id_type::ProfileId,
}
#[async_trait]
#[cfg(feature = "v2")]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for PublishableKeyAndProfileIdAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
_request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let key_manager_state = &(&state.session_state()).into();
let (merchant_account, key_store) = state
.store()
.find_merchant_account_by_publishable_key(
key_manager_state,
self.publishable_key.as_str(),
)
.await
.map_err(|e| {
if e.current_context().is_db_not_found() {
e.change_context(errors::ApiErrorResponse::Unauthorized)
} else {
e.change_context(errors::ApiErrorResponse::InternalServerError)
}
})?;
let profile = state
.store()
.find_business_profile_by_profile_id(key_manager_state, &key_store, &self.profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: self.profile_id.get_string_repr().to_owned(),
})?;
let merchant_id = merchant_account.get_id().clone();
Ok((
AuthenticationData {
merchant_account,
key_store,
profile,
platform_merchant_account: None,
},
AuthenticationType::PublishableKey { merchant_id },
))
}
}
/// Take api-key from `Authorization` header
#[cfg(feature = "v2")]
#[derive(Debug)]
pub struct V2ApiKeyAuth {
pub is_connected_allowed: bool,
pub is_platform_allowed: bool,
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for V2ApiKeyAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let header_map_struct = HeaderMapStruct::new(request_headers);
let auth_string = header_map_struct.get_auth_string_from_header()?;
let api_key = auth_string
.split(',')
.find_map(|part| part.trim().strip_prefix("api-key="))
.ok_or_else(|| {
report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Unable to parse api_key")
})?;
if api_key.is_empty() {
return Err(errors::ApiErrorResponse::Unauthorized)
.attach_printable("API key is empty");
}
let profile_id = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::ProfileId>(headers::X_PROFILE_ID)?;
let api_key = api_keys::PlaintextApiKey::from(api_key);
let hash_key = {
let config = state.conf();
config.api_keys.get_inner().get_hash_key()?
};
let hashed_api_key = api_key.keyed_hash(hash_key.peek());
let stored_api_key = state
.store()
.find_api_key_by_hash_optional(hashed_api_key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError) // If retrieve failed
.attach_printable("Failed to retrieve API key")?
.ok_or(report!(errors::ApiErrorResponse::Unauthorized)) // If retrieve returned `None`
.attach_printable("Merchant not authenticated")?;
if stored_api_key
.expires_at
.map(|expires_at| expires_at < date_time::now())
.unwrap_or(false)
{
return Err(report!(errors::ApiErrorResponse::Unauthorized))
.attach_printable("API key has expired");
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&stored_api_key.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
// Get connected merchant account if API call is done by Platform merchant account on behalf of connected merchant account
let (merchant, platform_merchant_account) = if state.conf().platform.enabled {
get_platform_merchant_account(state, request_headers, merchant).await?
} else {
(merchant, None)
};
if platform_merchant_account.is_some() && !self.is_platform_allowed {
return Err(report!(
errors::ApiErrorResponse::PlatformAccountAuthNotSupported
))
.attach_printable("Platform not authorized to access the resource");
}
let key_store = if platform_merchant_account.is_some() {
state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
merchant.get_id(),
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Failed to fetch merchant key store for the merchant id")?
} else {
key_store
};
let profile = state
.store()
.find_business_profile_by_profile_id(key_manager_state, &key_store, &profile_id)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account,
key_store,
profile,
};
Ok((
auth.clone(),
AuthenticationType::ApiKey {
merchant_id: auth.merchant_account.get_id().clone(),
key_id: stored_api_key.key_id,
},
))
}
}
#[cfg(feature = "v2")]
#[derive(Debug)]
pub struct V2ClientAuth(pub common_utils::types::authentication::ResourceId);
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for V2ClientAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let header_map_struct = HeaderMapStruct::new(request_headers);
let auth_string = header_map_struct.get_auth_string_from_header()?;
let publishable_key = auth_string
.split(',')
.find_map(|part| part.trim().strip_prefix("publishable-key="))
.ok_or_else(|| {
report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Unable to parse publishable_key")
})?;
let client_secret = auth_string
.split(',')
.find_map(|part| part.trim().strip_prefix("client-secret="))
.ok_or_else(|| {
report!(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Unable to parse client_secret")
})?;
let key_manager_state: &common_utils::types::keymanager::KeyManagerState =
&(&state.session_state()).into();
let db_client_secret: diesel_models::ClientSecretType = state
.store()
.get_client_secret(client_secret)
.await
.change_context(errors::ApiErrorResponse::Unauthorized)
.attach_printable("Invalid ephemeral_key")?;
let profile_id =
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
match (&self.0, &db_client_secret.resource_id) {
(
common_utils::types::authentication::ResourceId::Payment(self_id),
common_utils::types::authentication::ResourceId::Payment(db_id),
) => {
fp_utils::when(self_id != db_id, || {
Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized)
});
}
(
common_utils::types::authentication::ResourceId::Customer(self_id),
common_utils::types::authentication::ResourceId::Customer(db_id),
) => {
fp_utils::when(self_id != db_id, || {
Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized)
});
}
(
common_utils::types::authentication::ResourceId::PaymentMethodSession(self_id),
common_utils::types::authentication::ResourceId::PaymentMethodSession(db_id),
) => {
fp_utils::when(self_id != db_id, || {
Err::<(), errors::ApiErrorResponse>(errors::ApiErrorResponse::Unauthorized)
});
}
_ => {
return Err(errors::ApiErrorResponse::Unauthorized.into());
}
}
let (merchant_account, key_store) = state
.store()
.find_merchant_account_by_publishable_key(key_manager_state, publishable_key)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant_id = merchant_account.get_id().clone();
if db_client_secret.merchant_id != merchant_id {
return Err(errors::ApiErrorResponse::Unauthorized.into());
}
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
Ok((
AuthenticationData {
merchant_account,
key_store,
profile,
platform_merchant_account: None,
},
AuthenticationType::PublishableKey { merchant_id },
))
}
}
#[cfg(feature = "v2")]
pub fn api_or_client_auth<'a, T, A>(
api_auth: &'a dyn AuthenticateAndFetch<T, A>,
client_auth: &'a dyn AuthenticateAndFetch<T, A>,
headers: &HeaderMap,
) -> &'a dyn AuthenticateAndFetch<T, A>
where
{
if let Ok(val) = HeaderMapStruct::new(headers).get_auth_string_from_header() {
if val.trim().starts_with("api-key=") {
api_auth
} else {
client_auth
}
} else {
api_auth
}
}
#[cfg(feature = "v2")]
pub fn api_or_client_or_jwt_auth<'a, T, A>(
api_auth: &'a dyn AuthenticateAndFetch<T, A>,
client_auth: &'a dyn AuthenticateAndFetch<T, A>,
jwt_auth: &'a dyn AuthenticateAndFetch<T, A>,
headers: &HeaderMap,
) -> &'a dyn AuthenticateAndFetch<T, A>
where
{
if let Ok(val) = HeaderMapStruct::new(headers).get_auth_string_from_header() {
if val.trim().starts_with("api-key=") {
api_auth
} else if is_jwt_auth(headers) {
jwt_auth
} else {
client_auth
}
} else {
api_auth
}
}
#[derive(Debug)]
pub struct PublishableKeyAuth;
#[cfg(feature = "partial-auth")]
impl GetAuthType for PublishableKeyAuth {
fn get_auth_type(&self) -> detached::PayloadType {
detached::PayloadType::PublishableKey
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for PublishableKeyAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
if state.conf().platform.enabled {
throw_error_if_platform_merchant_authentication_required(request_headers)?;
}
let publishable_key =
get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;
let key_manager_state = &(&state.session_state()).into();
state
.store()
.find_merchant_account_by_publishable_key(key_manager_state, publishable_key)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)
.map(|(merchant_account, key_store)| {
let merchant_id = merchant_account.get_id().clone();
(
AuthenticationData {
merchant_account,
platform_merchant_account: None,
key_store,
profile_id: None,
},
AuthenticationType::PublishableKey { merchant_id },
)
})
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for PublishableKeyAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let publishable_key =
get_api_key(request_headers).change_context(errors::ApiErrorResponse::Unauthorized)?;
let key_manager_state = &(&state.session_state()).into();
let profile_id =
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
let (merchant_account, key_store) = state
.store()
.find_merchant_account_by_publishable_key(key_manager_state, publishable_key)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant_id = merchant_account.get_id().clone();
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
Ok((
AuthenticationData {
merchant_account,
key_store,
profile,
platform_merchant_account: None,
},
AuthenticationType::PublishableKey { merchant_id },
))
}
}
#[derive(Debug)]
pub(crate) struct JWTAuth {
pub permission: Permission,
}
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for JWTAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.permission, &role_info)?;
Ok((
(),
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "olap")]
#[async_trait]
impl<A> AuthenticateAndFetch<UserFromToken, A> for JWTAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(UserFromToken, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.permission, &role_info)?;
Ok((
UserFromToken {
user_id: payload.user_id.clone(),
merchant_id: payload.merchant_id.clone(),
org_id: payload.org_id,
role_id: payload.role_id,
profile_id: payload.profile_id,
tenant_id: payload.tenant_id,
},
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "olap")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationDataWithMultipleProfiles, A> for JWTAuth
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationDataWithMultipleProfiles, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.permission, &role_info)?;
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.change_context(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.change_context(errors::ApiErrorResponse::InvalidJwtToken)?;
Ok((
AuthenticationDataWithMultipleProfiles {
key_store,
merchant_account: merchant,
profile_id_list: None,
},
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
pub struct JWTAuthOrganizationFromRoute {
pub organization_id: id_type::OrganizationId,
pub required_permission: Permission,
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<Option<AuthenticationDataWithOrg>, A> for JWTAuthOrganizationFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(Option<AuthenticationDataWithOrg>, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
// Check if token has access to Organization that has been requested in the route
if payload.org_id != self.organization_id {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
Ok((
Some(AuthenticationDataWithOrg {
organization_id: payload.org_id.clone(),
}),
AuthenticationType::OrganizationJwt {
org_id: payload.org_id,
user_id: payload.user_id,
},
))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for JWTAuthOrganizationFromRoute
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
// Check if token has access to Organization that has been requested in the route
if payload.org_id != self.organization_id {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
Ok((
(),
AuthenticationType::OrganizationJwt {
org_id: payload.org_id,
user_id: payload.user_id,
},
))
}
}
pub struct JWTAuthMerchantFromRoute {
pub merchant_id: id_type::MerchantId,
pub required_permission: Permission,
}
pub struct JWTAuthMerchantFromHeader {
pub required_permission: Permission,
}
#[async_trait]
impl<A> AuthenticateAndFetch<(), A> for JWTAuthMerchantFromHeader
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<((), AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let merchant_id_from_header = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
// Check if token has access to MerchantId that has been requested through headers
if payload.merchant_id != merchant_id_from_header {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
Ok((
(),
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthMerchantFromHeader
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let merchant_id_from_header = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
// Check if token has access to MerchantId that has been requested through headers
if payload.merchant_id != merchant_id_from_header {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let auth = AuthenticationData {
merchant_account: merchant,
platform_merchant_account: None,
key_store,
profile_id: Some(payload.profile_id),
};
Ok((
auth,
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "v1")]
#[async_trait]
impl<A> AuthenticateAndFetch<Option<AuthenticationDataWithOrg>, A> for JWTAuthMerchantFromHeader
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(Option<AuthenticationDataWithOrg>, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
authorization::check_tenant(
payload.tenant_id.clone(),
&state.session_state().tenant.tenant_id,
)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let merchant_id_from_header = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
// Check if token has access to MerchantId that has been requested through headers
if payload.merchant_id != merchant_id_from_header {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
let auth = Some(AuthenticationDataWithOrg {
organization_id: payload.org_id,
});
Ok((
auth,
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationData, A> for JWTAuthMerchantFromHeader
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationData, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
let profile_id =
get_id_type_by_key_from_headers(headers::X_PROFILE_ID.to_string(), request_headers)?
.get_required_value(headers::X_PROFILE_ID)?;
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let merchant_id_from_header = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
// Check if token has access to MerchantId that has been requested through headers
if payload.merchant_id != merchant_id_from_header {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let profile = state
.store()
.find_business_profile_by_merchant_id_profile_id(
key_manager_state,
&key_store,
&payload.merchant_id,
&profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::Unauthorized)?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant account for the merchant id")?;
let auth = AuthenticationData {
merchant_account: merchant,
key_store,
profile,
platform_merchant_account: None,
};
Ok((
auth,
AuthenticationType::MerchantJwt {
merchant_id: payload.merchant_id,
user_id: Some(payload.user_id),
},
))
}
}
#[cfg(feature = "v2")]
#[async_trait]
impl<A> AuthenticateAndFetch<AuthenticationDataWithoutProfile, A> for JWTAuthMerchantFromHeader
where
A: SessionStateInfo + Sync,
{
async fn authenticate_and_fetch(
&self,
request_headers: &HeaderMap,
state: &A,
) -> RouterResult<(AuthenticationDataWithoutProfile, AuthenticationType)> {
let payload = parse_jwt_payload::<A, AuthToken>(request_headers, state).await?;
if payload.check_in_blacklist(state).await? {
return Err(errors::ApiErrorResponse::InvalidJwtToken.into());
}
let role_info = authorization::get_role_info(state, &payload).await?;
authorization::check_permission(self.required_permission, &role_info)?;
let merchant_id_from_header = HeaderMapStruct::new(request_headers)
.get_id_type_from_header::<id_type::MerchantId>(headers::X_MERCHANT_ID)?;
// Check if token has access to MerchantId that has been requested through headers
if payload.merchant_id != merchant_id_from_header {
return Err(report!(errors::ApiErrorResponse::InvalidJwtToken));
}
let key_manager_state = &(&state.session_state()).into();
let key_store = state
.store()
.get_merchant_key_store_by_merchant_id(
key_manager_state,
&payload.merchant_id,
&state.store().get_master_key().to_vec().into(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::InvalidJwtToken)
.attach_printable("Failed to fetch merchant key store for the merchant id")?;
let merchant = state
.store()
.find_merchant_account_by_merchant_id(
key_manager_state,
|
crates/router/src/services/authentication.rs#chunk2
|
router
|
chunk
| null | null | null | 8,186
| null | null | null | null | null | null | null |
// Struct: ChannelProperties
// File: crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ChannelProperties
|
crates/hyperswitch_connectors/src/connectors/xendit/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ChannelProperties
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Function: list_blocklist_entries
// File: crates/router/src/core/blocklist.rs
// Module: router
pub fn list_blocklist_entries(
state: SessionState,
merchant_context: domain::MerchantContext,
query: api_blocklist::ListBlocklistQuery,
) -> RouterResponse<Vec<api_blocklist::BlocklistResponse>>
|
crates/router/src/core/blocklist.rs
|
router
|
function_signature
| null | null | null | 72
|
list_blocklist_entries
| null | null | null | null | null | null |
// File: crates/router/src/routes/user/theme.rs
// Module: router
// Public functions: 13
use actix_multipart::form::MultipartForm;
use actix_web::{web, HttpRequest, HttpResponse};
use api_models::user::theme as theme_api;
use common_utils::types::user::ThemeLineage;
use masking::Secret;
use router_env::Flow;
use crate::{
core::{api_locking, user::theme as theme_core},
routes::AppState,
services::{api, authentication as auth, authorization::permissions::Permission},
};
pub async fn get_theme_using_lineage(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<ThemeLineage>,
) -> HttpResponse {
let flow = Flow::GetThemeUsingLineage;
let lineage = query.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
lineage,
|state, _, lineage, _| theme_core::get_theme_using_lineage(state, lineage),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_theme_using_theme_id(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::GetThemeUsingThemeId;
let payload = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| theme_core::get_theme_using_theme_id(state, payload),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn upload_file_to_theme_storage(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
MultipartForm(payload): MultipartForm<theme_api::UploadFileAssetData>,
) -> HttpResponse {
let flow = Flow::UploadFileToThemeStorage;
let theme_id = path.into_inner();
let payload = theme_api::UploadFileRequest {
asset_name: payload.asset_name.into_inner(),
asset_data: Secret::new(payload.asset_data.data.to_vec()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| {
theme_core::upload_file_to_theme_storage(state, theme_id.clone(), payload)
},
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn create_theme(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<theme_api::CreateThemeRequest>,
) -> HttpResponse {
let flow = Flow::CreateTheme;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| theme_core::create_theme(state, payload),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn update_theme(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
payload: web::Json<theme_api::UpdateThemeRequest>,
) -> HttpResponse {
let flow = Flow::UpdateTheme;
let theme_id = path.into_inner();
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, _, payload, _| theme_core::update_theme(state, theme_id.clone(), payload),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn delete_theme(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::DeleteTheme;
let theme_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
theme_id,
|state, _, theme_id, _| theme_core::delete_theme(state, theme_id),
&auth::AdminApiAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn create_user_theme(
state: web::Data<AppState>,
req: HttpRequest,
payload: web::Json<theme_api::CreateUserThemeRequest>,
) -> HttpResponse {
let flow = Flow::CreateUserTheme;
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, user: auth::UserFromToken, payload, _| {
theme_core::create_user_theme(state, user, payload)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_user_theme_using_theme_id(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::GetUserThemeUsingThemeId;
let payload = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, user: auth::UserFromToken, payload, _| {
theme_core::get_user_theme_using_theme_id(state, user, payload)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn update_user_theme(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
payload: web::Json<theme_api::UpdateThemeRequest>,
) -> HttpResponse {
let flow = Flow::UpdateUserTheme;
let theme_id = path.into_inner();
let payload = payload.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, user: auth::UserFromToken, payload, _| {
theme_core::update_user_theme(state, theme_id.clone(), user, payload)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn delete_user_theme(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> HttpResponse {
let flow = Flow::DeleteUserTheme;
let theme_id = path.into_inner();
Box::pin(api::server_wrap(
flow,
state,
&req,
theme_id,
|state, user: auth::UserFromToken, theme_id, _| {
theme_core::delete_user_theme(state, user, theme_id)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn upload_file_to_user_theme_storage(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
MultipartForm(payload): MultipartForm<theme_api::UploadFileAssetData>,
) -> HttpResponse {
let flow = Flow::UploadFileToUserThemeStorage;
let theme_id = path.into_inner();
let payload = theme_api::UploadFileRequest {
asset_name: payload.asset_name.into_inner(),
asset_data: Secret::new(payload.asset_data.data.to_vec()),
};
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, user: auth::UserFromToken, payload, _| {
theme_core::upload_file_to_user_theme_storage(state, theme_id.clone(), user, payload)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeWrite,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn list_all_themes_in_lineage(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<theme_api::EntityTypeQueryParam>,
) -> HttpResponse {
let flow = Flow::ListAllThemesInLineage;
let entity_type = query.into_inner().entity_type;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, user: auth::UserFromToken, _payload, _| {
theme_core::list_all_themes_in_lineage(state, user, entity_type)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
pub async fn get_user_theme_using_lineage(
state: web::Data<AppState>,
req: HttpRequest,
query: web::Query<theme_api::EntityTypeQueryParam>,
) -> HttpResponse {
let flow = Flow::GetUserThemeUsingLineage;
let entity_type = query.into_inner().entity_type;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, user: auth::UserFromToken, _payload, _| {
theme_core::get_user_theme_using_lineage(state, user, entity_type)
},
&auth::JWTAuth {
permission: Permission::OrganizationThemeRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/user/theme.rs
|
router
|
full_file
| null | null | null | 2,083
| null | null | null | null | null | null | null |
// Implementation: impl Chargebee
// File: crates/hyperswitch_connectors/src/connectors/chargebee.rs
// Module: hyperswitch_connectors
// Methods: 1 total (1 public)
impl Chargebee
|
crates/hyperswitch_connectors/src/connectors/chargebee.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 46
| null |
Chargebee
| null | 1
| 1
| null | null |
// Implementation: impl ContractBasedRoutingConfigBody
// File: crates/api_models/src/routing.rs
// Module: api_models
// Methods: 1 total (1 public)
impl ContractBasedRoutingConfigBody
|
crates/api_models/src/routing.rs
|
api_models
|
impl_block
| null | null | null | 43
| null |
ContractBasedRoutingConfigBody
| null | 1
| 1
| null | null |
// Struct: MerchantInformation
// File: crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct MerchantInformation
|
crates/hyperswitch_connectors/src/connectors/peachpayments/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
MerchantInformation
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Implementation: impl FlattenedPaymentMethodsEnabled
// File: crates/hyperswitch_domain_models/src/merchant_connector_account.rs
// Module: hyperswitch_domain_models
// Methods: 1 total (1 public)
impl FlattenedPaymentMethodsEnabled
|
crates/hyperswitch_domain_models/src/merchant_connector_account.rs
|
hyperswitch_domain_models
|
impl_block
| null | null | null | 53
| null |
FlattenedPaymentMethodsEnabled
| null | 1
| 1
| null | null |
// Struct: Products
// File: crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Products
|
crates/hyperswitch_connectors/src/connectors/signifyd/transformers/api.rs
|
hyperswitch_connectors
|
struct_definition
|
Products
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Function: retrieve_routing_config_under_profile
// File: crates/router/src/core/routing.rs
// Module: router
pub fn retrieve_routing_config_under_profile(
state: SessionState,
merchant_context: domain::MerchantContext,
query_params: RoutingRetrieveQuery,
profile_id: common_utils::id_type::ProfileId,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::LinkedRoutingConfigRetrieveResponse>
|
crates/router/src/core/routing.rs
|
router
|
function_signature
| null | null | null | 93
|
retrieve_routing_config_under_profile
| null | null | null | null | null | null |
// Struct: PaystackErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaystackErrorResponse
|
crates/hyperswitch_connectors/src/connectors/paystack/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaystackErrorResponse
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Struct: ErrorDetails
// File: crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ErrorDetails
|
crates/hyperswitch_connectors/src/connectors/paypal/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ErrorDetails
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Struct: NexixpayErrorBody
// File: crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NexixpayErrorBody
|
crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NexixpayErrorBody
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Function: insert
// File: crates/diesel_models/src/query/blocklist_lookup.rs
// Module: diesel_models
pub fn insert(self, conn: &PgPooledConn) -> StorageResult<BlocklistLookup>
|
crates/diesel_models/src/query/blocklist_lookup.rs
|
diesel_models
|
function_signature
| null | null | null | 45
|
insert
| null | null | null | null | null | null |
// Function: cors
// File: crates/router/src/cors.rs
// Module: router
pub fn cors(config: settings::CorsSettings) -> actix_cors::Cors
|
crates/router/src/cors.rs
|
router
|
function_signature
| null | null | null | 37
|
cors
| null | null | null | null | null | null |
// File: crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs
// Module: hyperswitch_domain_models
// Public structs: 5
use api_models::payments::Address;
use common_utils::id_type;
use crate::connector_endpoints;
#[derive(Debug, Clone)]
pub struct SubscriptionItem {
pub item_price_id: String,
pub quantity: Option<u32>,
}
#[derive(Debug, Clone)]
pub struct SubscriptionCreateRequest {
pub customer_id: id_type::CustomerId,
pub subscription_id: id_type::SubscriptionId,
pub subscription_items: Vec<SubscriptionItem>,
pub billing_address: Address,
pub auto_collection: SubscriptionAutoCollection,
pub connector_params: connector_endpoints::ConnectorParams,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SubscriptionAutoCollection {
On,
Off,
}
#[derive(Debug, Clone)]
pub struct GetSubscriptionPlansRequest {
pub limit: Option<u32>,
pub offset: Option<u32>,
}
#[derive(Debug, Clone)]
pub struct GetSubscriptionPlanPricesRequest {
pub plan_price_id: String,
}
#[derive(Debug, Clone)]
pub struct GetSubscriptionEstimateRequest {
pub price_id: String,
}
|
crates/hyperswitch_domain_models/src/router_request_types/subscriptions.rs
|
hyperswitch_domain_models
|
full_file
| null | null | null | 256
| null | null | null | null | null | null | null |
// Struct: NetworkTokenDetailsPaymentMethod
// File: crates/api_models/src/payment_methods.rs
// Module: api_models
// Implementations: 0
pub struct NetworkTokenDetailsPaymentMethod
|
crates/api_models/src/payment_methods.rs
|
api_models
|
struct_definition
|
NetworkTokenDetailsPaymentMethod
| 0
|
[] | 40
| null | null | null | null | null | null | null |
// Function: build
// File: crates/payment_methods/src/core/migration.rs
// Module: payment_methods
pub fn build(self) -> RecordMigrationStatus
|
crates/payment_methods/src/core/migration.rs
|
payment_methods
|
function_signature
| null | null | null | 32
|
build
| null | null | null | null | null | null |
// Implementation: impl api::RefundExecute for for Boku
// File: crates/hyperswitch_connectors/src/connectors/boku.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Boku
|
crates/hyperswitch_connectors/src/connectors/boku.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Boku
|
api::RefundExecute for
| 0
| 0
| null | null |
// Struct: PaypalSdkData
// File: crates/connector_configs/src/common_config.rs
// Module: connector_configs
// Implementations: 0
pub struct PaypalSdkData
|
crates/connector_configs/src/common_config.rs
|
connector_configs
|
struct_definition
|
PaypalSdkData
| 0
|
[] | 37
| null | null | null | null | null | null | null |
// Implementation: impl MultipleCaptureData
// File: crates/router/src/core/payments/types.rs
// Module: router
// Methods: 15 total (15 public)
impl MultipleCaptureData
|
crates/router/src/core/payments/types.rs
|
router
|
impl_block
| null | null | null | 41
| null |
MultipleCaptureData
| null | 15
| 15
| null | null |
// Module Structure
// File: crates/hyperswitch_domain_models/src/router_request_types.rs
// Module: hyperswitch_domain_models
// Public submodules:
pub mod authentication;
pub mod fraud_check;
pub mod revenue_recovery;
pub mod subscriptions;
pub mod unified_authentication_service;
|
crates/hyperswitch_domain_models/src/router_request_types.rs
|
hyperswitch_domain_models
|
module_structure
| null | null | null | 57
| null | null | null | null | null | 5
| 0
|
// File: crates/router/src/connection.rs
// Module: router
// Public functions: 5
use bb8::PooledConnection;
use diesel::PgConnection;
use error_stack::ResultExt;
use storage_impl::errors as storage_errors;
use crate::errors;
pub type PgPool = bb8::Pool<async_bb8_diesel::ConnectionManager<PgConnection>>;
pub type PgPooledConn = async_bb8_diesel::Connection<PgConnection>;
/// Creates a Redis connection pool for the specified Redis settings
/// # Panics
///
/// Panics if failed to create a redis pool
#[allow(clippy::expect_used)]
pub async fn redis_connection(
conf: &crate::configs::Settings,
) -> redis_interface::RedisConnectionPool {
redis_interface::RedisConnectionPool::new(&conf.redis)
.await
.expect("Failed to create Redis Connection Pool")
}
pub async fn pg_connection_read<T: storage_impl::DatabaseStore>(
store: &T,
) -> errors::CustomResult<
PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,
storage_errors::StorageError,
> {
// If only OLAP is enabled get replica pool.
#[cfg(all(feature = "olap", not(feature = "oltp")))]
let pool = store.get_replica_pool();
// If either one of these are true we need to get master pool.
// 1. Only OLTP is enabled.
// 2. Both OLAP and OLTP is enabled.
// 3. Both OLAP and OLTP is disabled.
#[cfg(any(
all(not(feature = "olap"), feature = "oltp"),
all(feature = "olap", feature = "oltp"),
all(not(feature = "olap"), not(feature = "oltp"))
))]
let pool = store.get_master_pool();
pool.get()
.await
.change_context(storage_errors::StorageError::DatabaseConnectionError)
}
pub async fn pg_accounts_connection_read<T: storage_impl::DatabaseStore>(
store: &T,
) -> errors::CustomResult<
PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,
storage_errors::StorageError,
> {
// If only OLAP is enabled get replica pool.
#[cfg(all(feature = "olap", not(feature = "oltp")))]
let pool = store.get_accounts_replica_pool();
// If either one of these are true we need to get master pool.
// 1. Only OLTP is enabled.
// 2. Both OLAP and OLTP is enabled.
// 3. Both OLAP and OLTP is disabled.
#[cfg(any(
all(not(feature = "olap"), feature = "oltp"),
all(feature = "olap", feature = "oltp"),
all(not(feature = "olap"), not(feature = "oltp"))
))]
let pool = store.get_accounts_master_pool();
pool.get()
.await
.change_context(storage_errors::StorageError::DatabaseConnectionError)
}
pub async fn pg_connection_write<T: storage_impl::DatabaseStore>(
store: &T,
) -> errors::CustomResult<
PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,
storage_errors::StorageError,
> {
// Since all writes should happen to master DB only choose master DB.
let pool = store.get_master_pool();
pool.get()
.await
.change_context(storage_errors::StorageError::DatabaseConnectionError)
}
pub async fn pg_accounts_connection_write<T: storage_impl::DatabaseStore>(
store: &T,
) -> errors::CustomResult<
PooledConnection<'_, async_bb8_diesel::ConnectionManager<PgConnection>>,
storage_errors::StorageError,
> {
// Since all writes should happen to master DB only choose master DB.
let pool = store.get_accounts_master_pool();
pool.get()
.await
.change_context(storage_errors::StorageError::DatabaseConnectionError)
}
|
crates/router/src/connection.rs
|
router
|
full_file
| null | null | null | 869
| 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.