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
⌀ |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
// Function: generate_org_dispute_report
// File: crates/router/src/analytics.rs
// Module: router
pub fn generate_org_dispute_report(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<ReportRequest>,
) -> impl Responder
|
crates/router/src/analytics.rs
|
router
|
function_signature
| null | null | null | 67
|
generate_org_dispute_report
| null | null | null | null | null | null |
// Struct: ProphetpayVoidRequest
// File: crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ProphetpayVoidRequest
|
crates/hyperswitch_connectors/src/connectors/prophetpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ProphetpayVoidRequest
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Implementation: impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for for ClickhouseClient
// File: crates/analytics/src/clickhouse.rs
// Module: analytics
// Methods: 0 total (0 public)
impl super::payment_intents::metrics::PaymentIntentMetricAnalytics for for ClickhouseClient
|
crates/analytics/src/clickhouse.rs
|
analytics
|
impl_block
| null | null | null | 67
| null |
ClickhouseClient
|
super::payment_intents::metrics::PaymentIntentMetricAnalytics for
| 0
| 0
| null | null |
// Function: new
// File: crates/hyperswitch_constraint_graph/src/types.rs
// Module: hyperswitch_constraint_graph
pub fn new(identifier: String) -> Self
|
crates/hyperswitch_constraint_graph/src/types.rs
|
hyperswitch_constraint_graph
|
function_signature
| null | null | null | 36
|
new
| null | null | null | null | null | null |
// Function: new
// File: crates/diesel_models/src/organization.rs
// Module: diesel_models
pub fn new(
id: id_type::OrganizationId,
organization_type: common_enums::OrganizationType,
organization_name: Option<String>,
) -> Self
|
crates/diesel_models/src/organization.rs
|
diesel_models
|
function_signature
| null | null | null | 58
|
new
| null | null | null | null | null | null |
// Struct: CardResponse
// File: crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct CardResponse
|
crates/hyperswitch_connectors/src/connectors/silverflow/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
CardResponse
| 0
|
[] | 46
| null | null | null | null | null | null | null |
// Function: get_decision
// File: crates/common_types/src/domain.rs
// Module: common_types
// Documentation: Retrieves the decision to be taken for auto retries flow.
pub fn get_decision(&self) -> common_enums::GsmDecision
|
crates/common_types/src/domain.rs
|
common_types
|
function_signature
| null | null | null | 51
|
get_decision
| null | null | null | null | null | null |
// File: crates/router/src/services/authorization/roles.rs
// Module: router
// Public functions: 15
// Public structs: 1
#[cfg(feature = "recon")]
use std::collections::HashMap;
use std::collections::HashSet;
#[cfg(feature = "recon")]
use api_models::enums::ReconPermissionScope;
use common_enums::{EntityType, PermissionGroup, Resource, RoleScope};
use common_utils::{errors::CustomResult, id_type};
#[cfg(feature = "recon")]
use super::permission_groups::{RECON_OPS, RECON_REPORTS};
use super::{permission_groups::PermissionGroupExt, permissions::Permission};
use crate::{core::errors, routes::SessionState};
pub mod predefined_roles;
#[derive(Clone, serde::Serialize, serde::Deserialize, Debug)]
pub struct RoleInfo {
role_id: String,
role_name: String,
groups: Vec<PermissionGroup>,
scope: RoleScope,
entity_type: EntityType,
is_invitable: bool,
is_deletable: bool,
is_updatable: bool,
is_internal: bool,
}
impl RoleInfo {
pub fn get_role_id(&self) -> &str {
&self.role_id
}
pub fn get_role_name(&self) -> &str {
&self.role_name
}
pub fn get_permission_groups(&self) -> Vec<PermissionGroup> {
self.groups
.iter()
.flat_map(|group| group.accessible_groups())
.collect::<HashSet<_>>()
.into_iter()
.collect()
}
pub fn get_scope(&self) -> RoleScope {
self.scope
}
pub fn get_entity_type(&self) -> EntityType {
self.entity_type
}
pub fn is_invitable(&self) -> bool {
self.is_invitable
}
pub fn is_deletable(&self) -> bool {
self.is_deletable
}
pub fn is_internal(&self) -> bool {
self.is_internal
}
pub fn is_updatable(&self) -> bool {
self.is_updatable
}
pub fn get_resources_set(&self) -> HashSet<Resource> {
self.get_permission_groups()
.iter()
.flat_map(|group| group.resources())
.collect()
}
pub fn check_permission_exists(&self, required_permission: Permission) -> bool {
required_permission.entity_type() <= self.entity_type
&& self.get_permission_groups().iter().any(|group| {
required_permission.scope() <= group.scope()
&& group.resources().contains(&required_permission.resource())
})
}
#[cfg(feature = "recon")]
pub fn get_recon_acl(&self) -> HashMap<Resource, ReconPermissionScope> {
let mut acl: HashMap<Resource, ReconPermissionScope> = HashMap::new();
let mut recon_resources = RECON_OPS.to_vec();
recon_resources.extend(RECON_REPORTS);
let recon_internal_resources = [Resource::ReconToken];
self.get_permission_groups()
.iter()
.for_each(|permission_group| {
permission_group.resources().iter().for_each(|resource| {
if recon_resources.contains(resource)
&& !recon_internal_resources.contains(resource)
{
let scope = match resource {
Resource::ReconAndSettlementAnalytics => ReconPermissionScope::Read,
_ => ReconPermissionScope::from(permission_group.scope()),
};
acl.entry(*resource)
.and_modify(|curr_scope| {
*curr_scope = if (*curr_scope) < scope {
scope
} else {
*curr_scope
}
})
.or_insert(scope);
}
})
});
acl
}
pub fn from_predefined_roles(role_id: &str) -> Option<Self> {
predefined_roles::PREDEFINED_ROLES.get(role_id).cloned()
}
pub async fn from_role_id_in_lineage(
state: &SessionState,
role_id: &str,
merchant_id: &id_type::MerchantId,
org_id: &id_type::OrganizationId,
profile_id: &id_type::ProfileId,
tenant_id: &id_type::TenantId,
) -> CustomResult<Self, errors::StorageError> {
if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) {
Ok(role.clone())
} else {
state
.global_store
.find_role_by_role_id_in_lineage(
role_id,
merchant_id,
org_id,
profile_id,
tenant_id,
)
.await
.map(Self::from)
}
}
// TODO: To evaluate whether we can omit org_id and tenant_id for this function
pub async fn from_role_id_org_id_tenant_id(
state: &SessionState,
role_id: &str,
org_id: &id_type::OrganizationId,
tenant_id: &id_type::TenantId,
) -> CustomResult<Self, errors::StorageError> {
if let Some(role) = predefined_roles::PREDEFINED_ROLES.get(role_id) {
Ok(role.clone())
} else {
state
.global_store
.find_by_role_id_org_id_tenant_id(role_id, org_id, tenant_id)
.await
.map(Self::from)
}
}
}
impl From<diesel_models::role::Role> for RoleInfo {
fn from(role: diesel_models::role::Role) -> Self {
Self {
role_id: role.role_id,
role_name: role.role_name,
groups: role.groups,
scope: role.scope,
entity_type: role.entity_type,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
}
}
}
|
crates/router/src/services/authorization/roles.rs
|
router
|
full_file
| null | null | null | 1,244
| null | null | null | null | null | null | null |
// Struct: PaymentIntent
// File: crates/hyperswitch_domain_models/src/payments.rs
// Module: hyperswitch_domain_models
// Implementations: 2
pub struct PaymentIntent
|
crates/hyperswitch_domain_models/src/payments.rs
|
hyperswitch_domain_models
|
struct_definition
|
PaymentIntent
| 2
|
[] | 40
| null | null | null | null | null | null | null |
// Struct: FiservPaymentMethod
// File: crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct FiservPaymentMethod
|
crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
FiservPaymentMethod
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Struct: UserNew
// File: crates/diesel_models/src/user.rs
// Module: diesel_models
// Implementations: 0
pub struct UserNew
|
crates/diesel_models/src/user.rs
|
diesel_models
|
struct_definition
|
UserNew
| 0
|
[] | 34
| null | null | null | null | null | null | null |
// Implementation: impl api::RefundExecute for for Worldpayvantiv
// File: crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundExecute for for Worldpayvantiv
|
crates/hyperswitch_connectors/src/connectors/worldpayvantiv.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 65
| null |
Worldpayvantiv
|
api::RefundExecute for
| 0
| 0
| null | null |
// Function: delete_surcharge_decision_manager_config
// File: crates/router/src/routes/routing.rs
// Module: router
pub fn delete_surcharge_decision_manager_config(
state: web::Data<AppState>,
req: HttpRequest,
) -> impl Responder
|
crates/router/src/routes/routing.rs
|
router
|
function_signature
| null | null | null | 54
|
delete_surcharge_decision_manager_config
| null | null | null | null | null | null |
// Implementation: impl api::PaymentAuthorize for for Braintree
// File: crates/hyperswitch_connectors/src/connectors/braintree.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentAuthorize for for Braintree
|
crates/hyperswitch_connectors/src/connectors/braintree.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 58
| null |
Braintree
|
api::PaymentAuthorize for
| 0
| 0
| null | null |
// Implementation: impl ConnectorValidation for for Tsys
// File: crates/hyperswitch_connectors/src/connectors/tsys.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl ConnectorValidation for for Tsys
|
crates/hyperswitch_connectors/src/connectors/tsys.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 53
| null |
Tsys
|
ConnectorValidation for
| 0
| 0
| null | null |
// Implementation: impl ResponseError for for BackfillError
// File: crates/api_models/src/revenue_recovery_data_backfill.rs
// Module: api_models
// Methods: 1 total (0 public)
impl ResponseError for for BackfillError
|
crates/api_models/src/revenue_recovery_data_backfill.rs
|
api_models
|
impl_block
| null | null | null | 51
| null |
BackfillError
|
ResponseError for
| 1
| 0
| null | null |
// Function: find_by_id
// File: crates/diesel_models/src/query/relay.rs
// Module: diesel_models
pub fn find_by_id(
conn: &PgPooledConn,
id: &common_utils::id_type::RelayId,
) -> StorageResult<Self>
|
crates/diesel_models/src/query/relay.rs
|
diesel_models
|
function_signature
| null | null | null | 62
|
find_by_id
| null | null | null | null | null | null |
// Struct: DataPaymentCaptureRequest
// File: crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct DataPaymentCaptureRequest
|
crates/hyperswitch_connectors/src/connectors/datatrans/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
DataPaymentCaptureRequest
| 0
|
[] | 50
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorValidation for for Paystack
// File: crates/hyperswitch_connectors/src/connectors/paystack.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl ConnectorValidation for for Paystack
|
crates/hyperswitch_connectors/src/connectors/paystack.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 53
| null |
Paystack
|
ConnectorValidation for
| 0
| 0
| null | null |
// Function: with_network_tokenization
// File: crates/router/src/core/payments.rs
// Module: router
pub fn with_network_tokenization(
mut self,
state: &SessionState,
is_network_token_with_ntid_flow: IsNtWithNtiFlow,
is_nt_with_ntid_supported_connector: bool,
payment_method_info: &domain::PaymentMethod,
) -> Self
|
crates/router/src/core/payments.rs
|
router
|
function_signature
| null | null | null | 85
|
with_network_tokenization
| null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/opayo.rs
// Module: hyperswitch_connectors
// Public functions: 1
// Public structs: 1
mod transformers;
use common_enums::enums;
use common_utils::{
errors::CustomResult,
ext_traits::BytesExt,
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, MinorUnit, MinorUnitForConnector},
};
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCaptureRouterData, PaymentsSyncRouterData,
RefundSyncRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{
PaymentsAuthorizeType, PaymentsCaptureType, PaymentsSyncType, RefundExecuteType,
RefundSyncType, Response,
},
webhooks,
};
use masking::{ExposeInterface, Mask};
use transformers as opayo;
use crate::{constants::headers, types::ResponseRouterData, utils::convert_amount};
#[derive(Clone)]
pub struct Opayo {
amount_converter: &'static (dyn AmountConvertor<Output = MinorUnit> + Sync),
}
impl Opayo {
pub fn new() -> &'static Self {
&Self {
amount_converter: &MinorUnitForConnector,
}
}
}
impl api::Payment for Opayo {}
impl api::PaymentSession for Opayo {}
impl api::ConnectorAccessToken for Opayo {}
impl api::MandateSetup for Opayo {}
impl api::PaymentAuthorize for Opayo {}
impl api::PaymentSync for Opayo {}
impl api::PaymentCapture for Opayo {}
impl api::PaymentVoid for Opayo {}
impl api::Refund for Opayo {}
impl api::RefundExecute for Opayo {}
impl api::RefundSync for Opayo {}
impl api::PaymentToken for Opayo {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Opayo
{
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Opayo
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let content_type = ConnectorCommon::common_get_content_type(self);
let mut common_headers = self.get_auth_header(&req.connector_auth_type)?;
common_headers.push((
headers::CONTENT_TYPE.to_string(),
content_type.to_string().into(),
));
Ok(common_headers)
}
}
impl ConnectorCommon for Opayo {
fn id(&self) -> &'static str {
"opayo"
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.opayo.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = opayo::OpayoAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
headers::AUTHORIZATION.to_string(),
auth.api_key.expose().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: opayo::OpayoErrorResponse =
res.response
.parse_struct("OpayoErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_error_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.code,
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 Opayo {
fn validate_connector_against_payment_request(
&self,
capture_method: Option<enums::CaptureMethod>,
_payment_method: enums::PaymentMethod,
_pmt: Option<enums::PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
match capture_method {
enums::CaptureMethod::Automatic
| enums::CaptureMethod::Manual
| enums::CaptureMethod::SequentialAutomatic => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
crate::utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Opayo {
//TODO: implement sessions flow
}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Opayo {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Opayo {
fn build_request(
&self,
_req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
_connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Err(
errors::ConnectorError::NotImplemented("Setup Mandate flow for Opayo".to_string())
.into(),
)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Opayo {
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 = convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = opayo::OpayoRouterData::from((amount, req));
let connector_req = opayo::OpayoPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&PaymentsAuthorizeType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsAuthorizeType::get_headers(self, req, connectors)?)
.set_body(PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: opayo::OpayoPaymentsResponse = res
.response
.parse_struct("Opayo 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 Opayo {
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(&PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: opayo::OpayoPaymentsResponse = res
.response
.parse_struct("opayo 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 Opayo {
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(&PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsCaptureType::get_headers(self, req, connectors)?)
.set_body(PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: opayo::OpayoPaymentsResponse = res
.response
.parse_struct("Opayo 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 Opayo {}
impl ConnectorIntegration<Execute, RefundsData, RefundsResponseData> for Opayo {
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 = convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = opayo::OpayoRouterData::from((refund_amount, req));
let connector_req = opayo::OpayoRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::Json(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundExecuteType::get_headers(self, req, connectors)?)
.set_body(RefundExecuteType::get_request_body(self, req, connectors)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: opayo::RefundResponse = res
.response
.parse_struct("opayo 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 Opayo {
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(&RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(RefundSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: opayo::RefundResponse = res
.response
.parse_struct("opayo 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 Opayo {
fn get_webhook_object_reference_id(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
Err(report!(errors::ConnectorError::WebhooksNotImplemented))
}
}
impl ConnectorSpecifications for Opayo {}
|
crates/hyperswitch_connectors/src/connectors/opayo.rs
|
hyperswitch_connectors
|
full_file
| null | null | null | 4,406
| null | null | null | null | null | null | null |
// Function: get_index_for_correct_recovery_code
// File: crates/router/src/utils/user/password.rs
// Module: router
pub fn get_index_for_correct_recovery_code(
candidate: &Secret<String>,
recovery_codes: &[Secret<String>],
) -> CustomResult<Option<usize>, UserErrors>
|
crates/router/src/utils/user/password.rs
|
router
|
function_signature
| null | null | null | 61
|
get_index_for_correct_recovery_code
| null | null | null | null | null | null |
// Module Structure
// File: crates/hyperswitch_connectors/src/connectors/affirm.rs
// Module: hyperswitch_connectors
// Public submodules:
pub mod transformers;
|
crates/hyperswitch_connectors/src/connectors/affirm.rs
|
hyperswitch_connectors
|
module_structure
| null | null | null | 39
| null | null | null | null | null | 1
| 0
|
// Struct: NovalnetAuthType
// File: crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct NovalnetAuthType
|
crates/hyperswitch_connectors/src/connectors/novalnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
NovalnetAuthType
| 0
|
[] | 52
| null | null | null | null | null | null | null |
// Implementation: impl RequestExtendedAuthorizationBool
// File: crates/common_types/src/primitive_wrappers.rs
// Module: common_types
// Methods: 1 total (1 public)
impl RequestExtendedAuthorizationBool
|
crates/common_types/src/primitive_wrappers.rs
|
common_types
|
impl_block
| null | null | null | 43
| null |
RequestExtendedAuthorizationBool
| null | 1
| 1
| null | null |
// Struct: ApiKeyAuthWithMerchantIdFromRoute
// File: crates/router/src/services/authentication.rs
// Module: router
// Implementations: 1
// Traits: GetAuthType
pub struct ApiKeyAuthWithMerchantIdFromRoute
|
crates/router/src/services/authentication.rs
|
router
|
struct_definition
|
ApiKeyAuthWithMerchantIdFromRoute
| 1
|
[
"GetAuthType"
] | 51
| null | null | null | null | null | null | null |
// Implementation: impl ConnectorSpecifications for for Noon
// File: crates/hyperswitch_connectors/src/connectors/noon.rs
// Module: hyperswitch_connectors
// Methods: 3 total (0 public)
impl ConnectorSpecifications for for Noon
|
crates/hyperswitch_connectors/src/connectors/noon.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 51
| null |
Noon
|
ConnectorSpecifications for
| 3
| 0
| null | null |
// Function: setup_intents_retrieve
// File: crates/router/src/compatibility/stripe/setup_intents.rs
// Module: router
pub fn setup_intents_retrieve(
state: web::Data<routes::AppState>,
req: HttpRequest,
path: web::Path<common_utils::id_type::PaymentId>,
query_payload: web::Query<stripe_payment_types::StripePaymentRetrieveBody>,
) -> HttpResponse
|
crates/router/src/compatibility/stripe/setup_intents.rs
|
router
|
function_signature
| null | null | null | 90
|
setup_intents_retrieve
| null | null | null | null | null | null |
// Implementation: impl api::PaymentVoid for for Tokenex
// File: crates/hyperswitch_connectors/src/connectors/tokenex.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Tokenex
|
crates/hyperswitch_connectors/src/connectors/tokenex.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Tokenex
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Implementation: impl NmiMerchantDefinedField
// File: crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
// Module: hyperswitch_connectors
// Methods: 1 total (1 public)
impl NmiMerchantDefinedField
|
crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 54
| null |
NmiMerchantDefinedField
| null | 1
| 1
| null | null |
// File: crates/api_models/src/files.rs
// Module: api_models
// Public structs: 3
use utoipa::ToSchema;
#[derive(Debug, serde::Serialize, ToSchema)]
pub struct CreateFileResponse {
/// ID of the file created
pub file_id: String,
}
#[derive(Debug, serde::Serialize, ToSchema, Clone)]
pub struct FileMetadataResponse {
/// ID of the file created
pub file_id: String,
/// Name of the file
pub file_name: Option<String>,
/// Size of the file
pub file_size: i32,
/// Type of the file
pub file_type: String,
/// File availability
pub available: bool,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize)]
pub struct FileRetrieveQuery {
///Dispute Id
pub dispute_id: Option<String>,
}
|
crates/api_models/src/files.rs
|
api_models
|
full_file
| null | null | null | 190
| null | null | null | null | null | null | null |
// Function: success_based_routing_update_configs
// File: crates/router/src/core/routing.rs
// Module: router
pub 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>
|
crates/router/src/core/routing.rs
|
router
|
function_signature
| null | null | null | 88
|
success_based_routing_update_configs
| null | null | null | null | null | null |
// Function: perform_dynamic_routing_with_intelligent_router
// File: crates/router/src/core/payments/routing.rs
// Module: router
pub fn perform_dynamic_routing_with_intelligent_router<F, D>(
state: &SessionState,
routable_connectors: Vec<api_routing::RoutableConnectorChoice>,
profile: &domain::Profile,
dynamic_routing_config_params_interpolator: routing::helpers::DynamicRoutingConfigParamsInterpolator,
payment_data: &mut D,
) -> RoutingResult<Vec<api_routing::RoutableConnectorChoice>>
where
F: Send + Clone,
D: OperationSessionGetters<F> + OperationSessionSetters<F> + Send + Sync + Clone,
|
crates/router/src/core/payments/routing.rs
|
router
|
function_signature
| null | null | null | 147
|
perform_dynamic_routing_with_intelligent_router
| null | null | null | null | null | null |
// Implementation: impl CeleroTransactionResponseData
// File: crates/hyperswitch_connectors/src/connectors/celero/transformers.rs
// Module: hyperswitch_connectors
// Methods: 1 total (1 public)
impl CeleroTransactionResponseData
|
crates/hyperswitch_connectors/src/connectors/celero/transformers.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 55
| null |
CeleroTransactionResponseData
| null | 1
| 1
| null | null |
// Struct: PayeezyRouterData
// File: crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PayeezyRouterData<T>
|
crates/hyperswitch_connectors/src/connectors/payeezy/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PayeezyRouterData
| 0
|
[] | 54
| null | null | null | null | null | null | null |
// File: crates/router/src/consts/opensearch.rs
// Module: router
use api_models::analytics::search::SearchIndex;
pub const fn get_search_indexes() -> [SearchIndex; 8] {
[
SearchIndex::PaymentAttempts,
SearchIndex::PaymentIntents,
SearchIndex::Refunds,
SearchIndex::Disputes,
SearchIndex::SessionizerPaymentAttempts,
SearchIndex::SessionizerPaymentIntents,
SearchIndex::SessionizerRefunds,
SearchIndex::SessionizerDisputes,
]
}
pub const SEARCH_INDEXES: [SearchIndex; 8] = get_search_indexes();
|
crates/router/src/consts/opensearch.rs
|
router
|
full_file
| null | null | null | 136
| null | null | null | null | null | null | null |
// Struct: PaymentProcessingDetails
// File: crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct PaymentProcessingDetails
|
crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
PaymentProcessingDetails
| 0
|
[] | 47
| null | null | null | null | null | null | null |
// Function: get_count_by_merchant_id_status
// File: crates/diesel_models/src/query/payment_method.rs
// Module: diesel_models
pub fn get_count_by_merchant_id_status(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> StorageResult<i64>
|
crates/diesel_models/src/query/payment_method.rs
|
diesel_models
|
function_signature
| null | null | null | 83
|
get_count_by_merchant_id_status
| null | null | null | null | null | null |
// Implementation: impl api::PaymentSync for for Xendit
// File: crates/hyperswitch_connectors/src/connectors/xendit.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentSync for for Xendit
|
crates/hyperswitch_connectors/src/connectors/xendit.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 60
| null |
Xendit
|
api::PaymentSync for
| 0
| 0
| null | null |
// Struct: AdyenBankAccountDetails
// File: crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AdyenBankAccountDetails
|
crates/hyperswitch_connectors/src/connectors/adyenplatform/transformers/payouts.rs
|
hyperswitch_connectors
|
struct_definition
|
AdyenBankAccountDetails
| 0
|
[] | 56
| null | null | null | null | null | null | null |
// Trait: Domain
// File: crates/router/src/core/payments/operations.rs
// Module: router
pub trait Domain<F: Clone, R, D>: Send + Sync
|
crates/router/src/core/payments/operations.rs
|
router
|
trait_definition
| null | null | null | 37
| null | null |
Domain
| null | null | null | null |
// Implementation: impl Responder
// File: crates/router/src/routes/routing.rs
// Module: router
// Methods: 0 total (0 public)
impl Responder
|
crates/router/src/routes/routing.rs
|
router
|
impl_block
| null | null | null | 36
| null |
Responder
| null | 0
| 0
| null | null |
// Struct: BillingData
// File: crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct BillingData
|
crates/hyperswitch_connectors/src/connectors/redsys/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
BillingData
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Struct: AlwaysRequestExtendedAuthorization
// File: crates/common_utils/src/types/primitive_wrappers.rs
// Module: common_utils
// Implementations: 0
pub struct AlwaysRequestExtendedAuthorization
|
crates/common_utils/src/types/primitive_wrappers.rs
|
common_utils
|
struct_definition
|
AlwaysRequestExtendedAuthorization
| 0
|
[] | 41
| null | null | null | null | null | null | null |
// Implementation: impl MerchantConnectorAccount
// File: crates/hyperswitch_domain_models/src/merchant_connector_account.rs
// Module: hyperswitch_domain_models
// Methods: 6 total (6 public)
impl MerchantConnectorAccount
|
crates/hyperswitch_domain_models/src/merchant_connector_account.rs
|
hyperswitch_domain_models
|
impl_block
| null | null | null | 47
| null |
MerchantConnectorAccount
| null | 6
| 6
| null | null |
// Struct: LastPaymentError
// File: crates/router/src/compatibility/stripe/payment_intents/types.rs
// Module: router
// Implementations: 0
pub struct LastPaymentError
|
crates/router/src/compatibility/stripe/payment_intents/types.rs
|
router
|
struct_definition
|
LastPaymentError
| 0
|
[] | 41
| null | null | null | null | null | null | null |
// Struct: Notifications
// File: crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct Notifications
|
crates/hyperswitch_connectors/src/connectors/globalpay/requests.rs
|
hyperswitch_connectors
|
struct_definition
|
Notifications
| 0
|
[] | 42
| null | null | null | null | null | null | null |
// Implementation: impl Hash for for FrmMetricsBucketIdentifier
// File: crates/api_models/src/analytics/frm.rs
// Module: api_models
// Methods: 1 total (0 public)
impl Hash for for FrmMetricsBucketIdentifier
|
crates/api_models/src/analytics/frm.rs
|
api_models
|
impl_block
| null | null | null | 49
| null |
FrmMetricsBucketIdentifier
|
Hash for
| 1
| 0
| null | null |
// Implementation: impl DynamicRoutingStats
// File: crates/diesel_models/src/query/dynamic_routing_stats.rs
// Module: diesel_models
// Methods: 2 total (0 public)
impl DynamicRoutingStats
|
crates/diesel_models/src/query/dynamic_routing_stats.rs
|
diesel_models
|
impl_block
| null | null | null | 43
| null |
DynamicRoutingStats
| null | 2
| 0
| null | null |
// Implementation: impl PaymentSync for for Threedsecureio
// File: crates/hyperswitch_connectors/src/connectors/threedsecureio.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl PaymentSync for for Threedsecureio
|
crates/hyperswitch_connectors/src/connectors/threedsecureio.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Threedsecureio
|
PaymentSync for
| 0
| 0
| null | null |
// File: crates/router/tests/connectors/globalpay.rs
// Module: router
use std::str::FromStr;
use hyperswitch_domain_models::address::{Address, AddressDetails};
use masking::Secret;
use router::types::{self, api, domain, storage::enums, AccessToken, ConnectorAuthType};
use serde_json::json;
use crate::{
connector_auth,
utils::{self, Connector, ConnectorActions, PaymentInfo},
};
struct Globalpay;
impl ConnectorActions for Globalpay {}
static CONNECTOR: Globalpay = Globalpay {};
impl Connector for Globalpay {
fn get_data(&self) -> api::ConnectorData {
use router::connector::Globalpay;
utils::construct_connector_data_old(
Box::new(Globalpay::new()),
types::Connector::Globalpay,
api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.globalpay
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"globalpay".to_string()
}
fn get_connector_meta(&self) -> Option<serde_json::Value> {
Some(json!({"account_name": "transaction_processing"}))
}
}
fn get_access_token() -> Option<AccessToken> {
match Connector::get_auth_token(&CONNECTOR) {
ConnectorAuthType::BodyKey { api_key, key1: _ } => Some(AccessToken {
token: api_key,
expires: 18600,
}),
_ => None,
}
}
impl Globalpay {
fn get_request_interval(&self) -> u64 {
5
}
fn get_payment_info() -> Option<PaymentInfo> {
Some(PaymentInfo {
address: Some(types::PaymentAddress::new(
None,
Some(Address {
address: Some(AddressDetails {
country: Some(api_models::enums::CountryAlpha2::US),
..Default::default()
}),
phone: None,
..Default::default()
}),
None,
None,
)),
access_token: get_access_token(),
connector_meta_data: CONNECTOR.get_connector_meta(),
..Default::default()
})
}
}
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(None, Globalpay::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
#[actix_web::test]
async fn should_make_payment() {
let response = CONNECTOR
.make_payment(None, Globalpay::get_payment_info())
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
None,
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
Globalpay::get_payment_info(),
)
.await;
assert_eq!(response.unwrap().status, enums::AttemptStatus::Charged);
}
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.authorize_payment(None, Globalpay::get_payment_info())
.await
.unwrap();
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
Globalpay::get_payment_info(),
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
#[actix_web::test]
async fn should_fail_payment_for_incorrect_cvc() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4024007134364842").unwrap(),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
Globalpay::get_payment_info(),
)
.await
.unwrap();
let x = response.status;
assert_eq!(x, enums::AttemptStatus::Failure);
}
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(None, None, Globalpay::get_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(None, None, Globalpay::get_payment_info())
.await;
assert_eq!(response.unwrap().status, enums::AttemptStatus::Voided);
}
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(None, None, Globalpay::get_payment_info())
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_secs(
CONNECTOR.get_request_interval(),
))
.await;
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
Globalpay::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(
None,
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
Globalpay::get_payment_info(),
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
None,
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
Globalpay::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_succeeded_payment() {
let authorize_response = CONNECTOR
.make_payment(None, Globalpay::get_payment_info())
.await
.unwrap();
let txn_id = utils::get_connector_transaction_id(authorize_response.response.clone()).unwrap();
let refund_response = CONNECTOR
.refund_payment(
txn_id,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
Globalpay::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_manually_captured_refund() {
let refund_response = CONNECTOR
.capture_payment_and_refund(None, None, None, Globalpay::get_payment_info())
.await
.unwrap();
tokio::time::sleep(std::time::Duration::from_secs(
CONNECTOR.get_request_interval(),
))
.await;
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
Globalpay::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_fail_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
None,
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
Globalpay::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"You may only refund up to 115% of the original amount ",
);
}
// Captures a payment using invalid connector payment id.
#[actix_web::test]
async fn should_fail_capture_for_invalid_payment() {
let capture_response = CONNECTOR
.capture_payment("123ddsa12".to_string(), None, Globalpay::get_payment_info())
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("Transaction 123ddsa12 not found at this location.")
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
#[ignore]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(None, Globalpay::get_payment_info())
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
assert_ne!(txn_id, None, "Empty connector transaction id");
let void_response = CONNECTOR
.void_payment(txn_id.unwrap(), None, Globalpay::get_payment_info())
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"You cannot cancel this PaymentIntent because it has a status of succeeded."
);
}
// Creates a payment with incorrect expiry year.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_expiry_year() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_year: Secret::new("2000".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
Globalpay::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Expiry date invalid".to_string(),
);
}
// Creates a payment with incorrect expiry month.
#[actix_web::test]
async fn should_fail_payment_for_invalid_exp_month() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_exp_month: Secret::new("20".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
Globalpay::get_payment_info(),
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Invalid Expiry Date".to_string(),
);
}
// Creates multiple refunds against a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_succeeded_payment_multiple_times() {
CONNECTOR
.make_payment_and_multiple_refund(
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
Globalpay::get_payment_info(),
)
.await;
}
// Synchronizes a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_authorized_payment() {
let authorize_response = CONNECTOR
.authorize_payment(None, Globalpay::get_payment_info())
.await
.expect("Authorize payment response");
let txn_id = utils::get_connector_transaction_id(authorize_response.response);
let response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Authorized,
Some(types::PaymentsSyncData {
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
..Default::default()
}),
Globalpay::get_payment_info(),
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(None, None, None, Globalpay::get_payment_info())
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
|
crates/router/tests/connectors/globalpay.rs
|
router
|
full_file
| null | null | null | 3,007
| null | null | null | null | null | null | null |
// File: crates/router/src/db/dynamic_routing_stats.rs
// Module: router
use error_stack::report;
use router_env::{instrument, tracing};
use storage_impl::MockDb;
use super::Store;
use crate::{
connection,
core::errors::{self, CustomResult},
db::kafka_store::KafkaStore,
types::storage,
};
#[async_trait::async_trait]
pub trait DynamicRoutingStatsInterface {
async fn insert_dynamic_routing_stat_entry(
&self,
dynamic_routing_stat_new: storage::DynamicRoutingStatsNew,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>;
async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
&self,
attempt_id: String,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError>;
async fn update_dynamic_routing_stats(
&self,
attempt_id: String,
merchant_id: &common_utils::id_type::MerchantId,
data: storage::DynamicRoutingStatsUpdate,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError>;
}
#[async_trait::async_trait]
impl DynamicRoutingStatsInterface for Store {
#[instrument(skip_all)]
async fn insert_dynamic_routing_stat_entry(
&self,
dynamic_routing_stat: storage::DynamicRoutingStatsNew,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
dynamic_routing_stat
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
&self,
attempt_id: String,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::DynamicRoutingStats::find_optional_by_attempt_id_merchant_id(
&conn,
attempt_id,
merchant_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn update_dynamic_routing_stats(
&self,
attempt_id: String,
merchant_id: &common_utils::id_type::MerchantId,
data: storage::DynamicRoutingStatsUpdate,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::DynamicRoutingStats::update(&conn, attempt_id, merchant_id, data)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl DynamicRoutingStatsInterface for MockDb {
#[instrument(skip_all)]
async fn insert_dynamic_routing_stat_entry(
&self,
_dynamic_routing_stat: storage::DynamicRoutingStatsNew,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
&self,
_attempt_id: String,
_merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn update_dynamic_routing_stats(
&self,
_attempt_id: String,
_merchant_id: &common_utils::id_type::MerchantId,
_data: storage::DynamicRoutingStatsUpdate,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
}
#[async_trait::async_trait]
impl DynamicRoutingStatsInterface for KafkaStore {
#[instrument(skip_all)]
async fn insert_dynamic_routing_stat_entry(
&self,
dynamic_routing_stat: storage::DynamicRoutingStatsNew,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
self.diesel_store
.insert_dynamic_routing_stat_entry(dynamic_routing_stat)
.await
}
async fn find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(
&self,
attempt_id: String,
merchant_id: &common_utils::id_type::MerchantId,
) -> CustomResult<Option<storage::DynamicRoutingStats>, errors::StorageError> {
self.diesel_store
.find_dynamic_routing_stats_optional_by_attempt_id_merchant_id(attempt_id, merchant_id)
.await
}
async fn update_dynamic_routing_stats(
&self,
attempt_id: String,
merchant_id: &common_utils::id_type::MerchantId,
data: storage::DynamicRoutingStatsUpdate,
) -> CustomResult<storage::DynamicRoutingStats, errors::StorageError> {
self.diesel_store
.update_dynamic_routing_stats(attempt_id, merchant_id, data)
.await
}
}
|
crates/router/src/db/dynamic_routing_stats.rs
|
router
|
full_file
| null | null | null | 1,097
| null | null | null | null | null | null | null |
// Struct: ItaubankMetaData
// File: crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct ItaubankMetaData
|
crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
ItaubankMetaData
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Implementation: impl Capturable for for PaymentsTaxCalculationData
// File: crates/router/src/types.rs
// Module: router
// Methods: 0 total (0 public)
impl Capturable for for PaymentsTaxCalculationData
|
crates/router/src/types.rs
|
router
|
impl_block
| null | null | null | 48
| null |
PaymentsTaxCalculationData
|
Capturable for
| 0
| 0
| null | null |
// Implementation: impl Taxjar
// File: crates/hyperswitch_connectors/src/connectors/taxjar.rs
// Module: hyperswitch_connectors
// Methods: 1 total (1 public)
impl Taxjar
|
crates/hyperswitch_connectors/src/connectors/taxjar.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 46
| null |
Taxjar
| null | 1
| 1
| null | null |
// File: crates/router/src/types/storage/payment_attempt.rs
// Module: router
use common_utils::types::MinorUnit;
use diesel_models::{capture::CaptureNew, enums};
use error_stack::ResultExt;
pub use hyperswitch_domain_models::payments::payment_attempt::{
PaymentAttempt, PaymentAttemptUpdate,
};
use crate::{
core::errors, errors::RouterResult, types::transformers::ForeignFrom, utils::OptionExt,
};
pub trait PaymentAttemptExt {
fn make_new_capture(
&self,
capture_amount: MinorUnit,
capture_status: enums::CaptureStatus,
) -> RouterResult<CaptureNew>;
fn get_next_capture_id(&self) -> String;
fn get_total_amount(&self) -> MinorUnit;
fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails>;
}
impl PaymentAttemptExt for PaymentAttempt {
#[cfg(feature = "v2")]
fn make_new_capture(
&self,
capture_amount: MinorUnit,
capture_status: enums::CaptureStatus,
) -> RouterResult<CaptureNew> {
todo!()
}
#[cfg(feature = "v1")]
fn make_new_capture(
&self,
capture_amount: MinorUnit,
capture_status: enums::CaptureStatus,
) -> RouterResult<CaptureNew> {
let capture_sequence = self.multiple_capture_count.unwrap_or_default() + 1;
let now = common_utils::date_time::now();
Ok(CaptureNew {
payment_id: self.payment_id.clone(),
merchant_id: self.merchant_id.clone(),
capture_id: self.get_next_capture_id(),
status: capture_status,
amount: capture_amount,
currency: self.currency,
connector: self
.connector
.clone()
.get_required_value("connector")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"connector field is required in payment_attempt to create a capture",
)?,
error_message: None,
tax_amount: None,
created_at: now,
modified_at: now,
error_code: None,
error_reason: None,
authorized_attempt_id: self.attempt_id.clone(),
capture_sequence,
connector_capture_id: None,
connector_response_reference_id: None,
processor_capture_data: None,
// Below fields are deprecated. Please add any new fields above this line.
connector_capture_data: None,
})
}
#[cfg(feature = "v1")]
fn get_next_capture_id(&self) -> String {
let next_sequence_number = self.multiple_capture_count.unwrap_or_default() + 1;
format!("{}_{}", self.attempt_id.clone(), next_sequence_number)
}
#[cfg(feature = "v2")]
fn get_next_capture_id(&self) -> String {
todo!()
}
#[cfg(feature = "v1")]
fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails> {
self.net_amount
.get_surcharge_amount()
.map(
|surcharge_amount| api_models::payments::RequestSurchargeDetails {
surcharge_amount,
tax_amount: self.net_amount.get_tax_on_surcharge(),
},
)
}
#[cfg(feature = "v2")]
fn get_surcharge_details(&self) -> Option<api_models::payments::RequestSurchargeDetails> {
todo!()
}
#[cfg(feature = "v1")]
fn get_total_amount(&self) -> MinorUnit {
self.net_amount.get_total_amount()
}
#[cfg(feature = "v2")]
fn get_total_amount(&self) -> MinorUnit {
todo!()
}
}
pub trait AttemptStatusExt {
fn maps_to_intent_status(self, intent_status: enums::IntentStatus) -> bool;
}
impl AttemptStatusExt for enums::AttemptStatus {
fn maps_to_intent_status(self, intent_status: enums::IntentStatus) -> bool {
enums::IntentStatus::foreign_from(self) == intent_status
}
}
#[cfg(test)]
#[cfg(all(
feature = "v1", // Ignoring tests for v2 since they aren't actively running
feature = "dummy_connector"
))]
mod tests {
#![allow(clippy::expect_used, clippy::unwrap_used, clippy::print_stderr)]
use hyperswitch_domain_models::payments::payment_attempt::PaymentAttemptNew;
use tokio::sync::oneshot;
use uuid::Uuid;
use crate::{
configs::settings::Settings,
db::StorageImpl,
routes, services,
types::{self, storage::enums},
};
async fn create_single_connection_test_transaction_pool() -> routes::AppState {
// Set pool size to 1 and minimum idle connection size to 0
std::env::set_var("ROUTER__MASTER_DATABASE__POOL_SIZE", "1");
std::env::set_var("ROUTER__MASTER_DATABASE__MIN_IDLE", "0");
std::env::set_var("ROUTER__REPLICA_DATABASE__POOL_SIZE", "1");
std::env::set_var("ROUTER__REPLICA_DATABASE__MIN_IDLE", "0");
let conf = Settings::new().expect("invalid settings");
let tx: oneshot::Sender<()> = oneshot::channel().0;
let api_client = Box::new(services::MockApiClient);
Box::pin(routes::AppState::with_storage(
conf,
StorageImpl::PostgresqlTest,
tx,
api_client,
))
.await
}
#[tokio::test]
async fn test_payment_attempt_insert() {
let state = create_single_connection_test_transaction_pool().await;
let payment_id =
common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let current_time = common_utils::date_time::now();
let connector = types::Connector::DummyConnector1.to_string();
let payment_attempt = PaymentAttemptNew {
payment_id: payment_id.clone(),
connector: Some(connector),
created_at: current_time.into(),
modified_at: current_time.into(),
merchant_id: Default::default(),
attempt_id: Default::default(),
status: Default::default(),
net_amount: Default::default(),
currency: Default::default(),
save_to_locker: Default::default(),
error_message: Default::default(),
offer_amount: Default::default(),
payment_method_id: Default::default(),
payment_method: Default::default(),
capture_method: Default::default(),
capture_on: Default::default(),
confirm: Default::default(),
authentication_type: Default::default(),
last_synced: Default::default(),
cancellation_reason: Default::default(),
amount_to_capture: Default::default(),
mandate_id: Default::default(),
browser_info: Default::default(),
payment_token: Default::default(),
error_code: Default::default(),
connector_metadata: Default::default(),
payment_experience: Default::default(),
payment_method_type: Default::default(),
payment_method_data: Default::default(),
business_sub_label: Default::default(),
straight_through_algorithm: Default::default(),
preprocessing_step_id: Default::default(),
mandate_details: Default::default(),
error_reason: Default::default(),
connector_response_reference_id: Default::default(),
multiple_capture_count: Default::default(),
amount_capturable: Default::default(),
updated_by: Default::default(),
authentication_data: Default::default(),
encoded_data: Default::default(),
merchant_connector_id: Default::default(),
unified_code: Default::default(),
unified_message: Default::default(),
external_three_ds_authentication_attempted: Default::default(),
authentication_connector: Default::default(),
authentication_id: Default::default(),
mandate_data: Default::default(),
payment_method_billing_address_id: Default::default(),
fingerprint_id: Default::default(),
client_source: Default::default(),
client_version: Default::default(),
customer_acceptance: Default::default(),
profile_id: common_utils::generate_profile_id_of_default_length(),
organization_id: Default::default(),
connector_mandate_detail: Default::default(),
request_extended_authorization: Default::default(),
extended_authorization_applied: Default::default(),
capture_before: Default::default(),
card_discovery: Default::default(),
processor_merchant_id: Default::default(),
created_by: None,
setup_future_usage_applied: Default::default(),
routing_approach: Default::default(),
connector_request_reference_id: Default::default(),
network_transaction_id: Default::default(),
network_details: Default::default(),
is_stored_credential: None,
};
let store = state
.stores
.get(state.conf.multitenancy.get_tenant_ids().first().unwrap())
.unwrap();
let response = store
.insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly)
.await
.unwrap();
eprintln!("{response:?}");
assert_eq!(response.payment_id, payment_id.clone());
}
#[tokio::test]
/// Example of unit test
/// Kind of test: state-based testing
async fn test_find_payment_attempt() {
let state = create_single_connection_test_transaction_pool().await;
let current_time = common_utils::date_time::now();
let payment_id =
common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let attempt_id = Uuid::new_v4().to_string();
let merchant_id = common_utils::id_type::MerchantId::new_from_unix_timestamp();
let connector = types::Connector::DummyConnector1.to_string();
let payment_attempt = PaymentAttemptNew {
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
connector: Some(connector),
created_at: current_time.into(),
modified_at: current_time.into(),
attempt_id: attempt_id.clone(),
status: Default::default(),
net_amount: Default::default(),
currency: Default::default(),
save_to_locker: Default::default(),
error_message: Default::default(),
offer_amount: Default::default(),
payment_method_id: Default::default(),
payment_method: Default::default(),
capture_method: Default::default(),
capture_on: Default::default(),
confirm: Default::default(),
authentication_type: Default::default(),
last_synced: Default::default(),
cancellation_reason: Default::default(),
amount_to_capture: Default::default(),
mandate_id: Default::default(),
browser_info: Default::default(),
payment_token: Default::default(),
error_code: Default::default(),
connector_metadata: Default::default(),
payment_experience: Default::default(),
payment_method_type: Default::default(),
payment_method_data: Default::default(),
business_sub_label: Default::default(),
straight_through_algorithm: Default::default(),
preprocessing_step_id: Default::default(),
mandate_details: Default::default(),
error_reason: Default::default(),
connector_response_reference_id: Default::default(),
multiple_capture_count: Default::default(),
amount_capturable: Default::default(),
updated_by: Default::default(),
authentication_data: Default::default(),
encoded_data: Default::default(),
merchant_connector_id: Default::default(),
unified_code: Default::default(),
unified_message: Default::default(),
external_three_ds_authentication_attempted: Default::default(),
authentication_connector: Default::default(),
authentication_id: Default::default(),
mandate_data: Default::default(),
payment_method_billing_address_id: Default::default(),
fingerprint_id: Default::default(),
client_source: Default::default(),
client_version: Default::default(),
customer_acceptance: Default::default(),
profile_id: common_utils::generate_profile_id_of_default_length(),
organization_id: Default::default(),
connector_mandate_detail: Default::default(),
request_extended_authorization: Default::default(),
extended_authorization_applied: Default::default(),
capture_before: Default::default(),
card_discovery: Default::default(),
processor_merchant_id: Default::default(),
created_by: None,
setup_future_usage_applied: Default::default(),
routing_approach: Default::default(),
connector_request_reference_id: Default::default(),
network_transaction_id: Default::default(),
network_details: Default::default(),
is_stored_credential: Default::default(),
};
let store = state
.stores
.get(state.conf.multitenancy.get_tenant_ids().first().unwrap())
.unwrap();
store
.insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly)
.await
.unwrap();
let response = store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_id,
&merchant_id,
&attempt_id,
enums::MerchantStorageScheme::PostgresOnly,
)
.await
.unwrap();
eprintln!("{response:?}");
assert_eq!(response.payment_id, payment_id);
}
#[tokio::test]
/// Example of unit test
/// Kind of test: state-based testing
async fn test_payment_attempt_mandate_field() {
let state = create_single_connection_test_transaction_pool().await;
let uuid = Uuid::new_v4().to_string();
let merchant_id =
common_utils::id_type::MerchantId::try_from(std::borrow::Cow::from("merchant1"))
.unwrap();
let payment_id =
common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let current_time = common_utils::date_time::now();
let connector = types::Connector::DummyConnector1.to_string();
let payment_attempt = PaymentAttemptNew {
payment_id: payment_id.clone(),
merchant_id: merchant_id.clone(),
connector: Some(connector),
created_at: current_time.into(),
modified_at: current_time.into(),
mandate_id: Some("man_121212".to_string()),
attempt_id: uuid.clone(),
status: Default::default(),
net_amount: Default::default(),
currency: Default::default(),
save_to_locker: Default::default(),
error_message: Default::default(),
offer_amount: Default::default(),
payment_method_id: Default::default(),
payment_method: Default::default(),
capture_method: Default::default(),
capture_on: Default::default(),
confirm: Default::default(),
authentication_type: Default::default(),
last_synced: Default::default(),
cancellation_reason: Default::default(),
amount_to_capture: Default::default(),
browser_info: Default::default(),
payment_token: Default::default(),
error_code: Default::default(),
connector_metadata: Default::default(),
payment_experience: Default::default(),
payment_method_type: Default::default(),
payment_method_data: Default::default(),
business_sub_label: Default::default(),
straight_through_algorithm: Default::default(),
preprocessing_step_id: Default::default(),
mandate_details: Default::default(),
error_reason: Default::default(),
connector_response_reference_id: Default::default(),
multiple_capture_count: Default::default(),
amount_capturable: Default::default(),
updated_by: Default::default(),
authentication_data: Default::default(),
encoded_data: Default::default(),
merchant_connector_id: Default::default(),
unified_code: Default::default(),
unified_message: Default::default(),
external_three_ds_authentication_attempted: Default::default(),
authentication_connector: Default::default(),
authentication_id: Default::default(),
mandate_data: Default::default(),
payment_method_billing_address_id: Default::default(),
fingerprint_id: Default::default(),
client_source: Default::default(),
client_version: Default::default(),
customer_acceptance: Default::default(),
profile_id: common_utils::generate_profile_id_of_default_length(),
organization_id: Default::default(),
connector_mandate_detail: Default::default(),
request_extended_authorization: Default::default(),
extended_authorization_applied: Default::default(),
capture_before: Default::default(),
card_discovery: Default::default(),
processor_merchant_id: Default::default(),
created_by: None,
setup_future_usage_applied: Default::default(),
routing_approach: Default::default(),
connector_request_reference_id: Default::default(),
network_transaction_id: Default::default(),
network_details: Default::default(),
is_stored_credential: Default::default(),
};
let store = state
.stores
.get(state.conf.multitenancy.get_tenant_ids().first().unwrap())
.unwrap();
store
.insert_payment_attempt(payment_attempt, enums::MerchantStorageScheme::PostgresOnly)
.await
.unwrap();
let response = store
.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&payment_id,
&merchant_id,
&uuid,
enums::MerchantStorageScheme::PostgresOnly,
)
.await
.unwrap();
// checking it after fetch
assert_eq!(response.mandate_id, Some("man_121212".to_string()));
}
}
|
crates/router/src/types/storage/payment_attempt.rs
|
router
|
full_file
| null | null | null | 3,695
| null | null | null | null | null | null | null |
// Struct: FileMetadata
// File: crates/diesel_models/src/file.rs
// Module: diesel_models
// Implementations: 0
pub struct FileMetadata
|
crates/diesel_models/src/file.rs
|
diesel_models
|
struct_definition
|
FileMetadata
| 0
|
[] | 34
| null | null | null | null | null | null | null |
// Function: get_payment_response_using_payment_get_operation
// File: crates/router/src/core/revenue_recovery.rs
// Module: router
pub fn get_payment_response_using_payment_get_operation(
state: &SessionState,
payment_intent_id: &id_type::GlobalPaymentId,
revenue_recovery_payment_data: &pcr::RevenueRecoveryPaymentData,
merchant_context: &domain::MerchantContext,
active_payment_attempt_id: Option<&id_type::GlobalAttemptId>,
) -> Result<Option<ApplicationResponse<PaymentsResponse>>, sch_errors::ProcessTrackerError>
|
crates/router/src/core/revenue_recovery.rs
|
router
|
function_signature
| null | null | null | 116
|
get_payment_response_using_payment_get_operation
| null | null | null | null | null | null |
// Struct: MerchantConnectorCreate
// File: crates/api_models/src/admin.rs
// Module: api_models
// Implementations: 2
pub struct MerchantConnectorCreate
|
crates/api_models/src/admin.rs
|
api_models
|
struct_definition
|
MerchantConnectorCreate
| 2
|
[] | 35
| null | null | null | null | null | null | null |
// Implementation: impl api::Refund for for Razorpay
// File: crates/hyperswitch_connectors/src/connectors/razorpay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::Refund for for Razorpay
|
crates/hyperswitch_connectors/src/connectors/razorpay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Razorpay
|
api::Refund for
| 0
| 0
| null | null |
// Implementation: impl api::PaymentToken for for Getnet
// File: crates/hyperswitch_connectors/src/connectors/getnet.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentToken for for Getnet
|
crates/hyperswitch_connectors/src/connectors/getnet.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Getnet
|
api::PaymentToken for
| 0
| 0
| null | null |
// Function: set_amount_to_capture
// File: crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
// Module: hyperswitch_domain_models
pub fn set_amount_to_capture(&mut self, amount_to_capture: MinorUnit)
|
crates/hyperswitch_domain_models/src/payments/payment_attempt.rs
|
hyperswitch_domain_models
|
function_signature
| null | null | null | 50
|
set_amount_to_capture
| null | null | null | null | null | null |
// Struct: UserDeprecated
// File: crates/router/src/routes/app.rs
// Module: router
// Implementations: 1
pub struct UserDeprecated
|
crates/router/src/routes/app.rs
|
router
|
struct_definition
|
UserDeprecated
| 1
|
[] | 32
| null | null | null | null | null | null | null |
// Struct: FacilitapayPaymentsResponse
// File: crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct FacilitapayPaymentsResponse
|
crates/hyperswitch_connectors/src/connectors/facilitapay/responses.rs
|
hyperswitch_connectors
|
struct_definition
|
FacilitapayPaymentsResponse
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// Implementation: impl api::UasAuthenticationConfirmation for for UnifiedAuthenticationService
// File: crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::UasAuthenticationConfirmation for for UnifiedAuthenticationService
|
crates/hyperswitch_connectors/src/connectors/unified_authentication_service.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 65
| null |
UnifiedAuthenticationService
|
api::UasAuthenticationConfirmation for
| 0
| 0
| null | null |
// Struct: WellsfargopayoutPaymentsResponse
// File: crates/hyperswitch_connectors/src/connectors/wellsfargopayout/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct WellsfargopayoutPaymentsResponse
|
crates/hyperswitch_connectors/src/connectors/wellsfargopayout/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
WellsfargopayoutPaymentsResponse
| 0
|
[] | 59
| null | null | null | null | null | null | null |
// Implementation: impl VerifyIdForUpdateCustomer
// File: crates/router/src/core/customers.rs
// Module: router
// Methods: 1 total (0 public)
impl VerifyIdForUpdateCustomer
|
crates/router/src/core/customers.rs
|
router
|
impl_block
| null | null | null | 42
| null |
VerifyIdForUpdateCustomer
| null | 1
| 0
| null | null |
// Struct: RefundResponse
// File: crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RefundResponse
|
crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RefundResponse
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Struct: AirwallexWebhookData
// File: crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct AirwallexWebhookData
|
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
AirwallexWebhookData
| 0
|
[] | 55
| null | null | null | null | null | null | null |
// File: crates/storage_impl/src/mock_db/payment_intent.rs
// Module: storage_impl
use common_utils::{errors::CustomResult, types::keymanager::KeyManagerState};
use diesel_models::enums as storage_enums;
#[cfg(feature = "v1")]
use error_stack::ResultExt;
#[cfg(feature = "v1")]
use hyperswitch_domain_models::behaviour::Conversion;
use hyperswitch_domain_models::{
merchant_key_store::MerchantKeyStore,
payments::{
payment_intent::{PaymentIntentInterface, PaymentIntentUpdate},
PaymentIntent,
},
};
use super::MockDb;
use crate::errors::StorageError;
#[async_trait::async_trait]
impl PaymentIntentInterface for MockDb {
type Error = StorageError;
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_payment_intent_by_constraints(
&self,
_state: &KeyManagerState,
_merchant_id: &common_utils::id_type::MerchantId,
_filters: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v2", feature = "olap"))]
async fn get_filtered_payment_intents_attempt(
&self,
_state: &KeyManagerState,
_merchant_id: &common_utils::id_type::MerchantId,
_constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_merchant_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<
Vec<(
PaymentIntent,
Option<hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt>,
)>,
StorageError,
> {
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn filter_payment_intents_by_time_range_constraints(
&self,
_state: &KeyManagerState,
_merchant_id: &common_utils::id_type::MerchantId,
_time_range: &common_utils::types::TimeRange,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(feature = "olap")]
async fn get_intent_status_with_count(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_profile_id_list: Option<Vec<common_utils::id_type::ProfileId>>,
_time_range: &common_utils::types::TimeRange,
) -> CustomResult<Vec<(common_enums::IntentStatus, i64)>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<String>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v2", feature = "olap"))]
async fn get_filtered_active_attempt_ids_for_total_count(
&self,
_merchant_id: &common_utils::id_type::MerchantId,
_constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<Vec<Option<String>>, StorageError> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[cfg(all(feature = "v1", feature = "olap"))]
async fn get_filtered_payment_intents_attempt(
&self,
_state: &KeyManagerState,
_merchant_id: &common_utils::id_type::MerchantId,
_constraints: &hyperswitch_domain_models::payments::payment_intent::PaymentIntentFetchConstraints,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<
Vec<(
PaymentIntent,
hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
)>,
StorageError,
> {
// [#172]: Implement function for `MockDb`
Err(StorageError::MockDbError)?
}
#[allow(clippy::panic)]
async fn insert_payment_intent(
&self,
_state: &KeyManagerState,
new: PaymentIntent,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, StorageError> {
let mut payment_intents = self.payment_intents.lock().await;
payment_intents.push(new.clone());
Ok(new)
}
#[cfg(feature = "v1")]
// safety: only used for testing
#[allow(clippy::unwrap_used)]
async fn update_payment_intent(
&self,
state: &KeyManagerState,
this: PaymentIntent,
update: PaymentIntentUpdate,
key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, StorageError> {
let mut payment_intents = self.payment_intents.lock().await;
let payment_intent = payment_intents
.iter_mut()
.find(|item| item.get_id() == this.get_id() && item.merchant_id == this.merchant_id)
.unwrap();
let diesel_payment_intent_update = diesel_models::PaymentIntentUpdate::from(update);
let diesel_payment_intent = payment_intent
.clone()
.convert()
.await
.change_context(StorageError::EncryptionError)?;
*payment_intent = PaymentIntent::convert_back(
state,
diesel_payment_intent_update.apply_changeset(diesel_payment_intent),
key_store.key.get_inner(),
key_store.merchant_id.clone().into(),
)
.await
.change_context(StorageError::DecryptionError)?;
Ok(payment_intent.clone())
}
#[cfg(feature = "v2")]
// safety: only used for testing
#[allow(clippy::unwrap_used)]
async fn update_payment_intent(
&self,
_state: &KeyManagerState,
_this: PaymentIntent,
_update: PaymentIntentUpdate,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, StorageError> {
todo!()
}
#[cfg(feature = "v1")]
// safety: only used for testing
#[allow(clippy::unwrap_used)]
async fn find_payment_intent_by_payment_id_merchant_id(
&self,
_state: &KeyManagerState,
payment_id: &common_utils::id_type::PaymentId,
merchant_id: &common_utils::id_type::MerchantId,
_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<PaymentIntent, StorageError> {
let payment_intents = self.payment_intents.lock().await;
Ok(payment_intents
.iter()
.find(|payment_intent| {
payment_intent.get_id() == payment_id && payment_intent.merchant_id.eq(merchant_id)
})
.cloned()
.unwrap())
}
#[cfg(feature = "v2")]
async fn find_payment_intent_by_id(
&self,
_state: &KeyManagerState,
id: &common_utils::id_type::GlobalPaymentId,
_merchant_key_store: &MerchantKeyStore,
_storage_scheme: storage_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let payment_intents = self.payment_intents.lock().await;
let payment_intent = payment_intents
.iter()
.find(|payment_intent| payment_intent.get_id() == id)
.ok_or(StorageError::ValueNotFound(
"PaymentIntent not found".to_string(),
))?;
Ok(payment_intent.clone())
}
#[cfg(feature = "v2")]
async fn find_payment_intent_by_merchant_reference_id_profile_id(
&self,
_state: &KeyManagerState,
merchant_reference_id: &common_utils::id_type::PaymentReferenceId,
profile_id: &common_utils::id_type::ProfileId,
_merchant_key_store: &MerchantKeyStore,
_storage_scheme: &common_enums::MerchantStorageScheme,
) -> error_stack::Result<PaymentIntent, StorageError> {
let payment_intents = self.payment_intents.lock().await;
let payment_intent = payment_intents
.iter()
.find(|payment_intent| {
payment_intent.merchant_reference_id.as_ref() == Some(merchant_reference_id)
&& payment_intent.profile_id.eq(profile_id)
})
.ok_or(StorageError::ValueNotFound(
"PaymentIntent not found".to_string(),
))?;
Ok(payment_intent.clone())
}
}
|
crates/storage_impl/src/mock_db/payment_intent.rs
|
storage_impl
|
full_file
| null | null | null | 2,127
| null | null | null | null | null | null | null |
// Function: create_tenant_user
// File: crates/router/src/routes/user.rs
// Module: router
pub fn create_tenant_user(
state: web::Data<AppState>,
http_req: HttpRequest,
json_payload: web::Json<user_api::CreateTenantUserRequest>,
) -> HttpResponse
|
crates/router/src/routes/user.rs
|
router
|
function_signature
| null | null | null | 64
|
create_tenant_user
| null | null | null | null | null | null |
// Function: server
// File: crates/router/src/routes/app.rs
// Module: router
pub fn server(state: AppState) -> Scope
|
crates/router/src/routes/app.rs
|
router
|
function_signature
| null | null | null | 29
|
server
| null | null | null | null | null | null |
// Function: get_string_repr
// File: crates/common_utils/src/id_type/global_id/payment.rs
// Module: common_utils
// Documentation: Get string representation of the id
pub fn get_string_repr(&self) -> &str
|
crates/common_utils/src/id_type/global_id/payment.rs
|
common_utils
|
function_signature
| null | null | null | 48
|
get_string_repr
| null | null | null | null | null | null |
VaultFetchAction::FetchNetworkTokenDetailsFromLocker(nt_data)
}
Some(api_models::payments::MandateReferenceId::NetworkMandateId(_)) => {
VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker
}
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(_)) | None => {
VaultFetchAction::NoFetchAction
}
},
None => {
//saved card flow
let is_network_token_supported_connector = connector
.map(|conn| network_tokenization_supported_connectors.contains(&conn))
.unwrap_or(false);
match (
is_network_token_supported_connector,
network_token_requestor_ref_id,
) {
(true, Some(ref_id)) => {
VaultFetchAction::FetchNetworkTokenDataFromTokenizationService(ref_id)
}
(false, Some(_)) | (true, None) | (false, None) => {
VaultFetchAction::FetchCardDetailsFromLocker
}
}
}
}
}
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn retrieve_payment_method_data_with_permanent_token(
state: &SessionState,
locker_id: &str,
_payment_method_id: &str,
payment_intent: &PaymentIntent,
card_token_data: Option<&domain::CardToken>,
merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
mandate_id: Option<api_models::payments::MandateIds>,
payment_method_info: domain::PaymentMethod,
business_profile: &domain::Profile,
connector: Option<String>,
should_retry_with_pan: bool,
vault_data: Option<&domain_payments::VaultData>,
) -> RouterResult<domain::PaymentMethodData> {
let customer_id = payment_intent
.customer_id
.as_ref()
.get_required_value("customer_id")
.change_context(errors::ApiErrorResponse::UnprocessableEntity {
message: "no customer id provided for the payment".to_string(),
})?;
let network_tokenization_supported_connectors = &state
.conf
.network_tokenization_supported_connectors
.connector_list;
let connector_variant = connector
.as_ref()
.map(|conn| {
api_enums::Connector::from_str(conn.as_str())
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector:?}"))
})
.transpose()?;
let vault_fetch_action = decide_payment_method_retrieval_action(
business_profile.is_network_tokenization_enabled,
mandate_id,
connector_variant,
network_tokenization_supported_connectors,
should_retry_with_pan,
payment_method_info
.network_token_requestor_reference_id
.clone(),
);
let co_badged_card_data = payment_method_info
.get_payment_methods_data()
.and_then(|payment_methods_data| payment_methods_data.get_co_badged_card_data());
match vault_fetch_action {
VaultFetchAction::FetchCardDetailsFromLocker => {
let card = vault_data
.and_then(|vault_data| vault_data.get_card_vault_data())
.map(Ok)
.async_unwrap_or_else(|| async {
Box::pin(fetch_card_details_from_locker(
state,
customer_id,
&payment_intent.merchant_id,
locker_id,
card_token_data,
co_badged_card_data,
payment_method_info,
merchant_key_store,
))
.await
})
.await?;
Ok(domain::PaymentMethodData::Card(card))
}
VaultFetchAction::FetchCardDetailsForNetworkTransactionIdFlowFromLocker => {
fetch_card_details_for_network_transaction_flow_from_locker(
state,
customer_id,
&payment_intent.merchant_id,
locker_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch card information from the permanent locker")
}
VaultFetchAction::FetchNetworkTokenDataFromTokenizationService(
network_token_requestor_ref_id,
) => {
logger::info!("Fetching network token data from tokenization service");
match network_tokenization::get_token_from_tokenization_service(
state,
network_token_requestor_ref_id,
&payment_method_info,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch network token data from tokenization service")
{
Ok(network_token_data) => {
Ok(domain::PaymentMethodData::NetworkToken(network_token_data))
}
Err(err) => {
logger::info!(
"Failed to fetch network token data from tokenization service {err:?}"
);
logger::info!("Falling back to fetch card details from locker");
Ok(domain::PaymentMethodData::Card(
vault_data
.and_then(|vault_data| vault_data.get_card_vault_data())
.map(Ok)
.async_unwrap_or_else(|| async {
Box::pin(fetch_card_details_from_locker(
state,
customer_id,
&payment_intent.merchant_id,
locker_id,
card_token_data,
co_badged_card_data,
payment_method_info,
merchant_key_store,
))
.await
})
.await?,
))
}
}
}
VaultFetchAction::FetchNetworkTokenDetailsFromLocker(nt_data) => {
if let Some(network_token_locker_id) =
payment_method_info.network_token_locker_id.as_ref()
{
let network_token_data = vault_data
.and_then(|vault_data| vault_data.get_network_token_data())
.map(Ok)
.async_unwrap_or_else(|| async {
fetch_network_token_details_from_locker(
state,
customer_id,
&payment_intent.merchant_id,
network_token_locker_id,
nt_data,
)
.await
})
.await?;
Ok(domain::PaymentMethodData::NetworkToken(network_token_data))
} else {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Network token locker id is not present")
}
}
VaultFetchAction::NoFetchAction => Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment method data is not present"),
}
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn retrieve_card_with_permanent_token_for_external_authentication(
state: &SessionState,
locker_id: &str,
payment_intent: &PaymentIntent,
card_token_data: Option<&domain::CardToken>,
_merchant_key_store: &domain::MerchantKeyStore,
_storage_scheme: enums::MerchantStorageScheme,
) -> RouterResult<domain::PaymentMethodData> {
let customer_id = payment_intent
.customer_id
.as_ref()
.get_required_value("customer_id")
.change_context(errors::ApiErrorResponse::UnprocessableEntity {
message: "no customer id provided for the payment".to_string(),
})?;
Ok(domain::PaymentMethodData::Card(
fetch_card_details_from_internal_locker(
state,
customer_id,
&payment_intent.merchant_id,
locker_id,
card_token_data,
None,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch card information from the permanent locker")?,
))
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn fetch_card_details_from_locker(
state: &SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
locker_id: &str,
card_token_data: Option<&domain::CardToken>,
co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>,
payment_method_info: domain::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<domain::Card> {
match &payment_method_info.vault_source_details.clone() {
domain::PaymentMethodVaultSourceDetails::ExternalVault {
ref external_vault_source,
} => {
fetch_card_details_from_external_vault(
state,
merchant_id,
card_token_data,
co_badged_card_data,
payment_method_info,
merchant_key_store,
external_vault_source,
)
.await
}
domain::PaymentMethodVaultSourceDetails::InternalVault => {
fetch_card_details_from_internal_locker(
state,
customer_id,
merchant_id,
locker_id,
card_token_data,
co_badged_card_data,
)
.await
}
}
}
#[cfg(feature = "v1")]
pub async fn fetch_card_details_from_internal_locker(
state: &SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
locker_id: &str,
card_token_data: Option<&domain::CardToken>,
co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>,
) -> RouterResult<domain::Card> {
logger::debug!("Fetching card details from locker");
let card = cards::get_card_from_locker(state, customer_id, merchant_id, locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch card information from the permanent locker")?;
// The card_holder_name from locker retrieved card is considered if it is a non-empty string or else card_holder_name is picked
// from payment_method_data.card_token object
let name_on_card = if let Some(name) = card.name_on_card.clone() {
if name.clone().expose().is_empty() {
card_token_data
.and_then(|token_data| token_data.card_holder_name.clone())
.or(Some(name))
} else {
card.name_on_card
}
} else {
card_token_data.and_then(|token_data| token_data.card_holder_name.clone())
};
let api_card = api::Card {
card_number: card.card_number,
card_holder_name: name_on_card,
card_exp_month: card.card_exp_month,
card_exp_year: card.card_exp_year,
card_cvc: card_token_data
.cloned()
.unwrap_or_default()
.card_cvc
.unwrap_or_default(),
card_issuer: None,
nick_name: card.nick_name.map(masking::Secret::new),
card_network: card
.card_brand
.map(|card_brand| enums::CardNetwork::from_str(&card_brand))
.transpose()
.map_err(|e| {
logger::error!("Failed to parse card network {e:?}");
})
.ok()
.flatten(),
card_type: None,
card_issuing_country: None,
bank_code: None,
};
Ok(domain::Card::from((api_card, co_badged_card_data)))
}
#[cfg(feature = "v1")]
pub async fn fetch_card_details_from_external_vault(
state: &SessionState,
merchant_id: &id_type::MerchantId,
card_token_data: Option<&domain::CardToken>,
co_badged_card_data: Option<api_models::payment_methods::CoBadgedCardData>,
payment_method_info: domain::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
external_vault_mca_id: &id_type::MerchantConnectorAccountId,
) -> RouterResult<domain::Card> {
let key_manager_state = &state.into();
let merchant_connector_account_details = state
.store
.find_by_merchant_connector_account_merchant_id_merchant_connector_id(
key_manager_state,
merchant_id,
external_vault_mca_id,
merchant_key_store,
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantConnectorAccountNotFound {
id: external_vault_mca_id.get_string_repr().to_string(),
})?;
let vault_resp = vault::retrieve_payment_method_from_vault_external_v1(
state,
merchant_id,
&payment_method_info,
merchant_connector_account_details,
)
.await?;
let payment_methods_data = payment_method_info.get_payment_methods_data();
match vault_resp {
hyperswitch_domain_models::vault::PaymentMethodVaultingData::Card(card) => Ok(
domain::Card::from((card, card_token_data, co_badged_card_data)),
),
hyperswitch_domain_models::vault::PaymentMethodVaultingData::CardNumber(card_number) => {
let payment_methods_data = payment_methods_data
.get_required_value("PaymentMethodsData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Payment methods data not present")?;
let card = payment_methods_data
.get_card_details()
.get_required_value("CardDetails")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Card details not present")?;
Ok(
domain::Card::try_from((card_number, card_token_data, co_badged_card_data, card))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to generate card data")?,
)
}
}
}
#[cfg(feature = "v1")]
pub async fn fetch_network_token_details_from_locker(
state: &SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
network_token_locker_id: &str,
network_transaction_data: api_models::payments::NetworkTokenWithNTIRef,
) -> RouterResult<domain::NetworkTokenData> {
let mut token_data =
cards::get_card_from_locker(state, customer_id, merchant_id, network_token_locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"failed to fetch network token information from the permanent locker",
)?;
let expiry = network_transaction_data
.token_exp_month
.zip(network_transaction_data.token_exp_year);
if let Some((exp_month, exp_year)) = expiry {
token_data.card_exp_month = exp_month;
token_data.card_exp_year = exp_year;
}
let card_network = token_data
.card_brand
.map(|card_brand| enums::CardNetwork::from_str(&card_brand))
.transpose()
.map_err(|e| {
logger::error!("Failed to parse card network {e:?}");
})
.ok()
.flatten();
let network_token_data = domain::NetworkTokenData {
token_number: token_data.card_number,
token_cryptogram: None,
token_exp_month: token_data.card_exp_month,
token_exp_year: token_data.card_exp_year,
nick_name: token_data.nick_name.map(masking::Secret::new),
card_issuer: None,
card_network,
card_type: None,
card_issuing_country: None,
bank_code: None,
eci: None,
};
Ok(network_token_data)
}
#[cfg(feature = "v1")]
pub async fn fetch_card_details_for_network_transaction_flow_from_locker(
state: &SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
locker_id: &str,
) -> RouterResult<domain::PaymentMethodData> {
let card_details_from_locker =
cards::get_card_from_locker(state, customer_id, merchant_id, locker_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch card details from locker")?;
let card_network = card_details_from_locker
.card_brand
.map(|card_brand| enums::CardNetwork::from_str(&card_brand))
.transpose()
.map_err(|e| {
logger::error!("Failed to parse card network {e:?}");
})
.ok()
.flatten();
let card_details_for_network_transaction_id =
hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId {
card_number: card_details_from_locker.card_number,
card_exp_month: card_details_from_locker.card_exp_month,
card_exp_year: card_details_from_locker.card_exp_year,
card_issuer: None,
card_network,
card_type: None,
card_issuing_country: None,
bank_code: None,
nick_name: card_details_from_locker.nick_name.map(masking::Secret::new),
card_holder_name: card_details_from_locker.name_on_card.clone(),
};
Ok(
domain::PaymentMethodData::CardDetailsForNetworkTransactionId(
card_details_for_network_transaction_id,
),
)
}
#[cfg(feature = "v2")]
pub async fn retrieve_payment_method_from_db_with_token_data(
state: &SessionState,
merchant_key_store: &domain::MerchantKeyStore,
token_data: &storage::PaymentTokenData,
storage_scheme: storage::enums::MerchantStorageScheme,
) -> RouterResult<Option<domain::PaymentMethod>> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn retrieve_payment_method_from_db_with_token_data(
state: &SessionState,
merchant_key_store: &domain::MerchantKeyStore,
token_data: &storage::PaymentTokenData,
storage_scheme: storage::enums::MerchantStorageScheme,
) -> RouterResult<Option<domain::PaymentMethod>> {
match token_data {
storage::PaymentTokenData::PermanentCard(data) => {
if let Some(ref payment_method_id) = data.payment_method_id {
state
.store
.find_payment_method(
&(state.into()),
merchant_key_store,
payment_method_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("error retrieving payment method from DB")
.map(Some)
} else {
Ok(None)
}
}
storage::PaymentTokenData::WalletToken(data) => state
.store
.find_payment_method(
&(state.into()),
merchant_key_store,
&data.payment_method_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)
.attach_printable("error retrieveing payment method from DB")
.map(Some),
storage::PaymentTokenData::Temporary(_)
| storage::PaymentTokenData::TemporaryGeneric(_)
| storage::PaymentTokenData::Permanent(_)
| storage::PaymentTokenData::AuthBankDebit(_) => Ok(None),
}
}
#[cfg(feature = "v1")]
pub async fn retrieve_payment_token_data(
state: &SessionState,
token: String,
payment_method: Option<storage_enums::PaymentMethod>,
) -> RouterResult<storage::PaymentTokenData> {
let redis_conn = state
.store
.get_redis_conn()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get redis connection")?;
let key = format!(
"pm_token_{}_{}_hyperswitch",
token,
payment_method.get_required_value("payment_method")?
);
let token_data_string = redis_conn
.get_key::<Option<String>>(&key.into())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to fetch the token from redis")?
.ok_or(error_stack::Report::new(
errors::ApiErrorResponse::UnprocessableEntity {
message: "Token is invalid or expired".to_owned(),
},
))?;
let token_data_result = token_data_string
.clone()
.parse_struct("PaymentTokenData")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to deserialize hyperswitch token data");
let token_data = match token_data_result {
Ok(data) => data,
Err(e) => {
// The purpose of this logic is backwards compatibility to support tokens
// in redis that might be following the old format.
if token_data_string.starts_with('{') {
return Err(e);
} else {
storage::PaymentTokenData::temporary_generic(token_data_string)
}
}
};
Ok(token_data)
}
#[cfg(feature = "v2")]
pub async fn make_pm_data<'a, F: Clone, R, D>(
_operation: BoxedOperation<'a, F, R, D>,
_state: &'a SessionState,
_payment_data: &mut PaymentData<F>,
_merchant_key_store: &domain::MerchantKeyStore,
_customer: &Option<domain::Customer>,
_storage_scheme: common_enums::enums::MerchantStorageScheme,
_business_profile: Option<&domain::Profile>,
) -> RouterResult<(
BoxedOperation<'a, F, R, D>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
todo!()
}
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
pub async fn make_pm_data<'a, F: Clone, R, D>(
operation: BoxedOperation<'a, F, R, D>,
state: &'a SessionState,
payment_data: &mut PaymentData<F>,
merchant_key_store: &domain::MerchantKeyStore,
customer: &Option<domain::Customer>,
storage_scheme: common_enums::enums::MerchantStorageScheme,
business_profile: &domain::Profile,
should_retry_with_pan: bool,
) -> RouterResult<(
BoxedOperation<'a, F, R, D>,
Option<domain::PaymentMethodData>,
Option<String>,
)> {
use super::OperationSessionSetters;
use crate::core::payments::OperationSessionGetters;
let request = payment_data.payment_method_data.clone();
let mut card_token_data = payment_data
.payment_method_data
.clone()
.and_then(|pmd| match pmd {
domain::PaymentMethodData::CardToken(token_data) => Some(token_data),
_ => None,
})
.or(Some(domain::CardToken::default()));
if let Some(cvc) = payment_data.card_cvc.clone() {
if let Some(token_data) = card_token_data.as_mut() {
token_data.card_cvc = Some(cvc);
}
}
if payment_data.token_data.is_none() {
if let Some(payment_method_info) = &payment_data.payment_method_info {
if payment_method_info.get_payment_method_type()
== Some(storage_enums::PaymentMethod::Card)
{
payment_data.token_data =
Some(storage::PaymentTokenData::PermanentCard(CardTokenData {
payment_method_id: Some(payment_method_info.get_id().clone()),
locker_id: payment_method_info
.locker_id
.clone()
.or(Some(payment_method_info.get_id().clone())),
token: payment_method_info
.locker_id
.clone()
.unwrap_or(payment_method_info.get_id().clone()),
network_token_locker_id: payment_method_info
.network_token_requestor_reference_id
.clone()
.or(Some(payment_method_info.get_id().clone())),
}));
}
}
}
let mandate_id = payment_data.mandate_id.clone();
// TODO: Handle case where payment method and token both are present in request properly.
let (payment_method, pm_id) = match (&request, payment_data.token_data.as_ref()) {
(_, Some(hyperswitch_token)) => {
let existing_vault_data = payment_data.get_vault_operation();
let vault_data = existing_vault_data.and_then(|data| match data {
domain_payments::VaultOperation::ExistingVaultData(vault_data) => Some(vault_data),
domain_payments::VaultOperation::SaveCardData(_)
| domain_payments::VaultOperation::SaveCardAndNetworkTokenData(_) => None,
});
let pm_data = Box::pin(payment_methods::retrieve_payment_method_with_token(
state,
merchant_key_store,
hyperswitch_token,
&payment_data.payment_intent,
&payment_data.payment_attempt,
card_token_data.as_ref(),
customer,
storage_scheme,
mandate_id,
payment_data.payment_method_info.clone(),
business_profile,
should_retry_with_pan,
vault_data,
))
.await;
let payment_method_details = pm_data.attach_printable("in 'make_pm_data'")?;
if let Some(ref payment_method_data) = payment_method_details.payment_method_data {
let updated_vault_operation =
domain_payments::VaultOperation::get_updated_vault_data(
existing_vault_data,
payment_method_data,
);
if let Some(vault_operation) = updated_vault_operation {
payment_data.set_vault_operation(vault_operation);
}
// Temporarily store payment method data along with the cvc in redis for saved card payments, if required by the connector based on its configs
if payment_data.token.is_none() {
let (_, payment_token) = payment_methods::retrieve_payment_method_core(
&Some(payment_method_data.clone()),
state,
&payment_data.payment_intent,
&payment_data.payment_attempt,
merchant_key_store,
Some(business_profile),
)
.await?;
payment_data.token = payment_token;
}
};
Ok::<_, error_stack::Report<errors::ApiErrorResponse>>(
if let Some(payment_method_data) = payment_method_details.payment_method_data {
payment_data.payment_attempt.payment_method =
payment_method_details.payment_method;
(
Some(payment_method_data),
payment_method_details.payment_method_id,
)
} else {
(None, payment_method_details.payment_method_id)
},
)
}
(Some(_), _) => {
let (payment_method_data, payment_token) =
payment_methods::retrieve_payment_method_core(
&request,
state,
&payment_data.payment_intent,
&payment_data.payment_attempt,
merchant_key_store,
Some(business_profile),
)
.await?;
payment_data.token = payment_token;
Ok((payment_method_data, None))
}
_ => Ok((None, None)),
}?;
Ok((operation, payment_method, pm_id))
}
#[cfg(feature = "v1")]
pub async fn store_in_vault_and_generate_ppmt(
state: &SessionState,
payment_method_data: &domain::PaymentMethodData,
payment_intent: &PaymentIntent,
payment_attempt: &PaymentAttempt,
payment_method: enums::PaymentMethod,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<String> {
let router_token = vault::Vault::store_payment_method_data_in_locker(
state,
None,
payment_method_data,
payment_intent.customer_id.to_owned(),
payment_method,
merchant_key_store,
)
.await?;
let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
let key_for_hyperswitch_token = payment_attempt.get_payment_method().map(|payment_method| {
payment_methods_handler::ParentPaymentMethodToken::create_key_for_token((
&parent_payment_method_token,
payment_method,
))
});
let intent_fulfillment_time = business_profile
.and_then(|b_profile| b_profile.get_order_fulfillment_time())
.unwrap_or(consts::DEFAULT_FULFILLMENT_TIME);
if let Some(key_for_hyperswitch_token) = key_for_hyperswitch_token {
key_for_hyperswitch_token
.insert(
intent_fulfillment_time,
storage::PaymentTokenData::temporary_generic(router_token),
state,
)
.await?;
};
Ok(parent_payment_method_token)
}
#[cfg(feature = "v2")]
pub async fn store_payment_method_data_in_vault(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<Option<String>> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn store_payment_method_data_in_vault(
state: &SessionState,
payment_attempt: &PaymentAttempt,
payment_intent: &PaymentIntent,
payment_method: enums::PaymentMethod,
payment_method_data: &domain::PaymentMethodData,
merchant_key_store: &domain::MerchantKeyStore,
business_profile: Option<&domain::Profile>,
) -> RouterResult<Option<String>> {
if should_store_payment_method_data_in_vault(
&state.conf.temp_locker_enable_config,
payment_attempt.connector.clone(),
payment_method,
) || payment_intent.request_external_three_ds_authentication == Some(true)
{
let parent_payment_method_token = store_in_vault_and_generate_ppmt(
state,
payment_method_data,
payment_intent,
payment_attempt,
payment_method,
merchant_key_store,
business_profile,
)
.await?;
return Ok(Some(parent_payment_method_token));
}
Ok(None)
}
pub fn should_store_payment_method_data_in_vault(
temp_locker_enable_config: &TempLockerEnableConfig,
option_connector: Option<String>,
payment_method: enums::PaymentMethod,
) -> bool {
option_connector
.map(|connector| {
temp_locker_enable_config
.0
.get(&connector)
.map(|config| config.payment_method.contains(&payment_method))
.unwrap_or(false)
})
.unwrap_or(true)
}
#[instrument(skip_all)]
pub(crate) fn validate_capture_method(
capture_method: storage_enums::CaptureMethod,
) -> RouterResult<()> {
utils::when(
capture_method == storage_enums::CaptureMethod::Automatic,
|| {
Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState {
field_name: "capture_method".to_string(),
current_flow: "captured".to_string(),
current_value: capture_method.to_string(),
states: "manual, manual_multiple, scheduled".to_string()
}))
},
)
}
#[instrument(skip_all)]
pub(crate) fn validate_status_with_capture_method(
status: storage_enums::IntentStatus,
capture_method: storage_enums::CaptureMethod,
) -> RouterResult<()> {
if status == storage_enums::IntentStatus::Processing
&& !(capture_method == storage_enums::CaptureMethod::ManualMultiple)
{
return Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState {
field_name: "capture_method".to_string(),
current_flow: "captured".to_string(),
current_value: capture_method.to_string(),
states: "manual_multiple".to_string()
}));
}
utils::when(
status != storage_enums::IntentStatus::RequiresCapture
&& status != storage_enums::IntentStatus::PartiallyCapturedAndCapturable
&& status != storage_enums::IntentStatus::PartiallyAuthorizedAndRequiresCapture
&& status != storage_enums::IntentStatus::Processing,
|| {
Err(report!(errors::ApiErrorResponse::PaymentUnexpectedState {
field_name: "payment.status".to_string(),
current_flow: "captured".to_string(),
current_value: status.to_string(),
states: "requires_capture, partially_captured_and_capturable, processing"
.to_string()
}))
},
)
}
#[instrument(skip_all)]
pub(crate) fn validate_amount_to_capture(
amount: i64,
amount_to_capture: Option<i64>,
) -> RouterResult<()> {
utils::when(amount_to_capture.is_some_and(|value| value <= 0), || {
Err(report!(errors::ApiErrorResponse::InvalidDataFormat {
field_name: "amount".to_string(),
expected_format: "positive integer".to_string(),
}))
})?;
utils::when(
amount_to_capture.is_some() && (Some(amount) < amount_to_capture),
|| {
Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: "amount_to_capture is greater than amount".to_string()
}))
},
)
}
#[cfg(feature = "v1")]
#[instrument(skip_all)]
pub(crate) fn validate_payment_method_fields_present(
req: &api_models::payments::PaymentsRequest,
) -> RouterResult<()> {
let payment_method_data =
req.payment_method_data
.as_ref()
.and_then(|request_payment_method_data| {
request_payment_method_data.payment_method_data.as_ref()
});
utils::when(
req.payment_method.is_none() && payment_method_data.is_some(),
|| {
Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_method",
})
},
)?;
utils::when(
!matches!(
req.payment_method,
Some(api_enums::PaymentMethod::Card) | None
) && (req.payment_method_type.is_none()),
|| {
Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_method_type",
})
},
)?;
utils::when(
req.payment_method.is_some()
&& payment_method_data.is_none()
&& req.payment_token.is_none()
&& req.recurring_details.is_none()
&& req.ctp_service_details.is_none(),
|| {
Err(errors::ApiErrorResponse::MissingRequiredField {
field_name: "payment_method_data",
})
},
)?;
utils::when(
req.payment_method.is_some() && req.payment_method_type.is_some(),
|| {
req.payment_method
.map_or(Ok(()), |req_payment_method| {
req.payment_method_type.map_or(Ok(()), |req_payment_method_type| {
if !validate_payment_method_type_against_payment_method(req_payment_method, req_payment_method_type) {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: ("payment_method_type doesn't correspond to the specified payment_method"
.to_string()),
})
} else {
Ok(())
}
})
})
},
)?;
let validate_payment_method_and_payment_method_data =
|req_payment_method_data, req_payment_method: api_enums::PaymentMethod| {
api_enums::PaymentMethod::foreign_try_from(req_payment_method_data).and_then(|payment_method|
if req_payment_method != payment_method {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: ("payment_method_data doesn't correspond to the specified payment_method"
.to_string()),
})
} else {
Ok(())
})
};
utils::when(
req.payment_method.is_some() && payment_method_data.is_some(),
|| {
payment_method_data
.cloned()
.map_or(Ok(()), |payment_method_data| {
req.payment_method.map_or(Ok(()), |req_payment_method| {
validate_payment_method_and_payment_method_data(
payment_method_data,
req_payment_method,
)
})
})
},
)?;
Ok(())
}
pub fn check_force_psync_precondition(status: storage_enums::AttemptStatus) -> bool {
!matches!(
status,
storage_enums::AttemptStatus::Charged
| storage_enums::AttemptStatus::AutoRefunded
| storage_enums::AttemptStatus::Voided
| storage_enums::AttemptStatus::CodInitiated
| storage_enums::AttemptStatus::Started
| storage_enums::AttemptStatus::Failure
)
}
pub fn append_option<T, U, F, V>(func: F, option1: Option<T>, option2: Option<U>) -> Option<V>
where
F: FnOnce(T, U) -> V,
{
Some(func(option1?, option2?))
}
#[cfg(all(feature = "olap", feature = "v1"))]
pub(super) async fn filter_by_constraints(
state: &SessionState,
constraints: &PaymentIntentFetchConstraints,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: storage_enums::MerchantStorageScheme,
) -> CustomResult<Vec<PaymentIntent>, errors::StorageError> {
let db = &*state.store;
let result = db
.filter_payment_intent_by_constraints(
&(state).into(),
merchant_id,
constraints,
key_store,
storage_scheme,
)
.await?;
Ok(result)
}
#[cfg(feature = "olap")]
pub(super) fn validate_payment_list_request(
req: &api::PaymentListConstraints,
) -> CustomResult<(), errors::ApiErrorResponse> {
use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V1;
utils::when(
req.limit > PAYMENTS_LIST_MAX_LIMIT_V1 || req.limit < 1,
|| {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!("limit should be in between 1 and {PAYMENTS_LIST_MAX_LIMIT_V1}"),
})
},
)?;
Ok(())
}
#[cfg(feature = "olap")]
pub(super) fn validate_payment_list_request_for_joins(
limit: u32,
) -> CustomResult<(), errors::ApiErrorResponse> {
use common_utils::consts::PAYMENTS_LIST_MAX_LIMIT_V2;
utils::when(!(1..=PAYMENTS_LIST_MAX_LIMIT_V2).contains(&limit), || {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: format!("limit should be in between 1 and {PAYMENTS_LIST_MAX_LIMIT_V2}"),
})
})?;
Ok(())
}
|
crates/router/src/core/payments/helpers.rs#chunk2
|
router
|
chunk
| null | null | null | 8,191
| null | null | null | null | null | null | null |
// Struct: IncrementalAuthorization
// File: crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct IncrementalAuthorization
|
crates/hyperswitch_domain_models/src/router_flow_types/payments.rs
|
hyperswitch_domain_models
|
struct_definition
|
IncrementalAuthorization
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// File: crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs
// Module: hyperswitch_connectors
// Public structs: 29
use bytes::Bytes;
use common_enums::{
self, AttemptStatus, AuthorizationStatus, CaptureMethod, Currency, FutureUsage,
PaymentMethodStatus, RefundStatus,
};
use common_utils::{date_time, ext_traits::Encode, pii, types::MinorUnit};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
address::AddressDetails,
payment_method_data::{Card, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, PaymentMethodToken, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{
AuthenticationData, PaymentsAuthorizeData, PaymentsCancelData, PaymentsCaptureData,
PaymentsIncrementalAuthorizationData, PaymentsSyncData, ResponseId,
SetupMandateRequestData,
},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsIncrementalAuthorizationRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{consts, errors};
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
unimplemented_payment_method,
utils::{
self, AddressData, AddressDetailsData, CardData, CardIssuer, PaymentsAuthorizeRequestData,
RouterData as _,
},
};
const THREE_DS_MAX_SUPPORTED_VERSION: &str = "2.2.0";
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq, Clone)]
#[serde(transparent)]
pub struct ArchipelTenantId(pub String);
impl From<String> for ArchipelTenantId {
fn from(value: String) -> Self {
Self(value)
}
}
pub struct ArchipelRouterData<T> {
pub amount: MinorUnit,
pub tenant_id: ArchipelTenantId,
pub router_data: T,
}
impl<T> From<(MinorUnit, ArchipelTenantId, T)> for ArchipelRouterData<T> {
fn from((amount, tenant_id, router_data): (MinorUnit, ArchipelTenantId, T)) -> Self {
Self {
amount,
tenant_id,
router_data,
}
}
}
pub struct ArchipelAuthType {
pub(super) ca_certificate: Option<Secret<String>>,
}
impl TryFrom<&ConnectorAuthType> for ArchipelAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::HeaderKey { api_key } => Ok(Self {
ca_certificate: Some(api_key.to_owned()),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Debug, Deserialize, Serialize, Eq, PartialEq)]
pub struct ArchipelConfigData {
pub tenant_id: ArchipelTenantId,
pub platform_url: String,
}
impl TryFrom<&Option<pii::SecretSerdeValue>> for ArchipelConfigData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(connector_metadata: &Option<pii::SecretSerdeValue>) -> Result<Self, Self::Error> {
let config_data = utils::to_connector_meta_from_secret::<Self>(connector_metadata.clone())
.change_context(errors::ConnectorError::InvalidConnectorConfig {
config: "metadata. Required fields: tenant_id, platform_url",
})?;
Ok(config_data)
}
}
#[derive(Debug, Default, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum ArchipelPaymentInitiator {
#[default]
Customer,
Merchant,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ArchipelWalletProvider {
ApplePay,
GooglePay,
SamsungPay,
}
#[derive(Debug, Default, Serialize, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum ArchipelPaymentCertainty {
#[default]
Final,
Estimated,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelOrderRequest {
amount: MinorUnit,
currency: String,
certainty: ArchipelPaymentCertainty,
initiator: ArchipelPaymentInitiator,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
pub struct CardExpiryDate {
month: Secret<String>,
year: Secret<String>,
}
#[derive(Debug, Serialize, Default, Eq, PartialEq, Clone)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ApplicationSelectionIndicator {
#[default]
ByDefault,
CustomerChoice,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct Archipel3DS {
#[serde(rename = "acsTransID")]
acs_trans_id: Option<Secret<String>>,
#[serde(rename = "dsTransID")]
ds_trans_id: Option<Secret<String>>,
#[serde(rename = "3DSRequestorName")]
three_ds_requestor_name: Option<Secret<String>>,
#[serde(rename = "3DSAuthDate")]
three_ds_auth_date: Option<String>,
#[serde(rename = "3DSAuthAmt")]
three_ds_auth_amt: Option<MinorUnit>,
#[serde(rename = "3DSAuthStatus")]
three_ds_auth_status: Option<String>,
#[serde(rename = "3DSMaxSupportedVersion")]
three_ds_max_supported_version: String,
#[serde(rename = "3DSVersion")]
three_ds_version: Option<common_utils::types::SemanticVersion>,
authentication_value: Secret<String>,
authentication_method: Option<Secret<String>>,
eci: Option<String>,
}
impl From<AuthenticationData> for Archipel3DS {
fn from(three_ds_data: AuthenticationData) -> Self {
let now = date_time::date_as_yyyymmddthhmmssmmmz().ok();
Self {
acs_trans_id: None,
ds_trans_id: three_ds_data.ds_trans_id.map(Secret::new),
three_ds_requestor_name: None,
three_ds_auth_date: now,
three_ds_auth_amt: None,
three_ds_auth_status: None,
three_ds_max_supported_version: THREE_DS_MAX_SUPPORTED_VERSION.into(),
three_ds_version: three_ds_data.message_version,
authentication_value: three_ds_data.cavv,
authentication_method: None,
eci: three_ds_data.eci,
}
}
}
#[derive(Clone, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelCardHolder {
billing_address: Option<ArchipelBillingAddress>,
}
impl From<Option<ArchipelBillingAddress>> for ArchipelCardHolder {
fn from(value: Option<ArchipelBillingAddress>) -> Self {
Self {
billing_address: value,
}
}
}
#[derive(Clone, Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelBillingAddress {
address: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
}
pub trait ToArchipelBillingAddress {
fn to_archipel_billing_address(&self) -> Option<ArchipelBillingAddress>;
}
impl ToArchipelBillingAddress for AddressDetails {
fn to_archipel_billing_address(&self) -> Option<ArchipelBillingAddress> {
let address = self.get_combined_address_line().ok();
let postal_code = self.get_optional_zip();
match (address, postal_code) {
(None, None) => None,
(addr, zip) => Some(ArchipelBillingAddress {
address: addr,
postal_code: zip,
}),
}
}
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum ArchipelCredentialIndicatorStatus {
Initial,
Subsequent,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelCredentialIndicator {
status: ArchipelCredentialIndicatorStatus,
recurring: Option<bool>,
transaction_id: Option<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct TokenizedCardData {
card_data: ArchipelTokenizedCard,
wallet_information: ArchipelWalletInformation,
}
impl TryFrom<(&WalletData, &Option<PaymentMethodToken>)> for TokenizedCardData {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(wallet_data, pm_token): (&WalletData, &Option<PaymentMethodToken>),
) -> Result<Self, Self::Error> {
let WalletData::ApplePay(apple_pay_data) = wallet_data else {
return Err(error_stack::Report::from(
errors::ConnectorError::NotSupported {
message: "Wallet type used".to_string(),
connector: "Archipel",
},
));
};
let Some(PaymentMethodToken::ApplePayDecrypt(apple_pay_decrypt_data)) = pm_token else {
return Err(error_stack::Report::from(unimplemented_payment_method!(
"Apple Pay",
"Manual",
"Archipel"
)));
};
let card_number = apple_pay_decrypt_data
.application_primary_account_number
.clone();
let expiry_year_2_digit = apple_pay_decrypt_data
.get_two_digit_expiry_year()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "Apple pay expiry year",
})?;
let expiry_month = apple_pay_decrypt_data.get_expiry_month().change_context(
errors::ConnectorError::InvalidDataFormat {
field_name: "expiration_month",
},
)?;
Ok(Self {
card_data: ArchipelTokenizedCard {
expiry: CardExpiryDate {
year: expiry_year_2_digit,
month: expiry_month,
},
number: card_number,
scheme: ArchipelCardScheme::from(apple_pay_data.payment_method.network.as_str()),
},
wallet_information: {
ArchipelWalletInformation {
wallet_provider: ArchipelWalletProvider::ApplePay,
wallet_indicator: apple_pay_decrypt_data.payment_data.eci_indicator.clone(),
wallet_cryptogram: apple_pay_decrypt_data
.payment_data
.online_payment_cryptogram
.clone(),
}
},
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelTokenizedCard {
number: cards::CardNumber,
expiry: CardExpiryDate,
scheme: ArchipelCardScheme,
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelCard {
number: cards::CardNumber,
expiry: CardExpiryDate,
security_code: Option<Secret<String>>,
card_holder_name: Option<Secret<String>>,
application_selection_indicator: ApplicationSelectionIndicator,
scheme: ArchipelCardScheme,
}
impl TryFrom<(Option<Secret<String>>, Option<ArchipelCardHolder>, &Card)> for ArchipelCard {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(card_holder_name, card_holder_billing, ccard): (
Option<Secret<String>>,
Option<ArchipelCardHolder>,
&Card,
),
) -> Result<Self, Self::Error> {
// NOTE: Archipel does not accept `card.card_holder_name` field without `cardholder` field.
// So if `card_holder` is None, `card.card_holder_name` must also be None.
// However, the reverse is allowed — the `cardholder` field can exist without `card.card_holder_name`.
let card_holder_name = card_holder_billing
.as_ref()
.and_then(|_| ccard.card_holder_name.clone().or(card_holder_name.clone()));
let scheme: ArchipelCardScheme = ccard.get_card_issuer().ok().into();
Ok(Self {
number: ccard.card_number.clone(),
expiry: CardExpiryDate {
month: ccard.card_exp_month.clone(),
year: ccard.get_card_expiry_year_2_digit()?,
},
security_code: Some(ccard.card_cvc.clone()),
application_selection_indicator: ApplicationSelectionIndicator::ByDefault,
card_holder_name,
scheme,
})
}
}
impl
TryFrom<(
Option<Secret<String>>,
Option<ArchipelCardHolder>,
&hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId,
)> for ArchipelCard
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(card_holder_name, card_holder_billing, card_details): (
Option<Secret<String>>,
Option<ArchipelCardHolder>,
&hyperswitch_domain_models::payment_method_data::CardDetailsForNetworkTransactionId,
),
) -> Result<Self, Self::Error> {
// NOTE: Archipel does not accept `card.card_holder_name` field without `cardholder` field.
// So if `card_holder` is None, `card.card_holder_name` must also be None.
// However, the reverse is allowed — the `cardholder` field can exist without `card.card_holder_name`.
let card_holder_name = card_holder_billing.as_ref().and_then(|_| {
card_details
.card_holder_name
.clone()
.or(card_holder_name.clone())
});
let scheme: ArchipelCardScheme = card_details.get_card_issuer().ok().into();
Ok(Self {
number: card_details.card_number.clone(),
expiry: CardExpiryDate {
month: card_details.card_exp_month.clone(),
year: card_details.get_card_expiry_year_2_digit()?,
},
security_code: None,
application_selection_indicator: ApplicationSelectionIndicator::ByDefault,
card_holder_name,
scheme,
})
}
}
#[derive(Debug, Serialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelWalletInformation {
wallet_indicator: Option<String>,
wallet_provider: ArchipelWalletProvider,
wallet_cryptogram: Secret<String>,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelPaymentInformation {
order: ArchipelOrderRequest,
cardholder: Option<ArchipelCardHolder>,
card_holder_name: Option<Secret<String>>,
credential_indicator: Option<ArchipelCredentialIndicator>,
stored_on_file: bool,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelWalletAuthorizationRequest {
order: ArchipelOrderRequest,
card: ArchipelTokenizedCard,
cardholder: Option<ArchipelCardHolder>,
wallet: ArchipelWalletInformation,
#[serde(rename = "3DS")]
three_ds: Option<Archipel3DS>,
credential_indicator: Option<ArchipelCredentialIndicator>,
stored_on_file: bool,
tenant_id: ArchipelTenantId,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelCardAuthorizationRequest {
order: ArchipelOrderRequest,
card: ArchipelCard,
cardholder: Option<ArchipelCardHolder>,
#[serde(rename = "3DS")]
three_ds: Option<Archipel3DS>,
credential_indicator: Option<ArchipelCredentialIndicator>,
stored_on_file: bool,
tenant_id: ArchipelTenantId,
}
// PaymentsResponse
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
#[serde(rename_all = "UPPERCASE")]
pub enum ArchipelCardScheme {
Amex,
Mastercard,
Visa,
Discover,
Diners,
Unknown,
}
impl From<&str> for ArchipelCardScheme {
fn from(input: &str) -> Self {
match input {
"Visa" => Self::Visa,
"Amex" => Self::Amex,
"Diners" => Self::Diners,
"MasterCard" => Self::Mastercard,
"Discover" => Self::Discover,
_ => Self::Unknown,
}
}
}
impl From<Option<CardIssuer>> for ArchipelCardScheme {
fn from(card_issuer: Option<CardIssuer>) -> Self {
match card_issuer {
Some(CardIssuer::Visa) => Self::Visa,
Some(CardIssuer::Master | CardIssuer::Maestro) => Self::Mastercard,
Some(CardIssuer::AmericanExpress) => Self::Amex,
Some(CardIssuer::Discover) => Self::Discover,
Some(CardIssuer::DinersClub) => Self::Diners,
_ => Self::Unknown,
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
#[serde(rename_all = "lowercase")]
pub enum ArchipelPaymentStatus {
#[default]
Succeeded,
Failed,
}
impl TryFrom<(AttemptStatus, CaptureMethod)> for ArchipelPaymentFlow {
type Error = errors::ConnectorError;
fn try_from(
(status, capture_method): (AttemptStatus, CaptureMethod),
) -> Result<Self, Self::Error> {
let is_auto_capture = matches!(capture_method, CaptureMethod::Automatic);
match status {
AttemptStatus::AuthenticationFailed => Ok(Self::Verify),
AttemptStatus::Authorizing
| AttemptStatus::Authorized
| AttemptStatus::AuthorizationFailed => Ok(Self::Authorize),
AttemptStatus::Voided | AttemptStatus::VoidInitiated | AttemptStatus::VoidFailed => {
Ok(Self::Cancel)
}
AttemptStatus::CaptureInitiated | AttemptStatus::CaptureFailed => {
if is_auto_capture {
Ok(Self::Pay)
} else {
Ok(Self::Capture)
}
}
AttemptStatus::PaymentMethodAwaited | AttemptStatus::ConfirmationAwaited => {
if is_auto_capture {
Ok(Self::Pay)
} else {
Ok(Self::Authorize)
}
}
_ => Err(errors::ConnectorError::ProcessingStepFailed(Some(
Bytes::from_static(
"Impossible to determine Archipel flow from AttemptStatus".as_bytes(),
),
))),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub enum ArchipelPaymentFlow {
Verify,
Authorize,
Pay,
Capture,
Cancel,
}
struct ArchipelFlowStatus {
status: ArchipelPaymentStatus,
flow: ArchipelPaymentFlow,
}
impl ArchipelFlowStatus {
fn new(status: ArchipelPaymentStatus, flow: ArchipelPaymentFlow) -> Self {
Self { status, flow }
}
}
impl From<ArchipelFlowStatus> for AttemptStatus {
fn from(ArchipelFlowStatus { status, flow }: ArchipelFlowStatus) -> Self {
match status {
ArchipelPaymentStatus::Succeeded => match flow {
ArchipelPaymentFlow::Authorize => Self::Authorized,
ArchipelPaymentFlow::Pay
| ArchipelPaymentFlow::Verify
| ArchipelPaymentFlow::Capture => Self::Charged,
ArchipelPaymentFlow::Cancel => Self::Voided,
},
ArchipelPaymentStatus::Failed => match flow {
ArchipelPaymentFlow::Authorize | ArchipelPaymentFlow::Pay => {
Self::AuthorizationFailed
}
ArchipelPaymentFlow::Verify => Self::AuthenticationFailed,
ArchipelPaymentFlow::Capture => Self::CaptureFailed,
ArchipelPaymentFlow::Cancel => Self::VoidFailed,
},
}
}
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Clone)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelOrderResponse {
id: String,
amount: Option<i64>,
currency: Option<Currency>,
captured_amount: Option<i64>,
authorized_amount: Option<i64>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct ArchipelErrorMessage {
pub code: String,
pub description: Option<String>,
}
impl Default for ArchipelErrorMessage {
fn default() -> Self {
Self {
code: consts::NO_ERROR_CODE.to_string(),
description: Some(consts::NO_ERROR_MESSAGE.to_string()),
}
}
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
struct ArchipelErrorMessageWithHttpCode {
error_message: ArchipelErrorMessage,
http_code: u16,
}
impl ArchipelErrorMessageWithHttpCode {
fn new(error_message: ArchipelErrorMessage, http_code: u16) -> Self {
Self {
error_message,
http_code,
}
}
}
#[derive(Debug, Serialize, Deserialize, Eq, PartialEq, Default)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelTransactionMetadata {
pub transaction_id: String,
pub transaction_date: String,
pub financial_network_code: Option<String>,
pub issuer_transaction_id: Option<String>,
pub response_code: Option<String>,
pub authorization_code: Option<String>,
pub payment_account_reference: Option<Secret<String>>,
}
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct ArchipelPaymentsResponse {
order: ArchipelOrderResponse,
transaction_id: String,
transaction_date: String,
transaction_result: ArchipelPaymentStatus,
error: Option<ArchipelErrorMessage>,
financial_network_code: Option<String>,
issuer_transaction_id: Option<String>,
response_code: Option<String>,
authorization_code: Option<String>,
payment_account_reference: Option<Secret<String>>,
}
impl From<&ArchipelPaymentsResponse> for ArchipelTransactionMetadata {
fn from(payment_response: &ArchipelPaymentsResponse) -> Self {
Self {
transaction_id: payment_response.transaction_id.clone(),
transaction_date: payment_response.transaction_date.clone(),
financial_network_code: payment_response.financial_network_code.clone(),
issuer_transaction_id: payment_response.issuer_transaction_id.clone(),
response_code: payment_response.response_code.clone(),
authorization_code: payment_response.authorization_code.clone(),
payment_account_reference: payment_response.payment_account_reference.clone(),
}
}
}
// AUTHORIZATION FLOW
impl TryFrom<(MinorUnit, &PaymentsAuthorizeRouterData)> for ArchipelPaymentInformation {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
(amount, router_data): (MinorUnit, &PaymentsAuthorizeRouterData),
) -> Result<Self, Self::Error> {
let is_recurring_payment = router_data
.request
.mandate_id
.as_ref()
.and_then(|mandate_ids| mandate_ids.mandate_id.as_ref())
.is_some();
let is_subsequent_trx = router_data
.request
.mandate_id
.as_ref()
.and_then(|mandate_ids| mandate_ids.mandate_reference_id.as_ref())
.is_some();
let is_saved_card_payment = (router_data.request.is_mandate_payment())
| (router_data.request.setup_future_usage == Some(FutureUsage::OnSession))
| (router_data.payment_method_status == Some(PaymentMethodStatus::Active));
let certainty = if router_data.request.request_incremental_authorization {
if is_recurring_payment {
ArchipelPaymentCertainty::Final
} else {
ArchipelPaymentCertainty::Estimated
}
} else {
ArchipelPaymentCertainty::Final
};
let transaction_initiator = if is_recurring_payment {
ArchipelPaymentInitiator::Merchant
} else {
ArchipelPaymentInitiator::Customer
};
let order = ArchipelOrderRequest {
amount,
currency: router_data.request.currency.to_string(),
certainty,
initiator: transaction_initiator.clone(),
};
let cardholder = router_data
.get_billing_address()
.ok()
.and_then(|address| address.to_archipel_billing_address())
.map(|billing_address| ArchipelCardHolder {
billing_address: Some(billing_address),
});
// NOTE: Archipel does not accept `card.card_holder_name` field without `cardholder` field.
// So if `card_holder` is None, `card.card_holder_name` must also be None.
// However, the reverse is allowed — the `cardholder` field can exist without `card.card_holder_name`.
let card_holder_name = cardholder.as_ref().and_then(|_| {
router_data
.get_billing()
.ok()
.and_then(|billing| billing.get_optional_full_name())
});
let indicator_status = if is_subsequent_trx {
ArchipelCredentialIndicatorStatus::Subsequent
} else {
ArchipelCredentialIndicatorStatus::Initial
};
let stored_on_file =
is_saved_card_payment | router_data.request.is_customer_initiated_mandate_payment();
let credential_indicator = stored_on_file.then(|| ArchipelCredentialIndicator {
status: indicator_status.clone(),
recurring: Some(is_recurring_payment),
transaction_id: match indicator_status {
ArchipelCredentialIndicatorStatus::Initial => None,
ArchipelCredentialIndicatorStatus::Subsequent => {
router_data.request.get_optional_network_transaction_id()
}
},
});
Ok(Self {
order,
cardholder,
card_holder_name,
credential_indicator,
stored_on_file,
})
}
}
impl TryFrom<ArchipelRouterData<&PaymentsAuthorizeRouterData>>
for ArchipelCardAuthorizationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ArchipelRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let ArchipelRouterData {
amount,
tenant_id,
router_data,
} = item;
let payment_information: ArchipelPaymentInformation =
ArchipelPaymentInformation::try_from((amount, router_data))?;
let payment_method_data = match &item.router_data.request.payment_method_data {
PaymentMethodData::Card(ccard) => ArchipelCard::try_from((
payment_information.card_holder_name,
payment_information.cardholder.clone(),
ccard,
))?,
PaymentMethodData::CardDetailsForNetworkTransactionId(card_details) => {
ArchipelCard::try_from((
payment_information.card_holder_name,
payment_information.cardholder.clone(),
card_details,
))?
}
PaymentMethodData::CardRedirect(..)
| PaymentMethodData::Wallet(..)
| PaymentMethodData::PayLater(..)
| PaymentMethodData::BankRedirect(..)
| PaymentMethodData::BankDebit(..)
| PaymentMethodData::BankTransfer(..)
| PaymentMethodData::Crypto(..)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(..)
| PaymentMethodData::Upi(..)
| PaymentMethodData::Voucher(..)
| PaymentMethodData::GiftCard(..)
| PaymentMethodData::CardToken(..)
| PaymentMethodData::OpenBanking(..)
| PaymentMethodData::NetworkToken(..)
| PaymentMethodData::MobilePayment(..) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Archipel"),
))?,
};
let three_ds: Option<Archipel3DS> = if item.router_data.is_three_ds() {
let auth_data = item
.router_data
.request
.get_authentication_data()
.change_context(errors::ConnectorError::NotSupported {
message: "Selected 3DS authentication method".to_string(),
connector: "archipel",
})?;
Some(Archipel3DS::from(auth_data))
} else {
None
};
Ok(Self {
order: payment_information.order,
cardholder: payment_information.cardholder,
card: payment_method_data,
three_ds,
credential_indicator: payment_information.credential_indicator,
stored_on_file: payment_information.stored_on_file,
tenant_id,
})
}
}
impl TryFrom<ArchipelRouterData<&PaymentsAuthorizeRouterData>>
for ArchipelWalletAuthorizationRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ArchipelRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let ArchipelRouterData {
amount,
tenant_id,
router_data,
} = item;
let payment_information = ArchipelPaymentInformation::try_from((amount, router_data))?;
let payment_method_data = match &item.router_data.request.payment_method_data {
PaymentMethodData::Wallet(wallet_data) => {
TokenizedCardData::try_from((wallet_data, &item.router_data.payment_method_token))?
}
PaymentMethodData::Card(..)
| PaymentMethodData::CardDetailsForNetworkTransactionId(..)
| PaymentMethodData::CardRedirect(..)
| PaymentMethodData::PayLater(..)
| PaymentMethodData::BankRedirect(..)
| PaymentMethodData::BankDebit(..)
| PaymentMethodData::BankTransfer(..)
| PaymentMethodData::Crypto(..)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(..)
| PaymentMethodData::Upi(..)
| PaymentMethodData::Voucher(..)
| PaymentMethodData::GiftCard(..)
| PaymentMethodData::CardToken(..)
| PaymentMethodData::OpenBanking(..)
| PaymentMethodData::NetworkToken(..)
| PaymentMethodData::MobilePayment(..) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Archipel"),
))?,
};
Ok(Self {
order: payment_information.order,
cardholder: payment_information.cardholder,
card: payment_method_data.card_data.clone(),
wallet: payment_method_data.wallet_information.clone(),
three_ds: None,
credential_indicator: payment_information.credential_indicator,
stored_on_file: payment_information.stored_on_file,
tenant_id,
})
}
}
// Responses for AUTHORIZATION FLOW
impl<F>
TryFrom<
ResponseRouterData<
F,
ArchipelPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
> for RouterData<F, PaymentsAuthorizeData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
ArchipelPaymentsResponse,
PaymentsAuthorizeData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
if let Some(error) = item.response.error {
return Ok(Self {
response: Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),
..item.data
});
};
let capture_method = item
.data
.request
.capture_method
.ok_or_else(|| errors::ConnectorError::CaptureMethodNotSupported)?;
let (archipel_flow, is_incremental_allowed) = match capture_method {
CaptureMethod::Automatic => (ArchipelPaymentFlow::Pay, false),
_ => (
ArchipelPaymentFlow::Authorize,
item.data.request.request_incremental_authorization,
),
};
let connector_metadata: Option<serde_json::Value> =
ArchipelTransactionMetadata::from(&item.response)
.encode_to_value()
.ok();
let status: AttemptStatus =
ArchipelFlowStatus::new(item.response.transaction_result, archipel_flow).into();
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order.id),
charges: None,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
// Save archipel initial transaction uuid for network transaction mit/cit
network_txn_id: item
.data
.request
.is_customer_initiated_mandate_payment()
.then_some(item.response.transaction_id),
connector_response_reference_id: None,
incremental_authorization_allowed: Some(is_incremental_allowed),
}),
..item.data
})
}
}
// PSYNC FLOW
impl<F>
TryFrom<ResponseRouterData<F, ArchipelPaymentsResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
ArchipelPaymentsResponse,
PaymentsSyncData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
if let Some(error) = item.response.error {
return Ok(Self {
response: Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),
..item.data
});
};
let connector_metadata: Option<serde_json::Value> =
ArchipelTransactionMetadata::from(&item.response)
.encode_to_value()
.ok();
let capture_method = item
.data
.request
.capture_method
.ok_or_else(|| errors::ConnectorError::CaptureMethodNotSupported)?;
let archipel_flow: ArchipelPaymentFlow = (item.data.status, capture_method).try_into()?;
let status: AttemptStatus =
ArchipelFlowStatus::new(item.response.transaction_result, archipel_flow).into();
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order.id),
charges: None,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
}),
..item.data
})
}
}
/* CAPTURE FLOW */
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct ArchipelCaptureRequest {
order: ArchipelCaptureOrderRequest,
}
#[derive(Debug, Serialize, Eq, PartialEq)]
pub struct ArchipelCaptureOrderRequest {
amount: MinorUnit,
}
impl From<ArchipelRouterData<&PaymentsCaptureRouterData>> for ArchipelCaptureRequest {
fn from(item: ArchipelRouterData<&PaymentsCaptureRouterData>) -> Self {
Self {
order: ArchipelCaptureOrderRequest {
amount: item.amount,
},
}
}
}
impl<F>
TryFrom<
ResponseRouterData<F, ArchipelPaymentsResponse, PaymentsCaptureData, PaymentsResponseData>,
> for RouterData<F, PaymentsCaptureData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
ArchipelPaymentsResponse,
PaymentsCaptureData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
if let Some(error) = item.response.error {
return Ok(Self {
response: Err(ArchipelErrorMessageWithHttpCode::new(error, item.http_code).into()),
..item.data
});
};
let connector_metadata: Option<serde_json::Value> =
ArchipelTransactionMetadata::from(&item.response)
.encode_to_value()
.ok();
let status: AttemptStatus = ArchipelFlowStatus::new(
item.response.transaction_result,
ArchipelPaymentFlow::Capture,
)
.into();
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(item.response.order.id),
charges: None,
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata,
network_txn_id: None,
connector_response_reference_id: None,
incremental_authorization_allowed: None,
}),
..item.data
})
}
}
// Setup Mandate FLow
impl TryFrom<ArchipelRouterData<&SetupMandateRouterData>> for ArchipelCardAuthorizationRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: ArchipelRouterData<&SetupMandateRouterData>) -> Result<Self, Self::Error> {
let order = ArchipelOrderRequest {
amount: item.amount,
currency: item.router_data.request.currency.to_string(),
certainty: ArchipelPaymentCertainty::Final,
initiator: ArchipelPaymentInitiator::Customer,
};
let cardholder = Some(ArchipelCardHolder {
billing_address: item
.router_data
.get_billing_address()
.ok()
.and_then(|address| address.to_archipel_billing_address()),
});
// NOTE: Archipel does not accept `card.card_holder_name` field without `cardholder` field.
// So if `card_holder` is None, `card.card_holder_name` must also be None.
// However, the reverse is allowed — the `cardholder` field can exist without `card.card_holder_name`.
let card_holder_name = cardholder.as_ref().and_then(|_| {
item.router_data
.get_billing()
.ok()
.and_then(|billing| billing.get_optional_full_name())
});
let stored_on_file = true;
let credential_indicator = Some(ArchipelCredentialIndicator {
status: ArchipelCredentialIndicatorStatus::Initial,
recurring: Some(false),
transaction_id: None,
});
|
crates/hyperswitch_connectors/src/connectors/archipel/transformers.rs#chunk0
|
hyperswitch_connectors
|
chunk
| null | null | null | 8,189
| null | null | null | null | null | null | null |
// Function: lower_program
// File: crates/euclid/src/frontend/dir/lowering.rs
// Module: euclid
pub fn lower_program<O>(
dir_program: dir::DirProgram<O>,
) -> Result<vir::ValuedProgram<O>, AnalysisError>
|
crates/euclid/src/frontend/dir/lowering.rs
|
euclid
|
function_signature
| null | null | null | 56
|
lower_program
| null | null | null | null | null | null |
// Implementation: impl Relay
// File: crates/router/src/routes/app.rs
// Module: router
// Methods: 1 total (1 public)
impl Relay
|
crates/router/src/routes/app.rs
|
router
|
impl_block
| null | null | null | 33
| null |
Relay
| null | 1
| 1
| null | null |
// Implementation: impl fred::types::FromRedis for for HsetnxReply
// File: crates/redis_interface/src/types.rs
// Module: redis_interface
// Methods: 1 total (0 public)
impl fred::types::FromRedis for for HsetnxReply
|
crates/redis_interface/src/types.rs
|
redis_interface
|
impl_block
| null | null | null | 57
| null |
HsetnxReply
|
fred::types::FromRedis for
| 1
| 0
| null | null |
// Struct: RefundResponse
// File: crates/hyperswitch_connectors/src/connectors/wellsfargopayout/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RefundResponse
|
crates/hyperswitch_connectors/src/connectors/wellsfargopayout/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RefundResponse
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Struct: MultipleCaptureRequestData
// File: crates/hyperswitch_domain_models/src/router_request_types.rs
// Module: hyperswitch_domain_models
// Implementations: 0
pub struct MultipleCaptureRequestData
|
crates/hyperswitch_domain_models/src/router_request_types.rs
|
hyperswitch_domain_models
|
struct_definition
|
MultipleCaptureRequestData
| 0
|
[] | 45
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentVoid for for Aci
// File: crates/hyperswitch_connectors/src/connectors/aci.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentVoid for for Aci
|
crates/hyperswitch_connectors/src/connectors/aci.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 57
| null |
Aci
|
api::PaymentVoid for
| 0
| 0
| null | null |
// Struct: RsyncApplicationInformation
// File: crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RsyncApplicationInformation
|
crates/hyperswitch_connectors/src/connectors/barclaycard/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RsyncApplicationInformation
| 0
|
[] | 51
| null | null | null | null | null | null | null |
// Function: new
// File: crates/common_utils/src/types/user/theme.rs
// Module: common_utils
// Documentation: Constructor for ThemeLineage
pub fn new(
entity_type: EntityType,
tenant_id: id_type::TenantId,
org_id: id_type::OrganizationId,
merchant_id: id_type::MerchantId,
profile_id: id_type::ProfileId,
) -> Self
|
crates/common_utils/src/types/user/theme.rs
|
common_utils
|
function_signature
| null | null | null | 86
|
new
| null | null | null | null | null | null |
// Struct: WellsfargoAuthenticationErrorResponse
// File: crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct WellsfargoAuthenticationErrorResponse
|
crates/hyperswitch_connectors/src/connectors/wellsfargo/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
WellsfargoAuthenticationErrorResponse
| 0
|
[] | 53
| null | null | null | null | null | null | null |
// Implementation: impl super::behaviour::Conversion for for MerchantKeyStore
// File: crates/hyperswitch_domain_models/src/merchant_key_store.rs
// Module: hyperswitch_domain_models
// Methods: 3 total (0 public)
impl super::behaviour::Conversion for for MerchantKeyStore
|
crates/hyperswitch_domain_models/src/merchant_key_store.rs
|
hyperswitch_domain_models
|
impl_block
| null | null | null | 63
| null |
MerchantKeyStore
|
super::behaviour::Conversion for
| 3
| 0
| null | null |
// File: crates/router/src/routes/metrics/bg_metrics_collector.rs
// Module: router
// Public functions: 1
use storage_impl::redis::cache;
const DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS: u16 = 15;
pub fn spawn_metrics_collector(metrics_collection_interval_in_secs: Option<u16>) {
let metrics_collection_interval = metrics_collection_interval_in_secs
.unwrap_or(DEFAULT_BG_METRICS_COLLECTION_INTERVAL_IN_SECS);
let cache_instances = [
&cache::CONFIG_CACHE,
&cache::ACCOUNTS_CACHE,
&cache::ROUTING_CACHE,
&cache::CGRAPH_CACHE,
&cache::PM_FILTERS_CGRAPH_CACHE,
&cache::DECISION_MANAGER_CACHE,
&cache::SURCHARGE_CACHE,
&cache::SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE,
&cache::CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE,
&cache::ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE,
];
tokio::spawn(async move {
loop {
for instance in cache_instances {
instance.record_entry_count_metric().await
}
tokio::time::sleep(std::time::Duration::from_secs(
metrics_collection_interval.into(),
))
.await
}
});
}
|
crates/router/src/routes/metrics/bg_metrics_collector.rs
|
router
|
full_file
| null | null | null | 267
| null | null | null | null | null | null | null |
// Function: get_merchant_reference_id
// File: crates/api_models/src/admin.rs
// Module: api_models
pub fn get_merchant_reference_id(&self) -> id_type::MerchantId
|
crates/api_models/src/admin.rs
|
api_models
|
function_signature
| null | null | null | 41
|
get_merchant_reference_id
| null | null | null | null | null | null |
// Struct: RefundPaymentData
// File: crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct RefundPaymentData
|
crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
RefundPaymentData
| 0
|
[] | 49
| null | null | null | null | null | null | null |
// Function: get_sso_id_from_redis
// File: crates/router/src/utils/user.rs
// Module: router
pub fn get_sso_id_from_redis(
state: &SessionState,
oidc_state: Secret<String>,
) -> UserResult<String>
|
crates/router/src/utils/user.rs
|
router
|
function_signature
| null | null | null | 55
|
get_sso_id_from_redis
| null | null | null | null | null | null |
// Implementation: impl api::RefundSync for for Authipay
// File: crates/hyperswitch_connectors/src/connectors/authipay.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::RefundSync for for Authipay
|
crates/hyperswitch_connectors/src/connectors/authipay.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 59
| null |
Authipay
|
api::RefundSync for
| 0
| 0
| null | null |
// File: crates/diesel_models/src/refund.rs
// Module: diesel_models
// Public functions: 8
// Public structs: 8
use common_utils::{
id_type, pii,
types::{ChargeRefunds, ConnectorTransactionId, ConnectorTransactionIdTrait, MinorUnit},
};
use diesel::{AsChangeset, Identifiable, Insertable, Queryable, Selectable};
use serde::{Deserialize, Serialize};
use time::PrimitiveDateTime;
use crate::enums as storage_enums;
#[cfg(feature = "v1")]
use crate::schema::refund;
#[cfg(feature = "v2")]
use crate::{schema_v2::refund, RequiredFromNullable};
#[cfg(feature = "v1")]
#[derive(
Clone,
Debug,
Eq,
Identifiable,
Queryable,
Selectable,
PartialEq,
serde::Serialize,
serde::Deserialize,
)]
#[diesel(table_name = refund, primary_key(refund_id), check_for_backend(diesel::pg::Pg))]
pub struct Refund {
pub internal_reference_id: String,
pub refund_id: String, //merchant_reference id
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
pub connector_transaction_id: ConnectorTransactionId,
pub connector: String,
pub connector_refund_id: Option<ConnectorTransactionId>,
pub external_reference_id: Option<String>,
pub refund_type: storage_enums::RefundType,
pub total_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub refund_amount: MinorUnit,
pub refund_status: storage_enums::RefundStatus,
pub sent_to_gateway: bool,
pub refund_error_message: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub refund_arn: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub description: Option<String>,
pub attempt_id: String,
pub refund_reason: Option<String>,
pub refund_error_code: Option<String>,
pub profile_id: Option<id_type::ProfileId>,
pub updated_by: String,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub charges: Option<ChargeRefunds>,
pub organization_id: id_type::OrganizationId,
/// INFO: This field is deprecated and replaced by processor_refund_data
pub connector_refund_data: Option<String>,
/// INFO: This field is deprecated and replaced by processor_transaction_data
pub connector_transaction_data: Option<String>,
pub split_refunds: Option<common_types::refunds::SplitRefund>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub processor_refund_data: Option<String>,
pub processor_transaction_data: Option<String>,
pub issuer_error_code: Option<String>,
pub issuer_error_message: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(
Clone,
Debug,
Eq,
Identifiable,
Queryable,
Selectable,
PartialEq,
serde::Serialize,
serde::Deserialize,
)]
#[diesel(table_name = refund, primary_key(id), check_for_backend(diesel::pg::Pg))]
pub struct Refund {
pub payment_id: id_type::GlobalPaymentId,
pub merchant_id: id_type::MerchantId,
pub connector_transaction_id: ConnectorTransactionId,
pub connector: String,
pub connector_refund_id: Option<ConnectorTransactionId>,
pub external_reference_id: Option<String>,
pub refund_type: storage_enums::RefundType,
pub total_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub refund_amount: MinorUnit,
pub refund_status: storage_enums::RefundStatus,
pub sent_to_gateway: bool,
pub refund_error_message: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub refund_arn: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub description: Option<String>,
pub attempt_id: id_type::GlobalAttemptId,
pub refund_reason: Option<String>,
pub refund_error_code: Option<String>,
pub profile_id: Option<id_type::ProfileId>,
pub updated_by: String,
pub charges: Option<ChargeRefunds>,
pub organization_id: id_type::OrganizationId,
pub split_refunds: Option<common_types::refunds::SplitRefund>,
pub unified_code: Option<String>,
pub unified_message: Option<String>,
pub processor_refund_data: Option<String>,
pub processor_transaction_data: Option<String>,
pub id: id_type::GlobalRefundId,
#[diesel(deserialize_as = RequiredFromNullable<id_type::RefundReferenceId>)]
pub merchant_reference_id: id_type::RefundReferenceId,
pub connector_id: Option<id_type::MerchantConnectorAccountId>,
}
#[cfg(feature = "v1")]
#[derive(
Clone,
Debug,
Eq,
PartialEq,
Insertable,
router_derive::DebugAsDisplay,
serde::Serialize,
serde::Deserialize,
router_derive::Setter,
)]
#[diesel(table_name = refund)]
pub struct RefundNew {
pub refund_id: String,
pub payment_id: id_type::PaymentId,
pub merchant_id: id_type::MerchantId,
pub internal_reference_id: String,
pub external_reference_id: Option<String>,
pub connector_transaction_id: ConnectorTransactionId,
pub connector: String,
pub connector_refund_id: Option<ConnectorTransactionId>,
pub refund_type: storage_enums::RefundType,
pub total_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub refund_amount: MinorUnit,
pub refund_status: storage_enums::RefundStatus,
pub sent_to_gateway: bool,
pub metadata: Option<pii::SecretSerdeValue>,
pub refund_arn: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub description: Option<String>,
pub attempt_id: String,
pub refund_reason: Option<String>,
pub profile_id: Option<id_type::ProfileId>,
pub updated_by: String,
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
pub charges: Option<ChargeRefunds>,
pub organization_id: id_type::OrganizationId,
pub split_refunds: Option<common_types::refunds::SplitRefund>,
pub processor_refund_data: Option<String>,
pub processor_transaction_data: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(
Clone,
Debug,
Eq,
PartialEq,
Insertable,
router_derive::DebugAsDisplay,
serde::Serialize,
serde::Deserialize,
router_derive::Setter,
)]
#[diesel(table_name = refund)]
pub struct RefundNew {
pub merchant_reference_id: id_type::RefundReferenceId,
pub payment_id: id_type::GlobalPaymentId,
pub merchant_id: id_type::MerchantId,
pub id: id_type::GlobalRefundId,
pub external_reference_id: Option<String>,
pub connector_transaction_id: ConnectorTransactionId,
pub connector: String,
pub connector_refund_id: Option<ConnectorTransactionId>,
pub refund_type: storage_enums::RefundType,
pub total_amount: MinorUnit,
pub currency: storage_enums::Currency,
pub refund_amount: MinorUnit,
pub refund_status: storage_enums::RefundStatus,
pub sent_to_gateway: bool,
pub metadata: Option<pii::SecretSerdeValue>,
pub refund_arn: Option<String>,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub created_at: PrimitiveDateTime,
#[serde(with = "common_utils::custom_serde::iso8601")]
pub modified_at: PrimitiveDateTime,
pub description: Option<String>,
pub attempt_id: id_type::GlobalAttemptId,
pub refund_reason: Option<String>,
pub profile_id: Option<id_type::ProfileId>,
pub updated_by: String,
pub connector_id: Option<id_type::MerchantConnectorAccountId>,
pub charges: Option<ChargeRefunds>,
pub organization_id: id_type::OrganizationId,
pub split_refunds: Option<common_types::refunds::SplitRefund>,
pub processor_refund_data: Option<String>,
pub processor_transaction_data: Option<String>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum RefundUpdate {
Update {
connector_refund_id: ConnectorTransactionId,
refund_status: storage_enums::RefundStatus,
sent_to_gateway: bool,
refund_error_message: Option<String>,
refund_arn: String,
updated_by: String,
processor_refund_data: Option<String>,
},
MetadataAndReasonUpdate {
metadata: Option<pii::SecretSerdeValue>,
reason: Option<String>,
updated_by: String,
},
StatusUpdate {
connector_refund_id: Option<ConnectorTransactionId>,
sent_to_gateway: bool,
refund_status: storage_enums::RefundStatus,
updated_by: String,
processor_refund_data: Option<String>,
},
ErrorUpdate {
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
connector_refund_id: Option<ConnectorTransactionId>,
processor_refund_data: Option<String>,
unified_code: Option<String>,
unified_message: Option<String>,
issuer_error_code: Option<String>,
issuer_error_message: Option<String>,
},
ManualUpdate {
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
},
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
pub enum RefundUpdate {
Update {
connector_refund_id: ConnectorTransactionId,
refund_status: storage_enums::RefundStatus,
sent_to_gateway: bool,
refund_error_message: Option<String>,
refund_arn: String,
updated_by: String,
processor_refund_data: Option<String>,
},
MetadataAndReasonUpdate {
metadata: Option<pii::SecretSerdeValue>,
reason: Option<String>,
updated_by: String,
},
StatusUpdate {
connector_refund_id: Option<ConnectorTransactionId>,
sent_to_gateway: bool,
refund_status: storage_enums::RefundStatus,
updated_by: String,
processor_refund_data: Option<String>,
},
ErrorUpdate {
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
connector_refund_id: Option<ConnectorTransactionId>,
processor_refund_data: Option<String>,
unified_code: Option<String>,
unified_message: Option<String>,
},
ManualUpdate {
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
},
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = refund)]
pub struct RefundUpdateInternal {
connector_refund_id: Option<ConnectorTransactionId>,
refund_status: Option<storage_enums::RefundStatus>,
sent_to_gateway: Option<bool>,
refund_error_message: Option<String>,
refund_arn: Option<String>,
metadata: Option<pii::SecretSerdeValue>,
refund_reason: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
modified_at: PrimitiveDateTime,
processor_refund_data: Option<String>,
unified_code: Option<String>,
unified_message: Option<String>,
issuer_error_code: Option<String>,
issuer_error_message: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, AsChangeset, router_derive::DebugAsDisplay)]
#[diesel(table_name = refund)]
pub struct RefundUpdateInternal {
connector_refund_id: Option<ConnectorTransactionId>,
refund_status: Option<storage_enums::RefundStatus>,
sent_to_gateway: Option<bool>,
refund_error_message: Option<String>,
refund_arn: Option<String>,
metadata: Option<pii::SecretSerdeValue>,
refund_reason: Option<String>,
refund_error_code: Option<String>,
updated_by: String,
modified_at: PrimitiveDateTime,
processor_refund_data: Option<String>,
unified_code: Option<String>,
unified_message: Option<String>,
}
#[cfg(feature = "v1")]
impl RefundUpdateInternal {
pub fn create_refund(self, source: Refund) -> Refund {
Refund {
connector_refund_id: self.connector_refund_id,
refund_status: self.refund_status.unwrap_or_default(),
sent_to_gateway: self.sent_to_gateway.unwrap_or_default(),
refund_error_message: self.refund_error_message,
refund_arn: self.refund_arn,
metadata: self.metadata,
refund_reason: self.refund_reason,
refund_error_code: self.refund_error_code,
updated_by: self.updated_by,
modified_at: self.modified_at,
processor_refund_data: self.processor_refund_data,
unified_code: self.unified_code,
unified_message: self.unified_message,
..source
}
}
}
#[cfg(feature = "v2")]
impl RefundUpdateInternal {
pub fn create_refund(self, source: Refund) -> Refund {
Refund {
connector_refund_id: self.connector_refund_id,
refund_status: self.refund_status.unwrap_or_default(),
sent_to_gateway: self.sent_to_gateway.unwrap_or_default(),
refund_error_message: self.refund_error_message,
refund_arn: self.refund_arn,
metadata: self.metadata,
refund_reason: self.refund_reason,
refund_error_code: self.refund_error_code,
updated_by: self.updated_by,
modified_at: self.modified_at,
processor_refund_data: self.processor_refund_data,
unified_code: self.unified_code,
unified_message: self.unified_message,
..source
}
}
}
#[cfg(feature = "v1")]
impl From<RefundUpdate> for RefundUpdateInternal {
fn from(refund_update: RefundUpdate) -> Self {
match refund_update {
RefundUpdate::Update {
connector_refund_id,
refund_status,
sent_to_gateway,
refund_error_message,
refund_arn,
updated_by,
processor_refund_data,
} => Self {
connector_refund_id: Some(connector_refund_id),
refund_status: Some(refund_status),
sent_to_gateway: Some(sent_to_gateway),
refund_error_message,
refund_arn: Some(refund_arn),
updated_by,
processor_refund_data,
metadata: None,
refund_reason: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
},
RefundUpdate::MetadataAndReasonUpdate {
metadata,
reason,
updated_by,
} => Self {
metadata,
refund_reason: reason,
updated_by,
connector_refund_id: None,
refund_status: None,
sent_to_gateway: None,
refund_error_message: None,
refund_arn: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
},
RefundUpdate::StatusUpdate {
connector_refund_id,
sent_to_gateway,
refund_status,
updated_by,
processor_refund_data,
} => Self {
connector_refund_id,
sent_to_gateway: Some(sent_to_gateway),
refund_status: Some(refund_status),
updated_by,
processor_refund_data,
refund_error_message: None,
refund_arn: None,
metadata: None,
refund_reason: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
},
RefundUpdate::ErrorUpdate {
refund_status,
refund_error_message,
refund_error_code,
unified_code,
unified_message,
updated_by,
connector_refund_id,
processor_refund_data,
issuer_error_code,
issuer_error_message,
} => Self {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
connector_refund_id,
processor_refund_data,
sent_to_gateway: None,
refund_arn: None,
metadata: None,
refund_reason: None,
modified_at: common_utils::date_time::now(),
unified_code,
unified_message,
issuer_error_code,
issuer_error_message,
},
RefundUpdate::ManualUpdate {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
} => Self {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
connector_refund_id: None,
sent_to_gateway: None,
refund_arn: None,
metadata: None,
refund_reason: None,
modified_at: common_utils::date_time::now(),
processor_refund_data: None,
unified_code: None,
unified_message: None,
issuer_error_code: None,
issuer_error_message: None,
},
}
}
}
#[cfg(feature = "v2")]
impl From<RefundUpdate> for RefundUpdateInternal {
fn from(refund_update: RefundUpdate) -> Self {
match refund_update {
RefundUpdate::Update {
connector_refund_id,
refund_status,
sent_to_gateway,
refund_error_message,
refund_arn,
updated_by,
processor_refund_data,
} => Self {
connector_refund_id: Some(connector_refund_id),
refund_status: Some(refund_status),
sent_to_gateway: Some(sent_to_gateway),
refund_error_message,
refund_arn: Some(refund_arn),
updated_by,
processor_refund_data,
metadata: None,
refund_reason: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
unified_code: None,
unified_message: None,
},
RefundUpdate::MetadataAndReasonUpdate {
metadata,
reason,
updated_by,
} => Self {
metadata,
refund_reason: reason,
updated_by,
connector_refund_id: None,
refund_status: None,
sent_to_gateway: None,
refund_error_message: None,
refund_arn: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
processor_refund_data: None,
unified_code: None,
unified_message: None,
},
RefundUpdate::StatusUpdate {
connector_refund_id,
sent_to_gateway,
refund_status,
updated_by,
processor_refund_data,
} => Self {
connector_refund_id,
sent_to_gateway: Some(sent_to_gateway),
refund_status: Some(refund_status),
updated_by,
processor_refund_data,
refund_error_message: None,
refund_arn: None,
metadata: None,
refund_reason: None,
refund_error_code: None,
modified_at: common_utils::date_time::now(),
unified_code: None,
unified_message: None,
},
RefundUpdate::ErrorUpdate {
refund_status,
refund_error_message,
refund_error_code,
unified_code,
unified_message,
updated_by,
connector_refund_id,
processor_refund_data,
} => Self {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
connector_refund_id,
processor_refund_data,
sent_to_gateway: None,
refund_arn: None,
metadata: None,
refund_reason: None,
modified_at: common_utils::date_time::now(),
unified_code,
unified_message,
},
RefundUpdate::ManualUpdate {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
} => Self {
refund_status,
refund_error_message,
refund_error_code,
updated_by,
connector_refund_id: None,
sent_to_gateway: None,
refund_arn: None,
metadata: None,
refund_reason: None,
modified_at: common_utils::date_time::now(),
processor_refund_data: None,
unified_code: None,
unified_message: None,
},
}
}
}
#[cfg(feature = "v1")]
impl RefundUpdate {
pub fn apply_changeset(self, source: Refund) -> Refund {
let RefundUpdateInternal {
connector_refund_id,
refund_status,
sent_to_gateway,
refund_error_message,
refund_arn,
metadata,
refund_reason,
refund_error_code,
updated_by,
modified_at: _,
processor_refund_data,
unified_code,
unified_message,
issuer_error_code,
issuer_error_message,
} = self.into();
Refund {
connector_refund_id: connector_refund_id.or(source.connector_refund_id),
refund_status: refund_status.unwrap_or(source.refund_status),
sent_to_gateway: sent_to_gateway.unwrap_or(source.sent_to_gateway),
refund_error_message: refund_error_message.or(source.refund_error_message),
refund_error_code: refund_error_code.or(source.refund_error_code),
refund_arn: refund_arn.or(source.refund_arn),
metadata: metadata.or(source.metadata),
refund_reason: refund_reason.or(source.refund_reason),
updated_by,
modified_at: common_utils::date_time::now(),
processor_refund_data: processor_refund_data.or(source.processor_refund_data),
unified_code: unified_code.or(source.unified_code),
unified_message: unified_message.or(source.unified_message),
issuer_error_code: issuer_error_code.or(source.issuer_error_code),
issuer_error_message: issuer_error_message.or(source.issuer_error_message),
..source
}
}
}
#[cfg(feature = "v2")]
impl RefundUpdate {
pub fn apply_changeset(self, source: Refund) -> Refund {
let RefundUpdateInternal {
connector_refund_id,
refund_status,
sent_to_gateway,
refund_error_message,
refund_arn,
metadata,
refund_reason,
refund_error_code,
updated_by,
modified_at: _,
processor_refund_data,
unified_code,
unified_message,
} = self.into();
Refund {
connector_refund_id: connector_refund_id.or(source.connector_refund_id),
refund_status: refund_status.unwrap_or(source.refund_status),
sent_to_gateway: sent_to_gateway.unwrap_or(source.sent_to_gateway),
refund_error_message: refund_error_message.or(source.refund_error_message),
refund_error_code: refund_error_code.or(source.refund_error_code),
refund_arn: refund_arn.or(source.refund_arn),
metadata: metadata.or(source.metadata),
refund_reason: refund_reason.or(source.refund_reason),
updated_by,
modified_at: common_utils::date_time::now(),
processor_refund_data: processor_refund_data.or(source.processor_refund_data),
unified_code: unified_code.or(source.unified_code),
unified_message: unified_message.or(source.unified_message),
..source
}
}
pub fn build_error_update_for_unified_error_and_message(
unified_error_object: (String, String),
refund_error_message: Option<String>,
refund_error_code: Option<String>,
storage_scheme: &storage_enums::MerchantStorageScheme,
) -> Self {
let (unified_code, unified_message) = unified_error_object;
Self::ErrorUpdate {
refund_status: Some(storage_enums::RefundStatus::Failure),
refund_error_message,
refund_error_code,
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: Some(unified_code),
unified_message: Some(unified_message),
}
}
pub fn build_error_update_for_integrity_check_failure(
integrity_check_failed_fields: String,
connector_refund_id: Option<ConnectorTransactionId>,
storage_scheme: &storage_enums::MerchantStorageScheme,
) -> Self {
Self::ErrorUpdate {
refund_status: Some(storage_enums::RefundStatus::ManualReview),
refund_error_message: Some(format!(
"Integrity Check Failed! as data mismatched for fields {integrity_check_failed_fields}"
)),
refund_error_code: Some("IE".to_string()),
updated_by: storage_scheme.to_string(),
connector_refund_id: connector_refund_id.clone(),
processor_refund_data: connector_refund_id.and_then(|x| x.extract_hashed_data()),
unified_code: None,
unified_message: None,
}
}
pub fn build_refund_update(
connector_refund_id: ConnectorTransactionId,
refund_status: storage_enums::RefundStatus,
storage_scheme: &storage_enums::MerchantStorageScheme,
) -> Self {
Self::Update {
connector_refund_id: connector_refund_id.clone(),
refund_status,
sent_to_gateway: true,
refund_error_message: None,
refund_arn: "".to_string(),
updated_by: storage_scheme.to_string(),
processor_refund_data: connector_refund_id.extract_hashed_data(),
}
}
pub fn build_error_update_for_refund_failure(
refund_status: Option<storage_enums::RefundStatus>,
refund_error_message: Option<String>,
refund_error_code: Option<String>,
storage_scheme: &storage_enums::MerchantStorageScheme,
) -> Self {
Self::ErrorUpdate {
refund_status,
refund_error_message,
refund_error_code,
updated_by: storage_scheme.to_string(),
connector_refund_id: None,
processor_refund_data: None,
unified_code: None,
unified_message: None,
}
}
}
#[cfg(feature = "v1")]
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct RefundCoreWorkflow {
pub refund_internal_reference_id: String,
pub connector_transaction_id: ConnectorTransactionId,
pub merchant_id: id_type::MerchantId,
pub payment_id: id_type::PaymentId,
pub processor_transaction_data: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct RefundCoreWorkflow {
pub refund_id: id_type::GlobalRefundId,
pub connector_transaction_id: ConnectorTransactionId,
pub merchant_id: id_type::MerchantId,
pub payment_id: id_type::GlobalPaymentId,
pub processor_transaction_data: Option<String>,
}
#[cfg(feature = "v1")]
impl common_utils::events::ApiEventMetric for Refund {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Refund {
payment_id: Some(self.payment_id.clone()),
refund_id: self.refund_id.clone(),
})
}
}
#[cfg(feature = "v2")]
impl common_utils::events::ApiEventMetric for Refund {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Refund {
payment_id: Some(self.payment_id.clone()),
refund_id: self.id.clone(),
})
}
}
impl ConnectorTransactionIdTrait for Refund {
fn get_optional_connector_refund_id(&self) -> Option<&String> {
match self
.connector_refund_id
.as_ref()
.map(|refund_id| refund_id.get_txn_id(self.processor_refund_data.as_ref()))
.transpose()
{
Ok(refund_id) => refund_id,
// In case hashed data is missing from DB, use the hashed ID as connector transaction ID
Err(_) => self
.connector_refund_id
.as_ref()
.map(|txn_id| txn_id.get_id()),
}
}
fn get_connector_transaction_id(&self) -> &String {
match self
.connector_transaction_id
.get_txn_id(self.processor_transaction_data.as_ref())
{
Ok(txn_id) => txn_id,
// In case hashed data is missing from DB, use the hashed ID as connector transaction ID
Err(_) => self.connector_transaction_id.get_id(),
}
}
}
mod tests {
#[test]
fn test_backwards_compatibility() {
let serialized_refund = r#"{
"internal_reference_id": "internal_ref_123",
"refund_id": "refund_456",
"payment_id": "payment_789",
"merchant_id": "merchant_123",
"connector_transaction_id": "connector_txn_789",
"connector": "stripe",
"connector_refund_id": null,
"external_reference_id": null,
"refund_type": "instant_refund",
"total_amount": 10000,
"currency": "USD",
"refund_amount": 9500,
"refund_status": "Success",
"sent_to_gateway": true,
"refund_error_message": null,
"metadata": null,
"refund_arn": null,
"created_at": "2024-02-26T12:00:00Z",
"updated_at": "2024-02-26T12:00:00Z",
"description": null,
"attempt_id": "attempt_123",
"refund_reason": null,
"refund_error_code": null,
"profile_id": null,
"updated_by": "admin",
"merchant_connector_id": null,
"charges": null,
"connector_transaction_data": null
"unified_code": null,
"unified_message": null,
"processor_transaction_data": null,
}"#;
let deserialized = serde_json::from_str::<super::Refund>(serialized_refund);
assert!(deserialized.is_ok());
}
}
|
crates/diesel_models/src/refund.rs
|
diesel_models
|
full_file
| null | null | null | 6,732
| null | null | null | null | null | null | null |
// Implementation: impl api::PaymentsCompleteAuthorize for for Bambora
// File: crates/hyperswitch_connectors/src/connectors/bambora.rs
// Module: hyperswitch_connectors
// Methods: 0 total (0 public)
impl api::PaymentsCompleteAuthorize for for Bambora
|
crates/hyperswitch_connectors/src/connectors/bambora.rs
|
hyperswitch_connectors
|
impl_block
| null | null | null | 62
| null |
Bambora
|
api::PaymentsCompleteAuthorize for
| 0
| 0
| null | null |
// Function: accept_dispute
// File: crates/router/src/core/disputes.rs
// Module: router
pub fn accept_dispute(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: Option<common_utils::id_type::ProfileId>,
req: disputes::DisputeId,
) -> RouterResponse<dispute_models::DisputeResponse>
|
crates/router/src/core/disputes.rs
|
router
|
function_signature
| null | null | null | 82
|
accept_dispute
| null | null | null | null | null | null |
// Function: routing_retrieve_default_config
// File: crates/router/src/routes/routing.rs
// Module: router
pub fn routing_retrieve_default_config(
state: web::Data<AppState>,
req: HttpRequest,
transaction_type: &enums::TransactionType,
) -> impl Responder
|
crates/router/src/routes/routing.rs
|
router
|
function_signature
| null | null | null | 62
|
routing_retrieve_default_config
| null | null | null | null | null | null |
// Function: find_by_merchant_id_payment_id_connector_dispute_id
// File: crates/diesel_models/src/query/dispute.rs
// Module: diesel_models
pub fn find_by_merchant_id_payment_id_connector_dispute_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payment_id: &common_utils::id_type::PaymentId,
connector_dispute_id: &str,
) -> StorageResult<Option<Self>>
|
crates/diesel_models/src/query/dispute.rs
|
diesel_models
|
function_signature
| null | null | null | 102
|
find_by_merchant_id_payment_id_connector_dispute_id
| null | null | null | null | null | null |
// Function: construct_payment_router_data_for_sdk_session
// File: crates/router/src/core/payments/transformers.rs
// Module: router
pub fn construct_payment_router_data_for_sdk_session<'a>(
state: &'a SessionState,
payment_data: hyperswitch_domain_models::payments::PaymentIntentData<api::Session>,
connector_id: &str,
merchant_context: &domain::MerchantContext,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
_merchant_recipient_data: Option<types::MerchantRecipientData>,
header_payload: Option<hyperswitch_domain_models::payments::HeaderPayload>,
) -> RouterResult<types::PaymentsSessionRouterData>
|
crates/router/src/core/payments/transformers.rs
|
router
|
function_signature
| null | null | null | 155
|
construct_payment_router_data_for_sdk_session
| null | null | null | null | null | null |
// Implementation: impl BackendOutput
// File: crates/euclid/src/backend.rs
// Module: euclid
// Methods: 1 total (1 public)
impl BackendOutput
|
crates/euclid/src/backend.rs
|
euclid
|
impl_block
| null | null | null | 37
| null |
BackendOutput
| null | 1
| 1
| null | null |
// Struct: ReverseLookupNew
// File: crates/diesel_models/src/reverse_lookup.rs
// Module: diesel_models
// Implementations: 0
pub struct ReverseLookupNew
|
crates/diesel_models/src/reverse_lookup.rs
|
diesel_models
|
struct_definition
|
ReverseLookupNew
| 0
|
[] | 38
| null | null | null | null | null | null | null |
// Struct: GlobalPayMeta
// File: crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs
// Module: hyperswitch_connectors
// Implementations: 0
pub struct GlobalPayMeta
|
crates/hyperswitch_connectors/src/connectors/globalpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
|
GlobalPayMeta
| 0
|
[] | 47
| null | null | null | null | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.