text
string | file_path
string | module
string | type
string | tokens
int64 | language
string | struct_name
string | type_name
string | trait_name
string | impl_type
string | function_name
string | source
string | section
string | keys
list | macro_type
string | url
string | title
string | chunk_index
int64 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo {
MerchantConnectorInfo {
connector_label: connector_label.to_string(),
merchant_connector_id: self.merchant_connector_id.clone(),
}
}
|
crates/api_models/src/admin.rs
|
api_models
|
function_signature
| 51
|
rust
| null | null | null | null |
to_merchant_connector_info
| null | null | null | null | null | null | null |
File: crates/router/src/services/authorization/roles/predefined_roles.rs
use std::{collections::HashMap, sync::LazyLock};
use common_enums::{EntityType, PermissionGroup, RoleScope};
use super::RoleInfo;
use crate::consts;
pub static PREDEFINED_ROLES: LazyLock<HashMap<&'static str, RoleInfo>> = LazyLock::new(|| {
let mut roles = HashMap::new();
// Internal Roles
roles.insert(
common_utils::consts::ROLE_ID_INTERNAL_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::OperationsManage,
PermissionGroup::ConnectorsView,
PermissionGroup::ConnectorsManage,
PermissionGroup::WorkflowsView,
PermissionGroup::WorkflowsManage,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
PermissionGroup::AccountManage,
PermissionGroup::OrganizationManage,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconOpsManage,
PermissionGroup::ReconReportsView,
PermissionGroup::ReconReportsManage,
],
role_id: common_utils::consts::ROLE_ID_INTERNAL_ADMIN.to_string(),
role_name: "internal_admin".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: false,
is_deletable: false,
is_updatable: false,
is_internal: true,
},
);
roles.insert(
common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::ConnectorsView,
PermissionGroup::WorkflowsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconReportsView,
],
role_id: common_utils::consts::ROLE_ID_INTERNAL_VIEW_ONLY_USER.to_string(),
role_name: "internal_view_only".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: false,
is_deletable: false,
is_updatable: false,
is_internal: true,
},
);
roles.insert(
common_utils::consts::ROLE_ID_INTERNAL_DEMO,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::ConnectorsView,
PermissionGroup::WorkflowsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconReportsView,
PermissionGroup::InternalManage,
],
role_id: common_utils::consts::ROLE_ID_INTERNAL_DEMO.to_string(),
role_name: "internal_demo".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: false,
is_deletable: false,
is_updatable: false,
is_internal: true,
},
);
// Tenant Roles
roles.insert(
common_utils::consts::ROLE_ID_TENANT_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::OperationsManage,
PermissionGroup::ConnectorsView,
PermissionGroup::ConnectorsManage,
PermissionGroup::WorkflowsView,
PermissionGroup::WorkflowsManage,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
PermissionGroup::AccountManage,
PermissionGroup::OrganizationManage,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconOpsManage,
PermissionGroup::ReconReportsView,
PermissionGroup::ReconReportsManage,
],
role_id: common_utils::consts::ROLE_ID_TENANT_ADMIN.to_string(),
role_name: "tenant_admin".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Tenant,
is_invitable: false,
is_deletable: false,
is_updatable: false,
is_internal: false,
},
);
// Organization Roles
roles.insert(
common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::OperationsManage,
PermissionGroup::ConnectorsView,
PermissionGroup::ConnectorsManage,
PermissionGroup::WorkflowsView,
PermissionGroup::WorkflowsManage,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
PermissionGroup::AccountManage,
PermissionGroup::OrganizationManage,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconOpsManage,
PermissionGroup::ReconReportsView,
PermissionGroup::ReconReportsManage,
PermissionGroup::ThemeView,
PermissionGroup::ThemeManage,
],
role_id: common_utils::consts::ROLE_ID_ORGANIZATION_ADMIN.to_string(),
role_name: "organization_admin".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Organization,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
// MERCHANT ROLES
roles.insert(
consts::user_role::ROLE_ID_MERCHANT_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::OperationsManage,
PermissionGroup::ConnectorsView,
PermissionGroup::ConnectorsManage,
PermissionGroup::WorkflowsView,
PermissionGroup::WorkflowsManage,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
PermissionGroup::AccountManage,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconOpsManage,
PermissionGroup::ReconReportsView,
PermissionGroup::ReconReportsManage,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_ADMIN.to_string(),
role_name: "merchant_admin".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::ConnectorsView,
PermissionGroup::WorkflowsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconReportsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_VIEW_ONLY.to_string(),
role_name: "merchant_view_only".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_IAM_ADMIN.to_string(),
role_name: "merchant_iam".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_MERCHANT_DEVELOPER,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::ConnectorsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
PermissionGroup::AccountManage,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconReportsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_DEVELOPER.to_string(),
role_name: "merchant_developer".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_MERCHANT_OPERATOR,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::OperationsManage,
PermissionGroup::ConnectorsView,
PermissionGroup::WorkflowsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconOpsManage,
PermissionGroup::ReconReportsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_OPERATOR.to_string(),
role_name: "merchant_operator".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::ReconOpsView,
PermissionGroup::ReconReportsView,
],
role_id: consts::user_role::ROLE_ID_MERCHANT_CUSTOMER_SUPPORT.to_string(),
role_name: "customer_support".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Merchant,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
// Profile Roles
roles.insert(
consts::user_role::ROLE_ID_PROFILE_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::OperationsManage,
PermissionGroup::ConnectorsView,
PermissionGroup::ConnectorsManage,
PermissionGroup::WorkflowsView,
PermissionGroup::WorkflowsManage,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
PermissionGroup::AccountManage,
],
role_id: consts::user_role::ROLE_ID_PROFILE_ADMIN.to_string(),
role_name: "profile_admin".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Profile,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_PROFILE_VIEW_ONLY,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::ConnectorsView,
PermissionGroup::WorkflowsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_PROFILE_VIEW_ONLY.to_string(),
role_name: "profile_view_only".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Profile,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_PROFILE_IAM_ADMIN,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::UsersManage,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_PROFILE_IAM_ADMIN.to_string(),
role_name: "profile_iam".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Profile,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_PROFILE_DEVELOPER,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::ConnectorsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
PermissionGroup::MerchantDetailsManage,
PermissionGroup::AccountManage,
],
role_id: consts::user_role::ROLE_ID_PROFILE_DEVELOPER.to_string(),
role_name: "profile_developer".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Profile,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_PROFILE_OPERATOR,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::OperationsManage,
PermissionGroup::ConnectorsView,
PermissionGroup::WorkflowsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_PROFILE_OPERATOR.to_string(),
role_name: "profile_operator".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Profile,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles.insert(
consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT,
RoleInfo {
groups: vec![
PermissionGroup::OperationsView,
PermissionGroup::AnalyticsView,
PermissionGroup::UsersView,
PermissionGroup::MerchantDetailsView,
PermissionGroup::AccountView,
],
role_id: consts::user_role::ROLE_ID_PROFILE_CUSTOMER_SUPPORT.to_string(),
role_name: "profile_customer_support".to_string(),
scope: RoleScope::Organization,
entity_type: EntityType::Profile,
is_invitable: true,
is_deletable: true,
is_updatable: true,
is_internal: false,
},
);
roles
});
|
crates/router/src/services/authorization/roles/predefined_roles.rs
|
router
|
full_file
| 3,281
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct TokenizeCreditCardData {
payment_method: TokenizePaymentMethodData,
}
|
crates/hyperswitch_connectors/src/connectors/braintree/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 19
|
rust
|
TokenizeCreditCardData
| null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.MandateAmountData
{
"type": "object",
"required": [
"amount",
"currency"
],
"properties": {
"amount": {
"type": "integer",
"format": "int64",
"description": "The maximum amount to be debited for the mandate transaction",
"example": 6540
},
"currency": {
"$ref": "#/components/schemas/Currency"
},
"start_date": {
"type": "string",
"format": "date-time",
"description": "Specifying start date of the mandate",
"example": "2022-09-10T00:00:00Z",
"nullable": true
},
"end_date": {
"type": "string",
"format": "date-time",
"description": "Specifying end date of the mandate",
"example": "2023-09-10T23:59:59Z",
"nullable": true
},
"metadata": {
"type": "object",
"description": "Additional details required by mandate",
"nullable": true
}
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 281
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"MandateAmountData"
] | null | null | null | null |
pub async fn link_routing_config_under_profile(
state: SessionState,
merchant_context: domain::MerchantContext,
profile_id: common_utils::id_type::ProfileId,
algorithm_id: common_utils::id_type::RoutingId,
transaction_type: &enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
metrics::ROUTING_LINK_CONFIG.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let routing_algorithm = RoutingAlgorithmUpdate::fetch_routing_algo(
merchant_context.get_merchant_account().get_id(),
&algorithm_id,
db,
)
.await?;
utils::when(routing_algorithm.0.profile_id != profile_id, || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Profile Id is invalid for the routing config".to_string(),
})
})?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")?;
utils::when(
routing_algorithm.0.algorithm_for != *transaction_type,
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"Cannot use {}'s routing algorithm for {} operation",
routing_algorithm.0.algorithm_for, transaction_type
),
})
},
)?;
utils::when(
business_profile.routing_algorithm_id == Some(algorithm_id.clone())
|| business_profile.payout_routing_algorithm_id == Some(algorithm_id.clone()),
|| {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: "Algorithm is already active".to_string(),
})
},
)?;
admin::ProfileWrapper::new(business_profile)
.update_profile_and_invalidate_routing_config_for_active_algorithm_id_update(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
algorithm_id,
transaction_type,
)
.await?;
metrics::ROUTING_LINK_CONFIG_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(
routing_algorithm.0.foreign_into(),
))
}
|
crates/router/src/core/routing.rs
|
router
|
function_signature
| 487
|
rust
| null | null | null | null |
link_routing_config_under_profile
| null | null | null | null | null | null | null |
pub struct OpennodePaymentsRequest {
amount: MinorUnit,
currency: String,
description: String,
auto_settle: bool,
success_url: String,
callback_url: String,
order_id: String,
}
|
crates/hyperswitch_connectors/src/connectors/opennode/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 50
|
rust
|
OpennodePaymentsRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub struct ForteCancelRequest {
action: String,
authorization_code: String,
}
|
crates/hyperswitch_connectors/src/connectors/forte/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 19
|
rust
|
ForteCancelRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub struct NumberComparison {
pub comparison_type: ComparisonType,
pub number: u64,
}
|
crates/api_models/src/routing.rs
|
api_models
|
struct_definition
| 22
|
rust
|
NumberComparison
| null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.ApplePayRecurringPaymentRequest
{
"type": "object",
"required": [
"payment_description",
"regular_billing",
"management_u_r_l"
],
"properties": {
"payment_description": {
"type": "string",
"description": "A description of the recurring payment that Apple Pay displays to the user in the payment sheet"
},
"regular_billing": {
"$ref": "#/components/schemas/ApplePayRegularBillingRequest"
},
"billing_agreement": {
"type": "string",
"description": "A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment",
"nullable": true
},
"management_u_r_l": {
"type": "string",
"description": "A URL to a web page where the user can update or delete the payment method for the recurring payment",
"example": "https://hyperswitch.io"
}
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 220
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"ApplePayRecurringPaymentRequest"
] | null | null | null | null |
pub struct CheckoutTokenResponse {
token: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 13
|
rust
|
CheckoutTokenResponse
| null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.GiftCardAdditionalData
{
"oneOf": [
{
"type": "object",
"required": [
"givex"
],
"properties": {
"givex": {
"$ref": "#/components/schemas/GivexGiftCardAdditionalData"
}
}
},
{
"type": "object",
"required": [
"pay_safe_card"
],
"properties": {
"pay_safe_card": {
"type": "object"
}
}
},
{
"type": "object",
"required": [
"bhn_card_network"
],
"properties": {
"bhn_card_network": {
"type": "object"
}
}
}
]
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 177
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"GiftCardAdditionalData"
] | null | null | null | null |
File: crates/router/src/db/authentication.rs
use diesel_models::authentication::AuthenticationUpdateInternal;
use error_stack::report;
use router_env::{instrument, tracing};
use super::{MockDb, Store};
use crate::{
connection,
core::errors::{self, CustomResult},
types::storage,
};
#[async_trait::async_trait]
pub trait AuthenticationInterface {
async fn insert_authentication(
&self,
authentication: storage::AuthenticationNew,
) -> CustomResult<storage::Authentication, errors::StorageError>;
async fn find_authentication_by_merchant_id_authentication_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
authentication_id: &common_utils::id_type::AuthenticationId,
) -> CustomResult<storage::Authentication, errors::StorageError>;
async fn find_authentication_by_merchant_id_connector_authentication_id(
&self,
merchant_id: common_utils::id_type::MerchantId,
connector_authentication_id: String,
) -> CustomResult<storage::Authentication, errors::StorageError>;
async fn update_authentication_by_merchant_id_authentication_id(
&self,
previous_state: storage::Authentication,
authentication_update: storage::AuthenticationUpdate,
) -> CustomResult<storage::Authentication, errors::StorageError>;
}
#[async_trait::async_trait]
impl AuthenticationInterface for Store {
#[instrument(skip_all)]
async fn insert_authentication(
&self,
authentication: storage::AuthenticationNew,
) -> CustomResult<storage::Authentication, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
authentication
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_authentication_by_merchant_id_authentication_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
authentication_id: &common_utils::id_type::AuthenticationId,
) -> CustomResult<storage::Authentication, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Authentication::find_by_merchant_id_authentication_id(
&conn,
merchant_id,
authentication_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn find_authentication_by_merchant_id_connector_authentication_id(
&self,
merchant_id: common_utils::id_type::MerchantId,
connector_authentication_id: String,
) -> CustomResult<storage::Authentication, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::Authentication::find_authentication_by_merchant_id_connector_authentication_id(
&conn,
&merchant_id,
&connector_authentication_id,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_authentication_by_merchant_id_authentication_id(
&self,
previous_state: storage::Authentication,
authentication_update: storage::AuthenticationUpdate,
) -> CustomResult<storage::Authentication, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::Authentication::update_by_merchant_id_authentication_id(
&conn,
previous_state.merchant_id,
previous_state.authentication_id,
authentication_update,
)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl AuthenticationInterface for MockDb {
async fn insert_authentication(
&self,
authentication: storage::AuthenticationNew,
) -> CustomResult<storage::Authentication, errors::StorageError> {
let mut authentications = self.authentications.lock().await;
if authentications.iter().any(|authentication_inner| {
authentication_inner.authentication_id == authentication.authentication_id
}) {
Err(errors::StorageError::DuplicateValue {
entity: "authentication_id",
key: Some(
authentication
.authentication_id
.get_string_repr()
.to_string(),
),
})?
}
let authentication = storage::Authentication {
created_at: common_utils::date_time::now(),
modified_at: common_utils::date_time::now(),
authentication_id: authentication.authentication_id,
merchant_id: authentication.merchant_id,
authentication_status: authentication.authentication_status,
authentication_connector: authentication.authentication_connector,
connector_authentication_id: authentication.connector_authentication_id,
authentication_data: None,
payment_method_id: authentication.payment_method_id,
authentication_type: authentication.authentication_type,
authentication_lifecycle_status: authentication.authentication_lifecycle_status,
error_code: authentication.error_code,
error_message: authentication.error_message,
connector_metadata: authentication.connector_metadata,
maximum_supported_version: authentication.maximum_supported_version,
threeds_server_transaction_id: authentication.threeds_server_transaction_id,
cavv: authentication.cavv,
authentication_flow_type: authentication.authentication_flow_type,
message_version: authentication.message_version,
eci: authentication.eci,
trans_status: authentication.trans_status,
acquirer_bin: authentication.acquirer_bin,
acquirer_merchant_id: authentication.acquirer_merchant_id,
three_ds_method_data: authentication.three_ds_method_data,
three_ds_method_url: authentication.three_ds_method_url,
acs_url: authentication.acs_url,
challenge_request: authentication.challenge_request,
acs_reference_number: authentication.acs_reference_number,
acs_trans_id: authentication.acs_trans_id,
acs_signed_content: authentication.acs_signed_content,
profile_id: authentication.profile_id,
payment_id: authentication.payment_id,
merchant_connector_id: authentication.merchant_connector_id,
ds_trans_id: authentication.ds_trans_id,
directory_server_id: authentication.directory_server_id,
acquirer_country_code: authentication.acquirer_country_code,
service_details: authentication.service_details,
organization_id: authentication.organization_id,
authentication_client_secret: authentication.authentication_client_secret,
force_3ds_challenge: authentication.force_3ds_challenge,
psd2_sca_exemption_type: authentication.psd2_sca_exemption_type,
return_url: authentication.return_url,
amount: authentication.amount,
currency: authentication.currency,
billing_address: authentication.billing_address,
shipping_address: authentication.shipping_address,
browser_info: authentication.browser_info,
email: authentication.email,
profile_acquirer_id: authentication.profile_acquirer_id,
challenge_code: authentication.challenge_code,
challenge_cancel: authentication.challenge_cancel,
challenge_code_reason: authentication.challenge_code_reason,
message_extension: authentication.message_extension,
};
authentications.push(authentication.clone());
Ok(authentication)
}
async fn find_authentication_by_merchant_id_authentication_id(
&self,
merchant_id: &common_utils::id_type::MerchantId,
authentication_id: &common_utils::id_type::AuthenticationId,
) -> CustomResult<storage::Authentication, errors::StorageError> {
let authentications = self.authentications.lock().await;
authentications
.iter()
.find(|a| a.merchant_id == *merchant_id && a.authentication_id == *authentication_id)
.ok_or(
errors::StorageError::ValueNotFound(format!(
"cannot find authentication for authentication_id = {authentication_id:?} and merchant_id = {merchant_id:?}"
)).into(),
).cloned()
}
async fn find_authentication_by_merchant_id_connector_authentication_id(
&self,
_merchant_id: common_utils::id_type::MerchantId,
_connector_authentication_id: String,
) -> CustomResult<storage::Authentication, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
async fn update_authentication_by_merchant_id_authentication_id(
&self,
previous_state: storage::Authentication,
authentication_update: storage::AuthenticationUpdate,
) -> CustomResult<storage::Authentication, errors::StorageError> {
let mut authentications = self.authentications.lock().await;
let authentication_id = previous_state.authentication_id.clone();
let merchant_id = previous_state.merchant_id.clone();
authentications
.iter_mut()
.find(|authentication| authentication.authentication_id == authentication_id && authentication.merchant_id == merchant_id)
.map(|authentication| {
let authentication_update_internal =
AuthenticationUpdateInternal::from(authentication_update);
let updated_authentication = authentication_update_internal.apply_changeset(previous_state);
*authentication = updated_authentication.clone();
updated_authentication
})
.ok_or(
errors::StorageError::ValueNotFound(format!(
"cannot find authentication for authentication_id = {authentication_id:?} and merchant_id = {merchant_id:?}"
))
.into(),
)
}
}
|
crates/router/src/db/authentication.rs
|
router
|
full_file
| 1,863
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct MerchantConnectorCreate {
/// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking.
#[schema(value_type = ConnectorType, example = "payment_processor")]
pub connector_type: api_enums::ConnectorType,
/// Name of the Connector
#[schema(value_type = Connector, example = "stripe")]
pub connector_name: api_enums::Connector,
/// This is an unique label you can generate and pass in order to identify this connector account on your Hyperswitch dashboard and reports, If not passed then if will take `connector_name`_`profile_name`. Eg: if your profile label is `default`, connector label can be `stripe_default`
#[schema(example = "stripe_US_travel")]
pub connector_label: Option<String>,
/// Identifier for the profile, if not provided default will be chosen from merchant account
#[schema(max_length = 64, value_type = String)]
pub profile_id: id_type::ProfileId,
/// An object containing the required details/credentials for a Connector account.
#[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))]
pub connector_account_details: Option<pii::SecretSerdeValue>,
/// An object containing the details about the payment methods that need to be enabled under this merchant connector account
#[schema(value_type = PaymentMethodsEnabled)]
pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>,
/// Webhook details of this merchant connector
#[schema(example = json!({
"connector_webhook_details": {
"merchant_secret": "1234567890987654321"
}
}))]
pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))]
pub metadata: Option<pii::SecretSerdeValue>,
/// A boolean value to indicate if the connector is disabled. By default, its value is false.
#[schema(default = false, example = false)]
pub disabled: Option<bool>,
/// Contains the frm configs for the merchant connector
#[schema(example = json!(consts::FRM_CONFIGS_EG))]
pub frm_configs: Option<Vec<FrmConfigs>>,
/// pm_auth_config will relate MCA records to their respective chosen auth services, based on payment_method and pmt
#[schema(value_type = Option<Object>)]
pub pm_auth_config: Option<pii::SecretSerdeValue>,
#[schema(value_type = Option<ConnectorStatus>, example = "inactive")]
// By default the ConnectorStatus is Active
pub status: Option<api_enums::ConnectorStatus>,
/// In case the merchant needs to store any additional sensitive data
#[schema(value_type = Option<AdditionalMerchantData>)]
pub additional_merchant_data: Option<AdditionalMerchantData>,
/// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials
#[schema(value_type = Option<ConnectorWalletDetails>)]
pub connector_wallets_details: Option<ConnectorWalletDetails>,
/// Additional data that might be required by hyperswitch, to enable some specific features.
#[schema(value_type = Option<MerchantConnectorAccountFeatureMetadata>)]
pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>,
}
|
crates/api_models/src/admin.rs
|
api_models
|
struct_definition
| 776
|
rust
|
MerchantConnectorCreate
| null | null | null | null | null | null | null | null | null | null | null |
pub struct DeliveryOptions {
id: String,
price: ChargeAmount,
shipping_method: ShippingMethod,
is_default: bool,
}
|
crates/hyperswitch_connectors/src/connectors/amazonpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 30
|
rust
|
DeliveryOptions
| null | null | null | null | null | null | null | null | null | null | null |
impl ConnectorSpecifications for Redsys {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&REDSYS_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*REDSYS_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::EventClass]> {
Some(&REDSYS_SUPPORTED_WEBHOOK_FLOWS)
}
#[cfg(feature = "v1")]
fn generate_connector_request_reference_id(
&self,
payment_intent: &hyperswitch_domain_models::payments::PaymentIntent,
payment_attempt: &hyperswitch_domain_models::payments::payment_attempt::PaymentAttempt,
is_config_enabled_to_send_payment_id_as_connector_request_id: bool,
) -> String {
if is_config_enabled_to_send_payment_id_as_connector_request_id
&& payment_intent.is_payment_id_from_merchant.unwrap_or(false)
{
payment_attempt.payment_id.get_string_repr().to_owned()
} else {
connector_utils::generate_12_digit_number().to_string()
}
}
}
|
crates/hyperswitch_connectors/src/connectors/redsys.rs
|
hyperswitch_connectors
|
impl_block
| 250
|
rust
| null |
Redsys
|
ConnectorSpecifications for
|
impl ConnectorSpecifications for for Redsys
| null | null | null | null | null | null | null | null |
impl api::PaymentAuthorize for Nmi {}
|
crates/hyperswitch_connectors/src/connectors/nmi.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Nmi
|
api::PaymentAuthorize for
|
impl api::PaymentAuthorize for for Nmi
| null | null | null | null | null | null | null | null |
File: crates/router/src/services/api.rs
Public functions: 20
Public structs: 1
pub mod client;
pub mod generic_link_response;
pub mod request;
use std::{
collections::{HashMap, HashSet},
fmt::Debug,
future::Future,
str,
sync::Arc,
time::{Duration, Instant},
};
use actix_http::header::HeaderMap;
use actix_web::{
body,
http::header::{HeaderName, HeaderValue},
web, FromRequest, HttpRequest, HttpResponse, Responder, ResponseError,
};
pub use client::{ApiClient, MockApiClient, ProxyClient};
pub use common_enums::enums::PaymentAction;
pub use common_utils::request::{ContentType, Method, Request, RequestBuilder};
use common_utils::{
consts::{DEFAULT_TENANT, TENANT_HEADER, X_HS_LATENCY},
errors::{ErrorSwitch, ReportSwitchExt},
request::RequestContent,
};
use error_stack::{report, Report, ResultExt};
use hyperswitch_domain_models::router_data_v2::flow_common_types as common_types;
pub use hyperswitch_domain_models::{
api::{
ApplicationResponse, GenericExpiredLinkData, GenericLinkFormData, GenericLinkStatusData,
GenericLinks, PaymentLinkAction, PaymentLinkFormData, PaymentLinkStatusData,
RedirectionFormData,
},
payment_method_data::PaymentMethodData,
router_response_types::RedirectForm,
};
pub use hyperswitch_interfaces::{
api::{
BoxedConnectorIntegration, CaptureSyncMethod, ConnectorIntegration,
ConnectorIntegrationAny, ConnectorRedirectResponse, ConnectorSpecifications,
ConnectorValidation,
},
connector_integration_v2::{
BoxedConnectorIntegrationV2, ConnectorIntegrationAnyV2, ConnectorIntegrationV2,
},
};
use masking::{Maskable, PeekInterface, Secret};
use router_env::{instrument, tracing, tracing_actix_web::RequestId, Tag};
use serde::Serialize;
use serde_json::json;
use tera::{Context, Error as TeraError, Tera};
use super::{
authentication::AuthenticateAndFetch,
connector_integration_interface::BoxedConnectorIntegrationInterface,
};
use crate::{
configs::Settings,
consts,
core::{
api_locking,
errors::{self, CustomResult},
payments, unified_connector_service,
},
events::{
api_logs::{ApiEvent, ApiEventMetric, ApiEventsType},
connector_api_logs::ConnectorEvent,
},
headers, logger,
routes::{
app::{AppStateInfo, ReqState, SessionStateInfo},
metrics, AppState, SessionState,
},
services::{
connector_integration_interface::RouterDataConversion,
generic_link_response::build_generic_link_html,
},
types::{self, api, ErrorResponse},
utils,
};
pub type BoxedPaymentConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::PaymentFlowData, Req, Resp>;
pub type BoxedRefundConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::RefundFlowData, Req, Resp>;
#[cfg(feature = "frm")]
pub type BoxedFrmConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::FrmFlowData, Req, Resp>;
pub type BoxedDisputeConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::DisputesFlowData, Req, Resp>;
pub type BoxedMandateRevokeConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::MandateRevokeFlowData, Req, Resp>;
#[cfg(feature = "payouts")]
pub type BoxedPayoutConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::PayoutFlowData, Req, Resp>;
pub type BoxedWebhookSourceVerificationConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::WebhookSourceVerifyData, Req, Resp>;
pub type BoxedExternalAuthenticationConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::ExternalAuthenticationFlowData, Req, Resp>;
pub type BoxedAuthenticationTokenConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::AuthenticationTokenFlowData, Req, Resp>;
pub type BoxedAccessTokenConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::AccessTokenFlowData, Req, Resp>;
pub type BoxedFilesConnectorIntegrationInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::FilesFlowData, Req, Resp>;
pub type BoxedRevenueRecoveryRecordBackInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::RevenueRecoveryRecordBackData, Req, Res>;
pub type BoxedBillingConnectorInvoiceSyncIntegrationInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<
T,
common_types::BillingConnectorInvoiceSyncFlowData,
Req,
Res,
>;
pub type BoxedUnifiedAuthenticationServiceInterface<T, Req, Resp> =
BoxedConnectorIntegrationInterface<T, common_types::UasFlowData, Req, Resp>;
pub type BoxedBillingConnectorPaymentsSyncIntegrationInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<
T,
common_types::BillingConnectorPaymentsSyncFlowData,
Req,
Res,
>;
pub type BoxedVaultConnectorIntegrationInterface<T, Req, Res> =
BoxedConnectorIntegrationInterface<T, common_types::VaultConnectorFlowData, Req, Res>;
/// Handle UCS webhook response processing
fn handle_ucs_response<T, Req, Resp>(
router_data: types::RouterData<T, Req, Resp>,
transform_data_bytes: Vec<u8>,
) -> CustomResult<types::RouterData<T, Req, Resp>, errors::ConnectorError>
where
T: Clone + Debug + 'static,
Req: Debug + Clone + 'static,
Resp: Debug + Clone + 'static,
{
let webhook_transform_data: unified_connector_service::WebhookTransformData =
serde_json::from_slice(&transform_data_bytes)
.change_context(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("Failed to deserialize UCS webhook transform data")?;
let webhook_content = webhook_transform_data
.webhook_content
.ok_or(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("UCS webhook transform data missing webhook_content")?;
let payment_get_response = match webhook_content.content {
Some(unified_connector_service_client::payments::webhook_response_content::Content::PaymentsResponse(payments_response)) => {
Ok(payments_response)
},
Some(unified_connector_service_client::payments::webhook_response_content::Content::RefundsResponse(_)) => {
Err(errors::ConnectorError::ProcessingStepFailed(Some("UCS webhook contains refund response but payment processing was expected".to_string().into())).into())
},
Some(unified_connector_service_client::payments::webhook_response_content::Content::DisputesResponse(_)) => {
Err(errors::ConnectorError::ProcessingStepFailed(Some("UCS webhook contains dispute response but payment processing was expected".to_string().into())).into())
},
None => {
Err(errors::ConnectorError::ResponseDeserializationFailed)
.attach_printable("UCS webhook content missing payments_response")
}
}?;
let (status, router_data_response, status_code) =
unified_connector_service::handle_unified_connector_service_response_for_payment_get(
payment_get_response.clone(),
)
.change_context(errors::ConnectorError::ProcessingStepFailed(None))
.attach_printable("Failed to process UCS webhook response using PSync handler")?;
let mut updated_router_data = router_data;
updated_router_data.status = status;
let _ = router_data_response.map_err(|error_response| {
updated_router_data.response = Err(error_response);
});
updated_router_data.raw_connector_response =
payment_get_response.raw_connector_response.map(Secret::new);
updated_router_data.connector_http_status_code = Some(status_code);
Ok(updated_router_data)
}
fn store_raw_connector_response_if_required<T, Req, Resp>(
return_raw_connector_response: Option<bool>,
router_data: &mut types::RouterData<T, Req, Resp>,
body: &types::Response,
) -> CustomResult<(), errors::ConnectorError>
where
T: Clone + Debug + 'static,
Req: Debug + Clone + 'static,
Resp: Debug + Clone + 'static,
{
if return_raw_connector_response == Some(true) {
let mut decoded = String::from_utf8(body.response.as_ref().to_vec())
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
if decoded.starts_with('\u{feff}') {
decoded = decoded.trim_start_matches('\u{feff}').to_string();
}
router_data.raw_connector_response = Some(Secret::new(decoded));
}
Ok(())
}
/// Handle the flow by interacting with connector module
/// `connector_request` is applicable only in case if the `CallConnectorAction` is `Trigger`
/// In other cases, It will be created if required, even if it is not passed
#[instrument(skip_all, fields(connector_name, payment_method))]
pub async fn execute_connector_processing_step<
'b,
'a,
T,
ResourceCommonData: Clone + RouterDataConversion<T, Req, Resp> + 'static,
Req: Debug + Clone + 'static,
Resp: Debug + Clone + 'static,
>(
state: &'b SessionState,
connector_integration: BoxedConnectorIntegrationInterface<T, ResourceCommonData, Req, Resp>,
req: &'b types::RouterData<T, Req, Resp>,
call_connector_action: payments::CallConnectorAction,
connector_request: Option<Request>,
return_raw_connector_response: Option<bool>,
) -> CustomResult<types::RouterData<T, Req, Resp>, errors::ConnectorError>
where
T: Clone + Debug + 'static,
// BoxedConnectorIntegration<T, Req, Resp>: 'b,
{
// If needed add an error stack as follows
// connector_integration.build_request(req).attach_printable("Failed to build request");
tracing::Span::current().record("connector_name", &req.connector);
tracing::Span::current().record("payment_method", req.payment_method.to_string());
logger::debug!(connector_request=?connector_request);
let mut router_data = req.clone();
match call_connector_action {
payments::CallConnectorAction::HandleResponse(res) => {
let response = types::Response {
headers: None,
response: res.into(),
status_code: 200,
};
connector_integration.handle_response(req, None, response)
}
payments::CallConnectorAction::UCSHandleResponse(transform_data_bytes) => {
handle_ucs_response(router_data, transform_data_bytes)
}
payments::CallConnectorAction::Avoid => Ok(router_data),
payments::CallConnectorAction::StatusUpdate {
status,
error_code,
error_message,
} => {
router_data.status = status;
let error_response = if error_code.is_some() | error_message.is_some() {
Some(ErrorResponse {
code: error_code.unwrap_or(consts::NO_ERROR_CODE.to_string()),
message: error_message.unwrap_or(consts::NO_ERROR_MESSAGE.to_string()),
status_code: 200, // This status code is ignored in redirection response it will override with 302 status code.
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
} else {
None
};
router_data.response = error_response.map(Err).unwrap_or(router_data.response);
Ok(router_data)
}
payments::CallConnectorAction::Trigger => {
metrics::CONNECTOR_CALL_COUNT.add(
1,
router_env::metric_attributes!(
("connector", req.connector.to_string()),
(
"flow",
std::any::type_name::<T>()
.split("::")
.last()
.unwrap_or_default()
),
),
);
let connector_request = match connector_request {
Some(connector_request) => Some(connector_request),
None => connector_integration
.build_request(req, &state.conf.connectors)
.inspect_err(|error| {
if matches!(
error.current_context(),
&errors::ConnectorError::RequestEncodingFailed
| &errors::ConnectorError::RequestEncodingFailedWithReason(_)
) {
metrics::REQUEST_BUILD_FAILURE.add(
1,
router_env::metric_attributes!((
"connector",
req.connector.clone()
)),
)
}
})?,
};
match connector_request {
Some(request) => {
let masked_request_body = match &request.body {
Some(request) => match request {
RequestContent::Json(i)
| RequestContent::FormUrlEncoded(i)
| RequestContent::Xml(i) => i
.masked_serialize()
.unwrap_or(json!({ "error": "failed to mask serialize"})),
RequestContent::FormData(_) => json!({"request_type": "FORM_DATA"}),
RequestContent::RawBytes(_) => json!({"request_type": "RAW_BYTES"}),
},
None => serde_json::Value::Null,
};
let request_url = request.url.clone();
let request_method = request.method;
let current_time = Instant::now();
let response =
call_connector_api(state, request, "execute_connector_processing_step")
.await;
let external_latency = current_time.elapsed().as_millis();
logger::info!(raw_connector_request=?masked_request_body);
let status_code = response
.as_ref()
.map(|i| {
i.as_ref()
.map_or_else(|value| value.status_code, |value| value.status_code)
})
.unwrap_or_default();
let mut connector_event = ConnectorEvent::new(
state.tenant.tenant_id.clone(),
req.connector.clone(),
std::any::type_name::<T>(),
masked_request_body,
request_url,
request_method,
req.payment_id.clone(),
req.merchant_id.clone(),
state.request_id.as_ref(),
external_latency,
req.refund_id.clone(),
req.dispute_id.clone(),
status_code,
);
match response {
Ok(body) => {
let response = match body {
Ok(body) => {
let connector_http_status_code = Some(body.status_code);
let handle_response_result = connector_integration
.handle_response(req, Some(&mut connector_event), body.clone())
.inspect_err(|error| {
if error.current_context()
== &errors::ConnectorError::ResponseDeserializationFailed
{
metrics::RESPONSE_DESERIALIZATION_FAILURE.add(
1,
router_env::metric_attributes!((
"connector",
req.connector.clone(),
)),
)
}
});
match handle_response_result {
Ok(mut data) => {
state.event_handler().log_event(&connector_event);
data.connector_http_status_code =
connector_http_status_code;
// Add up multiple external latencies in case of multiple external calls within the same request.
data.external_latency = Some(
data.external_latency
.map_or(external_latency, |val| {
val + external_latency
}),
);
store_raw_connector_response_if_required(
return_raw_connector_response,
&mut data,
&body,
)?;
Ok(data)
}
Err(err) => {
connector_event
.set_error(json!({"error": err.to_string()}));
state.event_handler().log_event(&connector_event);
Err(err)
}
}?
}
Err(body) => {
router_data.connector_http_status_code = Some(body.status_code);
router_data.external_latency = Some(
router_data
.external_latency
.map_or(external_latency, |val| val + external_latency),
);
metrics::CONNECTOR_ERROR_RESPONSE_COUNT.add(
1,
router_env::metric_attributes!((
"connector",
req.connector.clone(),
)),
);
store_raw_connector_response_if_required(
return_raw_connector_response,
&mut router_data,
&body,
)?;
let error = match body.status_code {
500..=511 => {
let error_res = connector_integration
.get_5xx_error_response(
body,
Some(&mut connector_event),
)?;
state.event_handler().log_event(&connector_event);
error_res
}
_ => {
let error_res = connector_integration
.get_error_response(
body,
Some(&mut connector_event),
)?;
if let Some(status) = error_res.attempt_status {
router_data.status = status;
};
state.event_handler().log_event(&connector_event);
error_res
}
};
router_data.response = Err(error);
router_data
}
};
Ok(response)
}
Err(error) => {
connector_event.set_error(json!({"error": error.to_string()}));
state.event_handler().log_event(&connector_event);
if error.current_context().is_upstream_timeout() {
let error_response = ErrorResponse {
code: consts::REQUEST_TIMEOUT_ERROR_CODE.to_string(),
message: consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string(),
reason: Some(consts::REQUEST_TIMEOUT_ERROR_MESSAGE.to_string()),
status_code: 504,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
};
router_data.response = Err(error_response);
router_data.connector_http_status_code = Some(504);
router_data.external_latency = Some(
router_data
.external_latency
.map_or(external_latency, |val| val + external_latency),
);
Ok(router_data)
} else {
Err(error.change_context(
errors::ConnectorError::ProcessingStepFailed(None),
))
}
}
}
}
None => Ok(router_data),
}
}
}
}
#[instrument(skip_all)]
pub async fn call_connector_api(
state: &SessionState,
request: Request,
flow_name: &str,
) -> CustomResult<Result<types::Response, types::Response>, errors::ApiClientError> {
let current_time = Instant::now();
let headers = request.headers.clone();
let url = request.url.clone();
let response = state
.api_client
.send_request(state, request, None, true)
.await;
match response.as_ref() {
Ok(resp) => {
let status_code = resp.status().as_u16();
let elapsed_time = current_time.elapsed();
logger::info!(
?headers,
url,
status_code,
flow=?flow_name,
?elapsed_time
);
}
Err(err) => {
logger::info!(
call_connector_api_error=?err
);
}
}
handle_response(response).await
}
#[instrument(skip_all)]
async fn handle_response(
response: CustomResult<reqwest::Response, errors::ApiClientError>,
) -> CustomResult<Result<types::Response, types::Response>, errors::ApiClientError> {
response
.map(|response| async {
logger::info!(?response);
let status_code = response.status().as_u16();
let headers = Some(response.headers().to_owned());
match status_code {
200..=202 | 302 | 204 => {
// If needed add log line
// logger:: error!( error_parsing_response=?err);
let response = response
.bytes()
.await
.change_context(errors::ApiClientError::ResponseDecodingFailed)
.attach_printable("Error while waiting for response")?;
Ok(Ok(types::Response {
headers,
response,
status_code,
}))
}
status_code @ 500..=599 => {
let bytes = response.bytes().await.map_err(|error| {
report!(error)
.change_context(errors::ApiClientError::ResponseDecodingFailed)
.attach_printable("Client error response received")
})?;
// let error = match status_code {
// 500 => errors::ApiClientError::InternalServerErrorReceived,
// 502 => errors::ApiClientError::BadGatewayReceived,
// 503 => errors::ApiClientError::ServiceUnavailableReceived,
// 504 => errors::ApiClientError::GatewayTimeoutReceived,
// _ => errors::ApiClientError::UnexpectedServerResponse,
// };
Ok(Err(types::Response {
headers,
response: bytes,
status_code,
}))
}
status_code @ 400..=499 => {
let bytes = response.bytes().await.map_err(|error| {
report!(error)
.change_context(errors::ApiClientError::ResponseDecodingFailed)
.attach_printable("Client error response received")
})?;
/* let error = match status_code {
400 => errors::ApiClientError::BadRequestReceived(bytes),
401 => errors::ApiClientError::UnauthorizedReceived(bytes),
403 => errors::ApiClientError::ForbiddenReceived,
404 => errors::ApiClientError::NotFoundReceived(bytes),
405 => errors::ApiClientError::MethodNotAllowedReceived,
408 => errors::ApiClientError::RequestTimeoutReceived,
422 => errors::ApiClientError::UnprocessableEntityReceived(bytes),
429 => errors::ApiClientError::TooManyRequestsReceived,
_ => errors::ApiClientError::UnexpectedServerResponse,
};
Err(report!(error).attach_printable("Client error response received"))
*/
Ok(Err(types::Response {
headers,
response: bytes,
status_code,
}))
}
_ => Err(report!(errors::ApiClientError::UnexpectedServerResponse)
.attach_printable("Unexpected response from server")),
}
})?
.await
}
#[derive(Debug, Eq, PartialEq, Serialize)]
pub struct ApplicationRedirectResponse {
pub url: String,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum AuthFlow {
Client,
Merchant,
}
#[allow(clippy::too_many_arguments)]
#[instrument(
skip(request, payload, state, func, api_auth, incoming_request_header),
fields(merchant_id)
)]
pub async fn server_wrap_util<'a, 'b, U, T, Q, F, Fut, E, OErr>(
flow: &'a impl router_env::types::FlowMetric,
state: web::Data<AppState>,
incoming_request_header: &HeaderMap,
request: &'a HttpRequest,
payload: T,
func: F,
api_auth: &dyn AuthenticateAndFetch<U, SessionState>,
lock_action: api_locking::LockAction,
) -> CustomResult<ApplicationResponse<Q>, OErr>
where
F: Fn(SessionState, U, T, ReqState) -> Fut,
'b: 'a,
Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>,
Q: Serialize + Debug + 'a + ApiEventMetric,
T: Debug + Serialize + ApiEventMetric,
E: ErrorSwitch<OErr> + error_stack::Context,
OErr: ResponseError + error_stack::Context + Serialize,
errors::ApiErrorResponse: ErrorSwitch<OErr>,
{
let request_id = RequestId::extract(request)
.await
.attach_printable("Unable to extract request id from request")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?;
let mut app_state = state.get_ref().clone();
let start_instant = Instant::now();
let serialized_request = masking::masked_serialize(&payload)
.attach_printable("Failed to serialize json request")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?;
let mut event_type = payload.get_api_event_type();
let tenant_id = if !state.conf.multitenancy.enabled {
common_utils::id_type::TenantId::try_from_string(DEFAULT_TENANT.to_owned())
.attach_printable("Unable to get default tenant id")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?
} else {
let request_tenant_id = incoming_request_header
.get(TENANT_HEADER)
.and_then(|value| value.to_str().ok())
.ok_or_else(|| errors::ApiErrorResponse::MissingTenantId.switch())
.and_then(|header_value| {
common_utils::id_type::TenantId::try_from_string(header_value.to_string()).map_err(
|_| {
errors::ApiErrorResponse::InvalidRequestData {
message: format!("`{}` header is invalid", headers::X_TENANT_ID),
}
.switch()
},
)
})?;
state
.conf
.multitenancy
.get_tenant(&request_tenant_id)
.map(|tenant| tenant.tenant_id.clone())
.ok_or(
errors::ApiErrorResponse::InvalidTenant {
tenant_id: request_tenant_id.get_string_repr().to_string(),
}
.switch(),
)?
};
let locale = utils::get_locale_from_header(&incoming_request_header.clone());
let mut session_state =
Arc::new(app_state.clone()).get_session_state(&tenant_id, Some(locale), || {
errors::ApiErrorResponse::InvalidTenant {
tenant_id: tenant_id.get_string_repr().to_string(),
}
.switch()
})?;
session_state.add_request_id(request_id);
let mut request_state = session_state.get_req_state();
request_state.event_context.record_info(request_id);
request_state
.event_context
.record_info(("flow".to_string(), flow.to_string()));
request_state.event_context.record_info((
"tenant_id".to_string(),
tenant_id.get_string_repr().to_string(),
));
// Currently auth failures are not recorded as API events
let (auth_out, auth_type) = api_auth
.authenticate_and_fetch(request.headers(), &session_state)
.await
.switch()?;
request_state.event_context.record_info(auth_type.clone());
let merchant_id = auth_type
.get_merchant_id()
.cloned()
.unwrap_or(common_utils::id_type::MerchantId::get_merchant_id_not_found());
app_state.add_flow_name(flow.to_string());
tracing::Span::current().record("merchant_id", merchant_id.get_string_repr().to_owned());
let output = {
lock_action
.clone()
.perform_locking_action(&session_state, merchant_id.to_owned())
.await
.switch()?;
let res = func(session_state.clone(), auth_out, payload, request_state)
.await
.switch();
lock_action
.free_lock_action(&session_state, merchant_id.to_owned())
.await
.switch()?;
res
};
let request_duration = Instant::now()
.saturating_duration_since(start_instant)
.as_millis();
let mut serialized_response = None;
let mut error = None;
let mut overhead_latency = None;
let status_code = match output.as_ref() {
Ok(res) => {
if let ApplicationResponse::Json(data) = res {
serialized_response.replace(
masking::masked_serialize(&data)
.attach_printable("Failed to serialize json response")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?,
);
} else if let ApplicationResponse::JsonWithHeaders((data, headers)) = res {
serialized_response.replace(
masking::masked_serialize(&data)
.attach_printable("Failed to serialize json response")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())?,
);
if let Some((_, value)) = headers.iter().find(|(key, _)| key == X_HS_LATENCY) {
if let Ok(external_latency) = value.clone().into_inner().parse::<u128>() {
overhead_latency.replace(external_latency);
}
}
}
event_type = res.get_api_event_type().or(event_type);
metrics::request::track_response_status_code(res)
}
Err(err) => {
error.replace(
serde_json::to_value(err.current_context())
.attach_printable("Failed to serialize json response")
.change_context(errors::ApiErrorResponse::InternalServerError.switch())
.ok()
.into(),
);
err.current_context().status_code().as_u16().into()
}
};
let infra = extract_mapped_fields(
&serialized_request,
state.enhancement.as_ref(),
state.infra_components.as_ref(),
);
let api_event = ApiEvent::new(
tenant_id,
Some(merchant_id.clone()),
flow,
&request_id,
request_duration,
status_code,
serialized_request,
serialized_response,
overhead_latency,
auth_type,
error,
event_type.unwrap_or(ApiEventsType::Miscellaneous),
request,
request.method(),
infra.clone(),
);
state.event_handler().log_event(&api_event);
output
}
#[instrument(
skip(request, state, func, api_auth, payload),
fields(request_method, request_url_path, status_code)
)]
pub async fn server_wrap<'a, T, U, Q, F, Fut, E>(
flow: impl router_env::types::FlowMetric,
state: web::Data<AppState>,
request: &'a HttpRequest,
payload: T,
func: F,
api_auth: &dyn AuthenticateAndFetch<U, SessionState>,
lock_action: api_locking::LockAction,
) -> HttpResponse
where
F: Fn(SessionState, U, T, ReqState) -> Fut,
Fut: Future<Output = CustomResult<ApplicationResponse<Q>, E>>,
Q: Serialize + Debug + ApiEventMetric + 'a,
T: Debug + Serialize + ApiEventMetric,
ApplicationResponse<Q>: Debug,
E: ErrorSwitch<api_models::errors::types::ApiErrorResponse> + error_stack::Context,
{
let request_method = request.method().as_str();
let url_path = request.path();
let unmasked_incoming_header_keys = state.conf().unmasked_headers.keys;
let incoming_request_header = request.headers();
let incoming_header_to_log: HashMap<String, HeaderValue> =
incoming_request_header
.iter()
.fold(HashMap::new(), |mut acc, (key, value)| {
let key = key.to_string();
if unmasked_incoming_header_keys.contains(&key.as_str().to_lowercase()) {
acc.insert(key.clone(), value.clone());
} else {
acc.insert(key.clone(), HeaderValue::from_static("**MASKED**"));
}
acc
});
tracing::Span::current().record("request_method", request_method);
tracing::Span::current().record("request_url_path", url_path);
let start_instant = Instant::now();
logger::info!(
tag = ?Tag::BeginRequest, payload = ?payload,
headers = ?incoming_header_to_log);
let server_wrap_util_res = server_wrap_util(
&flow,
state.clone(),
incoming_request_header,
request,
payload,
func,
api_auth,
lock_action,
)
.await
.map(|response| {
logger::info!(api_response =? response);
response
});
let res = match server_wrap_util_res {
Ok(ApplicationResponse::Json(response)) => match serde_json::to_string(&response) {
Ok(res) => http_response_json(res),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error serializing response from connector"
}
}"#,
),
},
Ok(ApplicationResponse::StatusOk) => http_response_ok(),
Ok(ApplicationResponse::TextPlain(text)) => http_response_plaintext(text),
Ok(ApplicationResponse::FileData((file_data, content_type))) => {
http_response_file_data(file_data, content_type)
}
Ok(ApplicationResponse::JsonForRedirection(response)) => {
match serde_json::to_string(&response) {
Ok(res) => http_redirect_response(res, response),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error serializing response from connector"
}
}"#,
),
}
}
Ok(ApplicationResponse::Form(redirection_data)) => {
let config = state.conf();
build_redirection_form(
&redirection_data.redirect_form,
redirection_data.payment_method_data,
redirection_data.amount,
redirection_data.currency,
config,
)
.respond_to(request)
.map_into_boxed_body()
}
Ok(ApplicationResponse::GenericLinkForm(boxed_generic_link_data)) => {
let link_type = boxed_generic_link_data.data.to_string();
match build_generic_link_html(
boxed_generic_link_data.data,
boxed_generic_link_data.locale,
) {
Ok(rendered_html) => {
let headers = if !boxed_generic_link_data.allowed_domains.is_empty() {
let domains_str = boxed_generic_link_data
.allowed_domains
.into_iter()
.collect::<Vec<String>>()
.join(" ");
let csp_header = format!("frame-ancestors 'self' {domains_str};");
Some(HashSet::from([("content-security-policy", csp_header)]))
} else {
None
};
http_response_html_data(rendered_html, headers)
}
Err(_) => http_response_err(format!("Error while rendering {link_type} HTML page")),
}
}
Ok(ApplicationResponse::PaymentLinkForm(boxed_payment_link_data)) => {
match *boxed_payment_link_data {
PaymentLinkAction::PaymentLinkFormData(payment_link_data) => {
match build_payment_link_html(payment_link_data) {
Ok(rendered_html) => http_response_html_data(rendered_html, None),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error while rendering payment link html page"
}
}"#,
),
}
}
PaymentLinkAction::PaymentLinkStatus(payment_link_data) => {
match get_payment_link_status(payment_link_data) {
Ok(rendered_html) => http_response_html_data(rendered_html, None),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error while rendering payment link status page"
}
}"#,
),
}
}
}
}
Ok(ApplicationResponse::JsonWithHeaders((response, headers))) => {
let request_elapsed_time = request.headers().get(X_HS_LATENCY).and_then(|value| {
if value == "true" {
Some(start_instant.elapsed())
} else {
None
}
});
let proxy_connector_http_status_code = if state
.conf
.proxy_status_mapping
.proxy_connector_http_status_code
{
headers
.iter()
.find(|(key, _)| key == headers::X_CONNECTOR_HTTP_STATUS_CODE)
.and_then(|(_, value)| {
match value.clone().into_inner().parse::<u16>() {
Ok(code) => match http::StatusCode::from_u16(code) {
Ok(status_code) => Some(status_code),
Err(err) => {
logger::error!(
"Invalid HTTP status code parsed from connector_http_status_code: {:?}",
err
);
None
}
},
Err(err) => {
logger::error!(
"Failed to parse connector_http_status_code from header: {:?}",
err
);
None
}
}
})
} else {
None
};
match serde_json::to_string(&response) {
Ok(res) => http_response_json_with_headers(
res,
headers,
request_elapsed_time,
proxy_connector_http_status_code,
),
Err(_) => http_response_err(
r#"{
"error": {
"message": "Error serializing response from connector"
}
}"#,
),
}
}
Err(error) => log_and_return_error_response(error),
};
let response_code = res.status().as_u16();
tracing::Span::current().record("status_code", response_code);
let end_instant = Instant::now();
let request_duration = end_instant.saturating_duration_since(start_instant);
logger::info!(
tag = ?Tag::EndRequest,
time_taken_ms = request_duration.as_millis(),
);
res
}
pub fn log_and_return_error_response<T>(error: Report<T>) -> HttpResponse
where
T: error_stack::Context + Clone + ResponseError,
Report<T>: EmbedError,
{
logger::error!(?error);
HttpResponse::from_error(error.embed().current_context().clone())
}
pub trait EmbedError: Sized {
fn embed(self) -> Self {
self
}
}
impl EmbedError for Report<api_models::errors::types::ApiErrorResponse> {
fn embed(self) -> Self {
#[cfg(feature = "detailed_errors")]
{
let mut report = self;
let error_trace = serde_json::to_value(&report).ok().and_then(|inner| {
serde_json::from_value::<Vec<errors::NestedErrorStack<'_>>>(inner)
.ok()
.map(Into::<errors::VecLinearErrorStack<'_>>::into)
.map(serde_json::to_value)
.transpose()
.ok()
.flatten()
});
|
crates/router/src/services/api.rs#chunk0
|
router
|
chunk
| 8,192
| null | null | null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.CardNetworkTypes
{
"type": "object",
"required": [
"eligible_connectors"
],
"properties": {
"card_network": {
"allOf": [
{
"$ref": "#/components/schemas/CardNetwork"
}
],
"nullable": true
},
"surcharge_details": {
"allOf": [
{
"$ref": "#/components/schemas/SurchargeDetailsResponse"
}
],
"nullable": true
},
"eligible_connectors": {
"type": "array",
"items": {
"type": "string"
},
"description": "The list of eligible connectors for a given card network",
"example": [
"stripe",
"adyen"
]
}
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 183
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"CardNetworkTypes"
] | null | null | null | null |
pub async fn get_user_details(state: web::Data<AppState>, req: HttpRequest) -> HttpResponse {
let flow = Flow::GetUserDetails;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, user, _, _| user_core::get_user_details(state, user),
&auth::DashboardNoPermissionAuth,
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/user.rs
|
router
|
function_signature
| 98
|
rust
| null | null | null | null |
get_user_details
| null | null | null | null | null | null | null |
pub struct Mandates {
pub supported_payment_methods: SupportedPaymentMethodsForMandate,
pub update_mandate_supported: SupportedPaymentMethodsForMandate,
}
|
crates/payment_methods/src/configs/settings.rs
|
payment_methods
|
struct_definition
| 36
|
rust
|
Mandates
| null | null | null | null | null | null | null | null | null | null | null |
pub fn get_organization_id_from_header(&self) -> RouterResult<id_type::OrganizationId> {
self.get_mandatory_header_value_by_key(headers::X_ORGANIZATION_ID)
.map(|val| val.to_owned())
.and_then(|organization_id| {
id_type::OrganizationId::try_from_string(organization_id).change_context(
errors::ApiErrorResponse::InvalidRequestData {
message: format!("`{}` header is invalid", headers::X_ORGANIZATION_ID),
},
)
})
}
|
crates/router/src/services/authentication.rs
|
router
|
function_signature
| 112
|
rust
| null | null | null | null |
get_organization_id_from_header
| null | null | null | null | null | null | null |
pub async fn get_file_purpose(field: &mut Field) -> Option<api::FilePurpose> {
let purpose = read_string(field).await;
match purpose.as_deref() {
Some("dispute_evidence") => Some(api::FilePurpose::DisputeEvidence),
_ => None,
}
}
|
crates/router/src/core/files/helpers.rs
|
router
|
function_signature
| 67
|
rust
| null | null | null | null |
get_file_purpose
| null | null | null | null | null | null | null |
Web Documentation: SDK Reference | Hyperswitch
# Type: Web Doc
Hyperswitch provides frontend integration solutions through SDKs tailored for various frameworks, including React and JavaScript. These SDKs come with pre-built support for the frameworks used in your application, eliminating the need for additional code to ensure compatibility. The following documentation offers detailed information on the APIs of these SDKs, outlining their methods and purposes:
React SDK Reference
: Explore the React SDK methods and their parameters to customize your payment experience.
JavaScript SDK Reference
: Discover the JavaScript SDK methods available for tailoring your payment integration.
React + HTML
JS
These resources provide comprehensive guidance to help you effectively integrate Hyperswitch's payment solutions into your applications.
7 months ago
Was this helpful?
|
https://docs.hyperswitch.io/learn-more/sdk-reference
| null |
web_doc_file
| 159
|
doc
| null | null | null | null | null |
web
| null | null | null |
https://docs.hyperswitch.io/learn-more/sdk-reference
|
SDK Reference | Hyperswitch
| null |
pub fn should_call_connector_create_customer<'a>(
state: &SessionState,
connector: &api::ConnectorData,
customer: &'a Option<domain::Customer>,
merchant_connector_account: &domain::MerchantConnectorAccountTypeDetails,
) -> (bool, Option<&'a str>) {
// Check if create customer is required for the connector
match merchant_connector_account {
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(_) => {
let connector_needs_customer = state
.conf
.connector_customer
.connector_list
.contains(&connector.connector_name);
if connector_needs_customer {
let connector_customer_details = customer
.as_ref()
.and_then(|cust| cust.get_connector_customer_id(merchant_connector_account));
let should_call_connector = connector_customer_details.is_none();
(should_call_connector, connector_customer_details)
} else {
(false, None)
}
}
// TODO: Construct connector_customer for MerchantConnectorDetails if required by connector.
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => {
todo!("Handle connector_customer construction for MerchantConnectorDetails");
}
}
}
|
crates/router/src/core/payments/customers.rs
|
router
|
function_signature
| 248
|
rust
| null | null | null | null |
should_call_connector_create_customer
| null | null | null | null | null | null | null |
pub async fn create_routing_algorithm_under_profile(
state: SessionState,
merchant_context: domain::MerchantContext,
authentication_profile_id: Option<common_utils::id_type::ProfileId>,
request: routing_types::RoutingConfigRequest,
transaction_type: enums::TransactionType,
) -> RouterResponse<routing_types::RoutingDictionaryRecord> {
use api_models::routing::StaticRoutingAlgorithm as EuclidAlgorithm;
metrics::ROUTING_CREATE_REQUEST_RECEIVED.add(1, &[]);
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let name = request
.name
.get_required_value("name")
.change_context(errors::ApiErrorResponse::MissingRequiredField { field_name: "name" })
.attach_printable("Name of config not given")?;
let description = request
.description
.get_required_value("description")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "description",
})
.attach_printable("Description of config not given")?;
let algorithm = request
.algorithm
.clone()
.get_required_value("algorithm")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "algorithm",
})
.attach_printable("Algorithm of config not given")?;
let algorithm_id = common_utils::generate_routing_id_of_default_length();
let profile_id = request
.profile_id
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::MissingRequiredField {
field_name: "profile_id",
})
.attach_printable("Profile_id not provided")?;
let business_profile = core_utils::validate_and_get_business_profile(
db,
key_manager_state,
merchant_context.get_merchant_key_store(),
Some(&profile_id),
merchant_context.get_merchant_account().get_id(),
)
.await?
.get_required_value("Profile")?;
core_utils::validate_profile_id_from_auth_layer(authentication_profile_id, &business_profile)?;
if algorithm.should_validate_connectors_in_routing_config() {
helpers::validate_connectors_in_routing_config(
&state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().get_id(),
&profile_id,
&algorithm,
)
.await?;
}
let mut decision_engine_routing_id: Option<String> = None;
if let Some(euclid_algorithm) = request.algorithm.clone() {
let maybe_static_algorithm: Option<StaticRoutingAlgorithm> = match euclid_algorithm {
EuclidAlgorithm::Advanced(program) => match program.try_into() {
Ok(internal_program) => Some(StaticRoutingAlgorithm::Advanced(internal_program)),
Err(e) => {
router_env::logger::error!(decision_engine_error = ?e, "decision_engine_euclid");
None
}
},
EuclidAlgorithm::Single(conn) => {
Some(StaticRoutingAlgorithm::Single(Box::new(conn.into())))
}
EuclidAlgorithm::Priority(connectors) => {
let converted: Vec<ConnectorInfo> =
connectors.into_iter().map(Into::into).collect();
Some(StaticRoutingAlgorithm::Priority(converted))
}
EuclidAlgorithm::VolumeSplit(splits) => {
let converted: Vec<VolumeSplit<ConnectorInfo>> =
splits.into_iter().map(Into::into).collect();
Some(StaticRoutingAlgorithm::VolumeSplit(converted))
}
EuclidAlgorithm::ThreeDsDecisionRule(_) => {
router_env::logger::error!(
"decision_engine_euclid: ThreeDsDecisionRules are not yet implemented"
);
None
}
};
if let Some(static_algorithm) = maybe_static_algorithm {
let routing_rule = RoutingRule {
rule_id: Some(algorithm_id.clone().get_string_repr().to_owned()),
name: name.clone(),
description: Some(description.clone()),
created_by: profile_id.get_string_repr().to_string(),
algorithm: static_algorithm,
algorithm_for: transaction_type.into(),
metadata: Some(RoutingMetadata {
kind: algorithm.get_kind().foreign_into(),
}),
};
match create_de_euclid_routing_algo(&state, &routing_rule).await {
Ok(id) => {
decision_engine_routing_id = Some(id);
}
Err(e)
if matches!(
e.current_context(),
errors::RoutingError::DecisionEngineValidationError(_)
) =>
{
if let errors::RoutingError::DecisionEngineValidationError(msg) =
e.current_context()
{
router_env::logger::error!(
decision_engine_euclid_error = ?msg,
decision_engine_euclid_request = ?routing_rule,
"failed to create rule in decision_engine with validation error"
);
}
}
Err(e) => {
router_env::logger::error!(
decision_engine_euclid_error = ?e,
decision_engine_euclid_request = ?routing_rule,
"failed to create rule in decision_engine"
);
}
}
}
}
if decision_engine_routing_id.is_some() {
router_env::logger::info!(routing_flow=?"create_euclid_routing_algorithm", is_equal=?"true", "decision_engine_euclid");
} else {
router_env::logger::info!(routing_flow=?"create_euclid_routing_algorithm", is_equal=?"false", "decision_engine_euclid");
}
let timestamp = common_utils::date_time::now();
let algo = RoutingAlgorithm {
algorithm_id: algorithm_id.clone(),
profile_id,
merchant_id: merchant_context.get_merchant_account().get_id().to_owned(),
name: name.clone(),
description: Some(description.clone()),
kind: algorithm.get_kind().foreign_into(),
algorithm_data: serde_json::json!(algorithm),
created_at: timestamp,
modified_at: timestamp,
algorithm_for: transaction_type.to_owned(),
decision_engine_routing_id,
};
let record = db
.insert_routing_algorithm(algo)
.await
.to_not_found_response(errors::ApiErrorResponse::ResourceIdNotFound)?;
let new_record = record.foreign_into();
metrics::ROUTING_CREATE_SUCCESS_RESPONSE.add(1, &[]);
Ok(service_api::ApplicationResponse::Json(new_record))
}
|
crates/router/src/core/routing.rs
|
router
|
function_signature
| 1,334
|
rust
| null | null | null | null |
create_routing_algorithm_under_profile
| null | null | null | null | null | null | null |
impl KafkaMessage for ApiEvent {
fn event_type(&self) -> EventType {
EventType::ApiLogs
}
fn key(&self) -> String {
self.request_id.clone()
}
}
|
crates/router/src/events/api_logs.rs
|
router
|
impl_block
| 43
|
rust
| null |
ApiEvent
|
KafkaMessage for
|
impl KafkaMessage for for ApiEvent
| null | null | null | null | null | null | null | null |
/// A boolean value to indicate if redirect to merchant with http post needs to be enabled
#[schema(default = false, example = true)]
pub redirect_to_merchant_with_http_post: bool,
/// Webhook related details
pub webhook_details: Option<WebhookDetails>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// The routing algorithm to be used for routing payments to desired connectors
#[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "stripe"}))]
pub routing_algorithm: Option<serde_json::Value>,
/// Will be used to determine the time till which your payment will be active once the payment session starts
#[schema(example = 900)]
pub intent_fulfillment_time: Option<i64>,
/// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom'
#[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))]
pub frm_routing_algorithm: Option<serde_json::Value>,
/// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom'
#[cfg(feature = "payouts")]
#[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))]
pub payout_routing_algorithm: Option<serde_json::Value>,
/// Verified Apple Pay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
/// Client Secret Default expiry for all payments created under this profile
#[schema(example = 900)]
pub session_expiry: Option<i64>,
/// Default Payment Link config for all payment links created under this profile
#[schema(value_type = Option<BusinessPaymentLinkConfig>)]
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
/// External 3DS authentication details
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
/// Merchant's config to support extended card info feature
pub extended_card_info_config: Option<ExtendedCardInfoConfig>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_shipping_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_billing_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
/// Indicates if the MIT (merchant initiated transaction) payments can be made connector
/// agnostic, i.e., MITs may be processed through different connector than CIT (customer
/// initiated transaction) based on the routing rules.
/// If set to `false`, MIT will go through the same connector as the CIT.
pub is_connector_agnostic_mit_enabled: Option<bool>,
/// Default payout link config
#[schema(value_type = Option<BusinessPayoutLinkConfig>)]
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
/// These key-value pairs are sent as additional custom headers in the outgoing webhook request.
#[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)]
pub outgoing_webhook_custom_http_headers: Option<MaskedHeaders>,
/// Merchant Connector id to be stored for tax_calculator connector
#[schema(value_type = Option<String>)]
pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>,
/// Indicates if tax_calculator connector is enabled or not.
/// If set to `true` tax_connector_id will be checked.
pub is_tax_connector_enabled: bool,
/// Indicates if network tokenization is enabled or not.
#[schema(default = false, example = false)]
pub is_network_tokenization_enabled: bool,
/// Indicates if is_auto_retries_enabled is enabled or not.
#[schema(default = false, example = false)]
pub is_auto_retries_enabled: bool,
/// Maximum number of auto retries allowed for a payment
pub max_auto_retries_enabled: Option<i16>,
/// Bool indicating if extended authentication must be requested for all payments
#[schema(value_type = Option<bool>)]
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
/// Indicates if click to pay is enabled or not.
#[schema(default = false, example = false)]
pub is_click_to_pay_enabled: bool,
/// Product authentication ids
#[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)]
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
/// Card Testing Guard Configs
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
///Indicates if clear pan retries is enabled or not.
pub is_clear_pan_retries_enabled: bool,
/// Indicates if 3ds challenge is forced
pub force_3ds_challenge: bool,
/// Indicates if debit routing is enabled or not
#[schema(value_type = Option<bool>)]
pub is_debit_routing_enabled: Option<bool>,
//Merchant country for the profile
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
/// Indicates if pre network tokenization is enabled or not
#[schema(default = false, example = false)]
pub is_pre_network_tokenization_enabled: bool,
/// Acquirer configs
#[schema(value_type = Option<Vec<ProfileAcquirerResponse>>)]
pub acquirer_configs: Option<Vec<ProfileAcquirerResponse>>,
/// Indicates if the redirection has to open in the iframe
#[schema(example = false)]
pub is_iframe_redirection_enabled: Option<bool>,
/// Four-digit code assigned based on business type to determine processing fees and risk level
#[schema(value_type = Option<MerchantCategoryCode>, example = "5411")]
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
/// Merchant country code.
/// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates.
/// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks.
/// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior.
#[schema(value_type = Option<MerchantCountryCode>, example = "840")]
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
#[schema(value_type = Option<u32>, example = 2)]
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
/// Indicates if manual retry for payment is enabled or not
pub is_manual_retry_enabled: Option<bool>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, ToSchema, Serialize)]
pub struct ProfileResponse {
/// The identifier for Merchant Account
#[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)]
pub merchant_id: id_type::MerchantId,
/// The identifier for profile. This must be used for creating merchant accounts, payments and payouts
#[schema(max_length = 64, value_type = String, example = "pro_abcdefghijklmnopqrstuvwxyz")]
pub id: id_type::ProfileId,
/// Name of the profile
#[schema(max_length = 64)]
pub profile_name: String,
/// The URL to redirect after the completion of the operation
#[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")]
pub return_url: Option<common_utils::types::Url>,
/// A boolean value to indicate if payment response hash needs to be enabled
#[schema(default = true, example = true)]
pub enable_payment_response_hash: bool,
/// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated.
pub payment_response_hash_key: Option<String>,
/// A boolean value to indicate if redirect to merchant with http post needs to be enabled
#[schema(default = false, example = true)]
pub redirect_to_merchant_with_http_post: bool,
/// Webhook related details
pub webhook_details: Option<WebhookDetails>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// Verified Apple Pay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
/// Client Secret Default expiry for all payments created under this profile
#[schema(example = 900)]
pub session_expiry: Option<i64>,
/// Default Payment Link config for all payment links created under this profile
#[schema(value_type = Option<BusinessPaymentLinkConfig>)]
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
/// External 3DS authentication details
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
/// Merchant's config to support extended card info feature
pub extended_card_info_config: Option<ExtendedCardInfoConfig>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_billing_details_from_wallet_connector_if_required: Option<bool>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
/// Indicates if the MIT (merchant initiated transaction) payments can be made connector
/// agnostic, i.e., MITs may be processed through different connector than CIT (customer
/// initiated transaction) based on the routing rules.
/// If set to `false`, MIT will go through the same connector as the CIT.
pub is_connector_agnostic_mit_enabled: Option<bool>,
/// Default payout link config
#[schema(value_type = Option<BusinessPayoutLinkConfig>)]
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
/// These key-value pairs are sent as additional custom headers in the outgoing webhook request.
#[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)]
pub outgoing_webhook_custom_http_headers: Option<MaskedHeaders>,
/// Will be used to determine the time till which your payment will be active once the payment session starts
#[schema(value_type = Option<u32>, example = 900)]
pub order_fulfillment_time: Option<OrderFulfillmentTime>,
/// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment
#[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")]
pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>,
/// Merchant Connector id to be stored for tax_calculator connector
#[schema(value_type = Option<String>)]
pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>,
/// Indicates if tax_calculator connector is enabled or not.
/// If set to `true` tax_connector_id will be checked.
pub is_tax_connector_enabled: bool,
/// Indicates if network tokenization is enabled or not.
#[schema(default = false, example = false)]
pub is_network_tokenization_enabled: bool,
/// Indicates if CVV should be collected during payment or not.
#[schema(value_type = Option<bool>)]
pub should_collect_cvv_during_payment:
Option<primitive_wrappers::ShouldCollectCvvDuringPayment>,
/// Indicates if click to pay is enabled or not.
#[schema(default = false, example = false)]
pub is_click_to_pay_enabled: bool,
/// Product authentication ids
#[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)]
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
/// Card Testing Guard Configs
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
///Indicates if clear pan retries is enabled or not.
pub is_clear_pan_retries_enabled: bool,
/// Indicates if debit routing is enabled or not
#[schema(value_type = Option<bool>)]
pub is_debit_routing_enabled: Option<bool>,
//Merchant country for the profile
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
/// Indicates if the redirection has to open in the iframe
#[schema(example = false)]
pub is_iframe_redirection_enabled: Option<bool>,
/// Indicates if external vault is enabled or not.
pub is_external_vault_enabled: Option<bool>,
/// External Vault Connector Details
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
/// Four-digit code assigned based on business type to determine processing fees and risk level
#[schema(value_type = Option<MerchantCategoryCode>, example = "5411")]
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
/// Merchant country code.
/// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates.
/// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks.
/// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior.
#[schema(value_type = Option<MerchantCountryCode>, example = "840")]
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
/// Enable split payments, i.e., split the amount between multiple payment methods
#[schema(value_type = SplitTxnsEnabled, default = "skip")]
pub split_txns_enabled: common_enums::SplitTxnsEnabled,
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ProfileUpdate {
/// The name of profile
#[schema(max_length = 64)]
pub profile_name: Option<String>,
/// The URL to redirect after the completion of the operation
#[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")]
pub return_url: Option<url::Url>,
/// A boolean value to indicate if payment response hash needs to be enabled
#[schema(default = true, example = true)]
pub enable_payment_response_hash: Option<bool>,
/// Refers to the hash key used for calculating the signature for webhooks and redirect response.
pub payment_response_hash_key: Option<String>,
/// A boolean value to indicate if redirect to merchant with http post needs to be enabled
#[schema(default = false, example = true)]
pub redirect_to_merchant_with_http_post: Option<bool>,
/// Webhook related details
pub webhook_details: Option<WebhookDetails>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// The routing algorithm to be used for routing payments to desired connectors
#[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "stripe"}))]
pub routing_algorithm: Option<serde_json::Value>,
/// Will be used to determine the time till which your payment will be active once the payment session starts
#[schema(example = 900)]
pub intent_fulfillment_time: Option<u32>,
/// The frm routing algorithm to be used for routing payments to desired FRM's
#[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))]
pub frm_routing_algorithm: Option<serde_json::Value>,
/// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom'
#[cfg(feature = "payouts")]
#[schema(value_type = Option<StaticRoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))]
pub payout_routing_algorithm: Option<serde_json::Value>,
/// Verified Apple Pay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
/// Client Secret Default expiry for all payments created under this profile
#[schema(example = 900)]
pub session_expiry: Option<u32>,
/// Default Payment Link config for all payment links created under this profile
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
/// External 3DS authentication details
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
/// Merchant's config to support extended card info feature
pub extended_card_info_config: Option<ExtendedCardInfoConfig>,
// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_shipping_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_billing_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
/// Bool indicating if extended authentication must be requested for all payments
#[schema(value_type = Option<bool>)]
pub always_request_extended_authorization:
Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>,
/// Indicates if the MIT (merchant initiated transaction) payments can be made connector
/// agnostic, i.e., MITs may be processed through different connector than CIT (customer
/// initiated transaction) based on the routing rules.
/// If set to `false`, MIT will go through the same connector as the CIT.
pub is_connector_agnostic_mit_enabled: Option<bool>,
/// Default payout link config
#[schema(value_type = Option<BusinessPayoutLinkConfig>)]
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
/// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs.
#[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)]
pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>,
/// Merchant Connector id to be stored for tax_calculator connector
#[schema(value_type = Option<String>)]
pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>,
/// Indicates if tax_calculator connector is enabled or not.
/// If set to `true` tax_connector_id will be checked.
pub is_tax_connector_enabled: Option<bool>,
/// Indicates if dynamic routing is enabled or not.
#[serde(default)]
pub dynamic_routing_algorithm: Option<serde_json::Value>,
/// Indicates if network tokenization is enabled or not.
pub is_network_tokenization_enabled: Option<bool>,
/// Indicates if is_auto_retries_enabled is enabled or not.
pub is_auto_retries_enabled: Option<bool>,
/// Maximum number of auto retries allowed for a payment
pub max_auto_retries_enabled: Option<u8>,
/// Indicates if click to pay is enabled or not.
#[schema(default = false, example = false)]
pub is_click_to_pay_enabled: Option<bool>,
/// Product authentication ids
#[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)]
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
/// Card Testing Guard Configs
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
///Indicates if clear pan retries is enabled or not.
pub is_clear_pan_retries_enabled: Option<bool>,
/// Indicates if 3ds challenge is forced
pub force_3ds_challenge: Option<bool>,
/// Indicates if debit routing is enabled or not
#[schema(value_type = Option<bool>)]
pub is_debit_routing_enabled: Option<bool>,
//Merchant country for the profile
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
/// Indicates if the redirection has to open in the iframe
#[schema(example = false)]
pub is_iframe_redirection_enabled: Option<bool>,
/// Indicates if pre network tokenization is enabled or not
#[schema(default = false, example = false)]
pub is_pre_network_tokenization_enabled: Option<bool>,
/// Four-digit code assigned based on business type to determine processing fees and risk level
#[schema(value_type = Option<MerchantCategoryCode>, example = "5411")]
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
/// Merchant country code.
/// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates.
/// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks.
/// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior.
#[schema(value_type = Option<MerchantCountryCode>, example = "840")]
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
#[schema(value_type = Option<u32>, example = 2)]
pub dispute_polling_interval: Option<primitive_wrappers::DisputePollingIntervalInHours>,
/// Indicates if manual retry for payment is enabled or not
pub is_manual_retry_enabled: Option<bool>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, Deserialize, ToSchema, Serialize)]
#[serde(deny_unknown_fields)]
pub struct ProfileUpdate {
/// The name of profile
#[schema(max_length = 64)]
pub profile_name: Option<String>,
/// The URL to redirect after the completion of the operation
#[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")]
pub return_url: Option<common_utils::types::Url>,
/// A boolean value to indicate if payment response hash needs to be enabled
#[schema(default = true, example = true)]
pub enable_payment_response_hash: Option<bool>,
/// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated.
pub payment_response_hash_key: Option<String>,
/// A boolean value to indicate if redirect to merchant with http post needs to be enabled
#[schema(default = false, example = true)]
pub redirect_to_merchant_with_http_post: Option<bool>,
/// Webhook related details
pub webhook_details: Option<WebhookDetails>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// Will be used to determine the time till which your payment will be active once the payment session starts
#[schema(value_type = Option<u32>, example = 900)]
pub order_fulfillment_time: Option<OrderFulfillmentTime>,
/// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment
#[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")]
pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>,
/// Verified Apple Pay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
/// Client Secret Default expiry for all payments created under this profile
#[schema(example = 900)]
pub session_expiry: Option<u32>,
/// Default Payment Link config for all payment links created under this profile
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
/// External 3DS authentication details
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
/// Merchant's config to support extended card info feature
pub extended_card_info_config: Option<ExtendedCardInfoConfig>,
// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_billing_details_from_wallet_connector_if_required: Option<bool>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
/// Indicates if the MIT (merchant initiated transaction) payments can be made connector
/// agnostic, i.e., MITs may be processed through different connector than CIT (customer
/// initiated transaction) based on the routing rules.
/// If set to `false`, MIT will go through the same connector as the CIT.
pub is_connector_agnostic_mit_enabled: Option<bool>,
/// Default payout link config
#[schema(value_type = Option<BusinessPayoutLinkConfig>)]
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
/// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs.
#[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)]
pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>,
/// Merchant Connector id to be stored for tax_calculator connector
#[schema(value_type = Option<String>)]
pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>,
/// Indicates if tax_calculator connector is enabled or not.
/// If set to `true` tax_connector_id will be checked.
pub is_tax_connector_enabled: Option<bool>,
/// Indicates if network tokenization is enabled or not.
pub is_network_tokenization_enabled: Option<bool>,
/// Indicates if click to pay is enabled or not.
#[schema(default = false, example = false)]
pub is_click_to_pay_enabled: Option<bool>,
/// Product authentication ids
#[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)]
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
/// Card Testing Guard Configs
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
///Indicates if clear pan retries is enabled or not.
pub is_clear_pan_retries_enabled: Option<bool>,
/// Indicates if debit routing is enabled or not
#[schema(value_type = Option<bool>)]
pub is_debit_routing_enabled: Option<bool>,
//Merchant country for the profile
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
/// Indicates if external vault is enabled or not.
pub is_external_vault_enabled: Option<bool>,
/// External Vault Connector Details
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
/// Four-digit code assigned based on business type to determine processing fees and risk level
#[schema(value_type = Option<MerchantCategoryCode>, example = "5411")]
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
/// Merchant country code.
/// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates.
/// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks.
/// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior.
#[schema(value_type = Option<MerchantCountryCode>, example = "840")]
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
/// Indicates the state of revenue recovery algorithm type
#[schema(value_type = Option<RevenueRecoveryAlgorithmType>, example = "cascading")]
pub revenue_recovery_retry_algorithm_type:
Option<common_enums::enums::RevenueRecoveryAlgorithmType>,
/// Enable split payments, i.e., split the amount between multiple payment methods
#[schema(value_type = Option<SplitTxnsEnabled>, default = "skip")]
pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct BusinessCollectLinkConfig {
#[serde(flatten)]
pub config: BusinessGenericLinkConfig,
/// List of payment methods shown on collect UI
#[schema(value_type = Vec<EnabledPaymentMethod>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs", "sepa"]}]"#)]
pub enabled_payment_methods: Vec<link_utils::EnabledPaymentMethod>,
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct BusinessPayoutLinkConfig {
#[serde(flatten)]
pub config: BusinessGenericLinkConfig,
/// Form layout of the payout link
#[schema(value_type = Option<UIWidgetFormLayout>, max_length = 255, example = "tabs")]
pub form_layout: Option<api_enums::UIWidgetFormLayout>,
/// Allows for removing any validations / pre-requisites which are necessary in a production environment
#[schema(value_type = Option<bool>, default = false)]
pub payout_test_mode: Option<bool>,
}
#[derive(Clone, Debug, serde::Serialize)]
pub struct MaskedHeaders(HashMap<String, String>);
impl MaskedHeaders {
fn mask_value(value: &str) -> String {
let value_len = value.len();
let masked_value = if value_len <= 4 {
"*".repeat(value_len)
} else {
value
.char_indices()
.map(|(index, ch)| {
if index < 2 || index >= value_len - 2 {
// Show the first two and last two characters, mask the rest with '*'
ch
} else {
// Mask the remaining characters
'*'
}
})
.collect::<String>()
};
masked_value
}
pub fn from_headers(headers: HashMap<String, Secret<String>>) -> Self {
let masked_headers = headers
.into_iter()
.map(|(key, value)| (key, Self::mask_value(value.peek())))
.collect();
Self(masked_headers)
}
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)]
pub struct BusinessGenericLinkConfig {
/// Custom domain name to be used for hosting the link
pub domain_name: Option<String>,
/// A list of allowed domains (glob patterns) where this link can be embedded / opened from
pub allowed_domains: HashSet<String>,
#[serde(flatten)]
#[schema(value_type = GenericLinkUiConfig)]
pub ui_config: link_utils::GenericLinkUiConfig,
}
impl BusinessGenericLinkConfig {
pub fn validate(&self) -> Result<(), &str> {
// Validate host domain name
let host_domain_valid = self
.domain_name
.clone()
.map(|host_domain| link_utils::validate_strict_domain(&host_domain))
.unwrap_or(true);
if !host_domain_valid {
return Err("Invalid host domain name received in payout_link_config");
}
let are_allowed_domains_valid = self
.allowed_domains
.clone()
.iter()
.all(|allowed_domain| link_utils::validate_wildcard_domain(allowed_domain));
if !are_allowed_domains_valid {
return Err("Invalid allowed domain names received in payout_link_config");
}
Ok(())
}
}
#[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)]
pub struct BusinessPaymentLinkConfig {
/// Custom domain name to be used for hosting the link in your own domain
pub domain_name: Option<String>,
/// Default payment link config for all future payment link
|
crates/api_models/src/admin.rs#chunk3
|
api_models
|
chunk
| 8,187
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl NoonOrderNvp {
pub fn new(metadata: &serde_json::Value) -> Self {
let metadata_as_string = metadata.to_string();
let hash_map: std::collections::BTreeMap<String, serde_json::Value> =
serde_json::from_str(&metadata_as_string).unwrap_or(std::collections::BTreeMap::new());
let inner = hash_map
.into_iter()
.enumerate()
.map(|(index, (hs_key, hs_value))| {
let noon_key = format!("{}", index + 1);
// to_string() function on serde_json::Value returns a string with "" quotes. Noon doesn't allow this. Hence get_value_as_string function
let noon_value = format!("{hs_key}={}", get_value_as_string(&hs_value));
(noon_key, Secret::new(noon_value))
})
.collect();
Self { inner }
}
}
|
crates/hyperswitch_connectors/src/connectors/noon/transformers.rs
|
hyperswitch_connectors
|
impl_block
| 195
|
rust
| null |
NoonOrderNvp
| null |
impl NoonOrderNvp
| null | null | null | null | null | null | null | null |
pub struct AdjustedBy {
id: i32,
#[serde(rename = "type")]
adjusted_by_type: String,
approval: i32,
message: String,
amount: FloatMajorUnit,
created: String,
url: String,
}
|
crates/hyperswitch_connectors/src/connectors/bambora/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 57
|
rust
|
AdjustedBy
| null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentCapture for Novalnet {}
|
crates/hyperswitch_connectors/src/connectors/novalnet.rs
|
hyperswitch_connectors
|
impl_block
| 10
|
rust
| null |
Novalnet
|
api::PaymentCapture for
|
impl api::PaymentCapture for for Novalnet
| null | null | null | null | null | null | null | null |
pub fn get_surcharge_details(&self, surcharge_key: SurchargeKey) -> Option<&SurchargeDetails> {
self.surcharge_results.get(&surcharge_key)
}
|
crates/router/src/core/payments/types.rs
|
router
|
function_signature
| 39
|
rust
| null | null | null | null |
get_surcharge_details
| null | null | null | null | null | null | null |
impl ConnectorCommon for Payone {
fn id(&self) -> &'static str {
"payone"
}
fn get_currency_unit(&self) -> CurrencyUnit {
CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/json"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.payone.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, Maskable<String>)>, ConnectorError> {
let auth = payone::PayoneAuthType::try_from(auth_type)
.change_context(ConnectorError::FailedToObtainAuthType)?;
Ok(vec![(
AUTHORIZATION.to_string(),
auth.api_key.expose().into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, ConnectorError> {
let response: payone::ErrorResponse = res
.response
.parse_struct("ErrorResponse")
.change_context(ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
let errors_list = response.errors.clone().unwrap_or_default();
let option_error_code_message = get_error_code_error_message_based_on_priority(
self.clone(),
errors_list
.into_iter()
.map(|errors| errors.into())
.collect(),
);
match response.errors {
Some(errors) => Ok(ErrorResponse {
status_code: res.status_code,
code: option_error_code_message
.clone()
.map(|error_code_message| error_code_message.error_code)
.unwrap_or(NO_ERROR_CODE.to_string()),
message: option_error_code_message
.clone()
.map(|error_code_message| error_code_message.error_code)
.unwrap_or(NO_ERROR_CODE.to_string()),
reason: Some(
errors
.iter()
.map(|error| format!("{} : {}", error.code, error.message))
.collect::<Vec<String>>()
.join(", "),
),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
None => Ok(ErrorResponse {
status_code: res.status_code,
code: NO_ERROR_CODE.to_string(),
message: NO_ERROR_MESSAGE.to_string(),
reason: None,
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
}),
}
}
}
|
crates/hyperswitch_connectors/src/connectors/payone.rs
|
hyperswitch_connectors
|
impl_block
| 619
|
rust
| null |
Payone
|
ConnectorCommon for
|
impl ConnectorCommon for for Payone
| null | null | null | null | null | null | null | null |
pub struct SamsungPayPaymentInformation {
fluid_data: FluidData,
tokenized_card: SamsungPayTokenizedCard,
}
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 26
|
rust
|
SamsungPayPaymentInformation
| null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.PaymentsCreateRequest
{
"type": "object",
"required": [
"amount",
"currency"
],
"properties": {
"amount": {
"type": "integer",
"format": "int64",
"description": "The primary amount for the payment, provided in the lowest denomination of the specified currency (e.g., 6540 for $65.40 USD). This field is mandatory for creating a payment.",
"minimum": 0
},
"order_tax_amount": {
"type": "integer",
"format": "int64",
"description": "Total tax amount applicable to the order, in the lowest denomination of the currency.",
"example": 6540,
"nullable": true
},
"currency": {
"$ref": "#/components/schemas/Currency"
},
"amount_to_capture": {
"type": "integer",
"format": "int64",
"description": "The amount to be captured from the user's payment method, in the lowest denomination. If not provided, and `capture_method` is `automatic`, the full payment `amount` will be captured. If `capture_method` is `manual`, this can be specified in the `/capture` call. Must be less than or equal to the authorized amount.",
"example": 6540,
"nullable": true
},
"shipping_cost": {
"type": "integer",
"format": "int64",
"description": "The shipping cost for the payment. This is required for tax calculation in some regions.",
"example": 6540,
"nullable": true
},
"payment_id": {
"type": "string",
"description": "Optional. A merchant-provided unique identifier for the payment, contains 30 characters long (e.g., \"pay_mbabizu24mvu3mela5njyhpit4\"). If provided, it ensures idempotency for the payment creation request. If omitted, Hyperswitch generates a unique ID for the payment.",
"example": "pay_mbabizu24mvu3mela5njyhpit4",
"nullable": true,
"maxLength": 30,
"minLength": 30
},
"routing": {
"allOf": [
{
"$ref": "#/components/schemas/StraightThroughAlgorithm"
}
],
"nullable": true
},
"connector": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Connector"
},
"description": "This allows to manually select a connector with which the payment can go through.",
"example": [
"stripe",
"adyen"
],
"nullable": true
},
"capture_method": {
"allOf": [
{
"$ref": "#/components/schemas/CaptureMethod"
}
],
"nullable": true
},
"authentication_type": {
"allOf": [
{
"$ref": "#/components/schemas/AuthenticationType"
}
],
"default": "three_ds",
"nullable": true
},
"billing": {
"allOf": [
{
"$ref": "#/components/schemas/Address"
}
],
"nullable": true
},
"confirm": {
"type": "boolean",
"description": "If set to `true`, Hyperswitch attempts to confirm and authorize the payment immediately after creation, provided sufficient payment method details are included. If `false` or omitted (default is `false`), the payment is created with a status such as `requires_payment_method` or `requires_confirmation`, and a separate `POST /payments/{payment_id}/confirm` call is necessary to proceed with authorization.",
"default": false,
"example": true,
"nullable": true
},
"customer": {
"allOf": [
{
"$ref": "#/components/schemas/CustomerDetails"
}
],
"nullable": true
},
"customer_id": {
"type": "string",
"description": "The identifier for the customer",
"example": "cus_y3oqhf46pyzuxjbcn2giaqnb44",
"nullable": true,
"maxLength": 64,
"minLength": 1
},
"off_session": {
"type": "boolean",
"description": "Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory",
"example": true,
"nullable": true
},
"description": {
"type": "string",
"description": "An arbitrary string attached to the payment. Often useful for displaying to users or for your own internal record-keeping.",
"example": "It's my first payment request",
"nullable": true
},
"return_url": {
"type": "string",
"description": "The URL to redirect the customer to after they complete the payment process or authentication. This is crucial for flows that involve off-site redirection (e.g., 3DS, some bank redirects, wallet payments).",
"example": "https://hyperswitch.io",
"nullable": true,
"maxLength": 2048
},
"setup_future_usage": {
"allOf": [
{
"$ref": "#/components/schemas/FutureUsage"
}
],
"nullable": true
},
"payment_method_data": {
"allOf": [
{
"$ref": "#/components/schemas/PaymentMethodDataRequest"
}
],
"nullable": true
},
"payment_method": {
"allOf": [
{
"$ref": "#/components/schemas/PaymentMethod"
}
],
"nullable": true
},
"payment_token": {
"type": "string",
"description": "As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner.",
"example": "187282ab-40ef-47a9-9206-5099ba31e432",
"nullable": true
},
"shipping": {
"allOf": [
{
"$ref": "#/components/schemas/Address"
}
],
"nullable": true
},
"statement_descriptor_name": {
"type": "string",
"description": "For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.",
"example": "Hyperswitch Router",
"nullable": true,
"maxLength": 255
},
"statement_descriptor_suffix": {
"type": "string",
"description": "Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.",
"example": "Payment for shoes purchase",
"nullable": true,
"maxLength": 255
},
"order_details": {
"type": "array",
"items": {
"$ref": "#/components/schemas/OrderDetailsWithAmount"
},
"description": "Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount",
"example": "[{\n \"product_name\": \"Apple iPhone 16\",\n \"quantity\": 1,\n \"amount\" : 69000\n \"product_img_link\" : \"https://dummy-img-link.com\"\n }]",
"nullable": true
},
"mandate_data": {
"allOf": [
{
"$ref": "#/components/schemas/MandateData"
}
],
"nullable": true
},
"customer_acceptance": {
"allOf": [
{
"$ref": "#/components/schemas/CustomerAcceptance"
}
],
"nullable": true
},
"mandate_id": {
"type": "string",
"description": "A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data",
"example": "mandate_iwer89rnjef349dni3",
"nullable": true,
"maxLength": 64
},
"browser_info": {
"allOf": [
{
"$ref": "#/components/schemas/BrowserInformation"
}
],
"nullable": true
},
"payment_experience": {
"allOf": [
{
"$ref": "#/components/schemas/PaymentExperience"
}
],
"nullable": true
},
"payment_method_type": {
"allOf": [
{
"$ref": "#/components/schemas/PaymentMethodType"
}
],
"nullable": true
},
"business_country": {
"allOf": [
{
"$ref": "#/components/schemas/CountryAlpha2"
}
],
"nullable": true
},
"business_label": {
"type": "string",
"description": "Business label of the merchant for this payment.\nTo be deprecated soon. Pass the profile_id instead",
"example": "food",
"nullable": true
},
"merchant_connector_details": {
"allOf": [
{
"$ref": "#/components/schemas/MerchantConnectorDetailsWrap"
}
],
"nullable": true
},
"allowed_payment_method_types": {
"type": "array",
"items": {
"$ref": "#/components/schemas/PaymentMethodType"
},
"description": "Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent",
"nullable": true
},
"metadata": {
"type": "object",
"description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.",
"nullable": true
},
"connector_metadata": {
"allOf": [
{
"$ref": "#/components/schemas/ConnectorMetadata"
}
],
"nullable": true
},
"payment_link": {
"type": "boolean",
"description": "Whether to generate the payment link for this payment or not (if applicable)",
"default": false,
"example": true,
"nullable": true
},
"payment_link_config": {
"allOf": [
{
"$ref": "#/components/schemas/PaymentCreatePaymentLinkConfig"
}
],
"nullable": true
},
"payment_link_config_id": {
"type": "string",
"description": "Custom payment link config id set at business profile, send only if business_specific_configs is configured",
"nullable": true
},
"profile_id": {
"type": "string",
"description": "The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up.",
"nullable": true
},
"surcharge_details": {
"allOf": [
{
"$ref": "#/components/schemas/RequestSurchargeDetails"
}
],
"nullable": true
},
"payment_type": {
"allOf": [
{
"$ref": "#/components/schemas/PaymentType"
}
],
"nullable": true
},
"request_incremental_authorization": {
"type": "boolean",
"description": "Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it.",
"nullable": true
},
"session_expiry": {
"type": "integer",
"format": "int32",
"description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins",
"example": 900,
"nullable": true,
"minimum": 0
},
"frm_metadata": {
"type": "object",
"description": "Additional data related to some frm(Fraud Risk Management) connectors",
"nullable": true
},
"request_external_three_ds_authentication": {
"type": "boolean",
"description": "Whether to perform external authentication (if applicable)",
"example": true,
"nullable": true
},
"recurring_details": {
"allOf": [
{
"$ref": "#/components/schemas/RecurringDetails"
}
],
"nullable": true
},
"split_payments": {
"allOf": [
{
"$ref": "#/components/schemas/SplitPaymentsRequest"
}
],
"nullable": true
},
"request_extended_authorization": {
"type": "boolean",
"description": "Optional boolean value to extent authorization period of this payment\n\ncapture method must be manual or manual_multiple",
"default": false,
"nullable": true
},
"merchant_order_reference_id": {
"type": "string",
"description": "Your unique identifier for this payment or order. This ID helps you reconcile payments on your system. If provided, it is passed to the connector if supported.",
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
},
"skip_external_tax_calculation": {
"type": "boolean",
"description": "Whether to calculate tax for this payment intent",
"nullable": true
},
"psd2_sca_exemption_type": {
"allOf": [
{
"$ref": "#/components/schemas/ScaExemptionType"
}
],
"nullable": true
},
"ctp_service_details": {
"allOf": [
{
"$ref": "#/components/schemas/CtpServiceDetails"
}
],
"nullable": true
},
"force_3ds_challenge": {
"type": "boolean",
"description": "Indicates if 3ds challenge is forced",
"nullable": true
},
"threeds_method_comp_ind": {
"allOf": [
{
"$ref": "#/components/schemas/ThreeDsCompletionIndicator"
}
],
"nullable": true
},
"is_iframe_redirection_enabled": {
"type": "boolean",
"description": "Indicates if the redirection has to open in the iframe",
"nullable": true
},
"all_keys_required": {
"type": "boolean",
"description": "If enabled, provides whole connector response",
"nullable": true
},
"payment_channel": {
"allOf": [
{
"$ref": "#/components/schemas/PaymentChannel"
}
],
"nullable": true
},
"tax_status": {
"allOf": [
{
"$ref": "#/components/schemas/TaxStatus"
}
],
"nullable": true
},
"discount_amount": {
"type": "integer",
"format": "int64",
"description": "Total amount of the discount you have applied to the order or transaction.",
"example": 6540,
"nullable": true
},
"shipping_amount_tax": {
"allOf": [
{
"$ref": "#/components/schemas/MinorUnit"
}
],
"nullable": true
},
"duty_amount": {
"allOf": [
{
"$ref": "#/components/schemas/MinorUnit"
}
],
"nullable": true
},
"order_date": {
"type": "string",
"format": "date-time",
"description": "Date the payer placed the order.",
"nullable": true
},
"enable_partial_authorization": {
"type": "boolean",
"description": "Allow partial authorization for this payment",
"nullable": true
}
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 3,709
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"PaymentsCreateRequest"
] | null | null | null | null |
impl ApiEventMetric for FrmFiltersResponse {}
|
crates/api_models/src/analytics.rs
|
api_models
|
impl_block
| 9
|
rust
| null |
FrmFiltersResponse
|
ApiEventMetric for
|
impl ApiEventMetric for for FrmFiltersResponse
| null | null | null | null | null | null | null | null |
impl api::RefundSync for Iatapay {}
|
crates/hyperswitch_connectors/src/connectors/iatapay.rs
|
hyperswitch_connectors
|
impl_block
| 12
|
rust
| null |
Iatapay
|
api::RefundSync for
|
impl api::RefundSync for for Iatapay
| null | null | null | null | null | null | null | null |
File: crates/hyperswitch_domain_models/src/behaviour.rs
use common_utils::{
errors::{CustomResult, ValidationError},
types::keymanager::{Identifier, KeyManagerState},
};
use masking::Secret;
/// Trait for converting domain types to storage models
#[async_trait::async_trait]
pub trait Conversion {
type DstType;
type NewDstType;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError>;
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
key_manager_identifier: Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized;
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError>;
}
#[async_trait::async_trait]
pub trait ReverseConversion<SrcType: Conversion> {
async fn convert(
self,
state: &KeyManagerState,
key: &Secret<Vec<u8>>,
key_manager_identifier: Identifier,
) -> CustomResult<SrcType, ValidationError>;
}
#[async_trait::async_trait]
impl<T: Send, U: Conversion<DstType = T>> ReverseConversion<U> for T {
async fn convert(
self,
state: &KeyManagerState,
key: &Secret<Vec<u8>>,
key_manager_identifier: Identifier,
) -> CustomResult<U, ValidationError> {
U::convert_back(state, self, key, key_manager_identifier).await
}
}
|
crates/hyperswitch_domain_models/src/behaviour.rs
|
hyperswitch_domain_models
|
full_file
| 320
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn refresh_cgraph_cache(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
key: String,
profile_id: &common_utils::id_type::ProfileId,
transaction_type: &api_enums::TransactionType,
) -> RoutingResult<Arc<hyperswitch_constraint_graph::ConstraintGraph<euclid_dir::DirValue>>> {
let mut merchant_connector_accounts = state
.store
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
&state.into(),
&key_store.merchant_id,
false,
key_store,
)
.await
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)?;
match transaction_type {
api_enums::TransactionType::Payment => {
merchant_connector_accounts.retain(|mca| {
mca.connector_type != storage_enums::ConnectorType::PaymentVas
&& mca.connector_type != storage_enums::ConnectorType::PaymentMethodAuth
&& mca.connector_type != storage_enums::ConnectorType::PayoutProcessor
&& mca.connector_type != storage_enums::ConnectorType::AuthenticationProcessor
});
}
#[cfg(feature = "payouts")]
api_enums::TransactionType::Payout => {
merchant_connector_accounts
.retain(|mca| mca.connector_type == storage_enums::ConnectorType::PayoutProcessor);
}
api_enums::TransactionType::ThreeDsAuthentication => {
Err(errors::RoutingError::InvalidTransactionType)?
}
};
let connector_type = match transaction_type {
api_enums::TransactionType::Payment => common_enums::ConnectorType::PaymentProcessor,
#[cfg(feature = "payouts")]
api_enums::TransactionType::Payout => common_enums::ConnectorType::PayoutProcessor,
api_enums::TransactionType::ThreeDsAuthentication => {
Err(errors::RoutingError::InvalidTransactionType)?
}
};
let merchant_connector_accounts = merchant_connector_accounts
.filter_based_on_profile_and_connector_type(profile_id, connector_type);
let api_mcas = merchant_connector_accounts
.into_iter()
.map(admin_api::MerchantConnectorResponse::foreign_try_from)
.collect::<Result<Vec<_>, _>>()
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)?;
let connector_configs = state
.conf
.pm_filters
.0
.clone()
.into_iter()
.filter(|(key, _)| key != "default")
.map(|(key, value)| {
let key = api_enums::RoutableConnectors::from_str(&key)
.map_err(|_| errors::RoutingError::InvalidConnectorName(key))?;
Ok((key, value.foreign_into()))
})
.collect::<Result<HashMap<_, _>, errors::RoutingError>>()?;
let default_configs = state
.conf
.pm_filters
.0
.get("default")
.cloned()
.map(ForeignFrom::foreign_from);
let config_pm_filters = CountryCurrencyFilter {
connector_configs,
default_configs,
};
let cgraph = Arc::new(
mca_graph::make_mca_graph(api_mcas, &config_pm_filters)
.change_context(errors::RoutingError::KgraphCacheRefreshFailed)
.attach_printable("when construction cgraph")?,
);
CGRAPH_CACHE
.push(
CacheKey {
key,
prefix: state.tenant.redis_key_prefix.clone(),
},
Arc::clone(&cgraph),
)
.await;
Ok(cgraph)
}
|
crates/router/src/core/payments/routing.rs
|
router
|
function_signature
| 785
|
rust
| null | null | null | null |
refresh_cgraph_cache
| null | null | null | null | null | null | null |
pub struct DummyConnector;
|
crates/router/src/routes/app.rs
|
router
|
struct_definition
| 5
|
rust
|
DummyConnector
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_domain_models/src/payment_address.rs
Public functions: 7
Public structs: 1
use crate::address::Address;
#[derive(Clone, Default, Debug)]
pub struct PaymentAddress {
shipping: Option<Address>,
billing: Option<Address>,
unified_payment_method_billing: Option<Address>,
payment_method_billing: Option<Address>,
}
impl PaymentAddress {
pub fn new(
shipping: Option<Address>,
billing: Option<Address>,
payment_method_billing: Option<Address>,
should_unify_address: Option<bool>,
) -> Self {
// billing -> .billing, this is the billing details passed in the root of payments request
// payment_method_billing -> .payment_method_data.billing
let unified_payment_method_billing = if should_unify_address.unwrap_or(true) {
// Merge the billing details field from both `payment.billing` and `payment.payment_method_data.billing`
// The unified payment_method_billing will be used as billing address and passed to the connector module
// This unification is required in order to provide backwards compatibility
// so that if `payment.billing` is passed it should be sent to the connector module
// Unify the billing details with `payment_method_data.billing`
payment_method_billing
.as_ref()
.map(|payment_method_billing| {
payment_method_billing
.clone()
.unify_address(billing.as_ref())
})
.or(billing.clone())
} else {
payment_method_billing.clone()
};
Self {
shipping,
billing,
unified_payment_method_billing,
payment_method_billing,
}
}
pub fn get_shipping(&self) -> Option<&Address> {
self.shipping.as_ref()
}
pub fn get_payment_method_billing(&self) -> Option<&Address> {
self.unified_payment_method_billing.as_ref()
}
/// Unify the billing details from `payment_method_data.[payment_method_data].billing details`.
/// Here the fields passed in payment_method_data_billing takes precedence
pub fn unify_with_payment_method_data_billing(
self,
payment_method_data_billing: Option<Address>,
) -> Self {
// Unify the billing details with `payment_method_data.billing_details`
let unified_payment_method_billing = payment_method_data_billing
.map(|payment_method_data_billing| {
payment_method_data_billing.unify_address(self.get_payment_method_billing())
})
.or(self.get_payment_method_billing().cloned());
Self {
shipping: self.shipping,
billing: self.billing,
unified_payment_method_billing,
payment_method_billing: self.payment_method_billing,
}
}
/// Unify the billing details from `payment_method_data.[payment_method_data].billing details`.
/// Here the `self` takes precedence
pub fn unify_with_payment_data_billing(
self,
other_payment_method_billing: Option<Address>,
) -> Self {
let unified_payment_method_billing = self
.get_payment_method_billing()
.map(|payment_method_billing| {
payment_method_billing
.clone()
.unify_address(other_payment_method_billing.as_ref())
})
.or(other_payment_method_billing);
Self {
shipping: self.shipping,
billing: self.billing,
unified_payment_method_billing,
payment_method_billing: self.payment_method_billing,
}
}
pub fn get_request_payment_method_billing(&self) -> Option<&Address> {
self.payment_method_billing.as_ref()
}
pub fn get_payment_billing(&self) -> Option<&Address> {
self.billing.as_ref()
}
}
|
crates/hyperswitch_domain_models/src/payment_address.rs
|
hyperswitch_domain_models
|
full_file
| 761
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl Responder {
let api_auth = auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
};
let (auth_type, _auth_flow) = match auth::get_auth_type_and_flow(req.headers(), api_auth) {
Ok(auth) => auth,
Err(err) => return api::log_and_return_error_response(report!(err)),
};
tracing::Span::current().record("payment_id", json_payload.payment_id.get_string_repr());
let payload = payment_types::PaymentsRetrieveRequest {
resource_id: payment_types::PaymentIdType::PaymentIntentId(json_payload.payment_id.clone()),
merchant_id: json_payload.merchant_id.clone(),
force_sync: json_payload.force_sync.unwrap_or(false),
merchant_connector_details: json_payload.merchant_connector_details.clone(),
..Default::default()
};
let flow = match json_payload.force_sync {
Some(true) => Flow::PaymentsRetrieveForceSync,
_ => Flow::PaymentsRetrieve,
};
tracing::Span::current().record("flow", flow.to_string());
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: auth::AuthenticationData, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::PSync,
payment_types::PaymentsResponse,
_,
_,
_,
payments::PaymentData<api_types::PSync>,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::PaymentStatus,
req,
api::AuthFlow::Merchant,
payments::CallConnectorAction::Trigger,
None,
HeaderPayload::default(),
)
},
&*auth_type,
locking_action,
))
.await
}
|
crates/router/src/routes/payments.rs
|
router
|
impl_block
| 424
|
rust
| null |
Responder
| null |
impl Responder
| null | null | null | null | null | null | null | null |
bank_code: None, // Bank code is not stored in external vault
}),
))
}
payment_methods::PaymentMethodsData::BankDetails(_)
| payment_methods::PaymentMethodsData::WalletDetails(_) => {
Err(errors::ApiErrorResponse::UnprocessableEntity {
message: "External vaulting is not supported for this payment method type"
.to_string(),
}
.into())
}
}
}
#[cfg(feature = "v2")]
/// Update the connector_mandate_details of the payment method with
/// new token details for the payment
fn create_connector_token_details_update(
token_details: payment_methods::ConnectorTokenDetails,
payment_method: &domain::PaymentMethod,
) -> hyperswitch_domain_models::mandates::CommonMandateReference {
let connector_id = token_details.connector_id.clone();
let reference_record =
hyperswitch_domain_models::mandates::ConnectorTokenReferenceRecord::foreign_from(
token_details,
);
let connector_token_details = payment_method.connector_mandate_details.clone();
match connector_token_details {
Some(mut connector_mandate_reference) => {
connector_mandate_reference
.insert_payment_token_reference_record(&connector_id, reference_record);
connector_mandate_reference
}
None => {
let reference_record_hash_map =
std::collections::HashMap::from([(connector_id, reference_record)]);
let payments_mandate_reference =
hyperswitch_domain_models::mandates::PaymentsTokenReference(
reference_record_hash_map,
);
hyperswitch_domain_models::mandates::CommonMandateReference {
payments: Some(payments_mandate_reference),
payouts: None,
}
}
}
}
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
pub async fn create_pm_additional_data_update(
pmd: Option<&domain::PaymentMethodVaultingData>,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
vault_id: Option<String>,
vault_fingerprint_id: Option<String>,
payment_method: &domain::PaymentMethod,
connector_token_details: Option<payment_methods::ConnectorTokenDetails>,
nt_data: Option<NetworkTokenPaymentMethodDetails>,
payment_method_type: Option<common_enums::PaymentMethod>,
payment_method_subtype: Option<common_enums::PaymentMethodType>,
external_vault_source: Option<id_type::MerchantConnectorAccountId>,
) -> RouterResult<storage::PaymentMethodUpdate> {
let encrypted_payment_method_data = pmd
.map(
|payment_method_vaulting_data| match payment_method_vaulting_data {
domain::PaymentMethodVaultingData::Card(card) => {
payment_method_data::PaymentMethodsData::Card(
payment_method_data::CardDetailsPaymentMethod::from(card.clone()),
)
}
domain::PaymentMethodVaultingData::NetworkToken(network_token) => {
payment_method_data::PaymentMethodsData::NetworkToken(
payment_method_data::NetworkTokenDetailsPaymentMethod::from(
network_token.clone(),
),
)
}
},
)
.async_map(|payment_method_details| async {
let key_manager_state = &(state).into();
cards::create_encrypted_data(key_manager_state, key_store, payment_method_details)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to encrypt Payment method data")
})
.await
.transpose()?
.map(From::from);
let connector_mandate_details_update = connector_token_details
.map(|connector_token| {
create_connector_token_details_update(connector_token, payment_method)
})
.map(From::from);
let pm_update = storage::PaymentMethodUpdate::GenericUpdate {
// A new payment method is created with inactive state
// It will be marked active after payment succeeds
status: Some(enums::PaymentMethodStatus::Inactive),
locker_id: vault_id,
payment_method_type_v2: payment_method_type,
payment_method_subtype,
payment_method_data: encrypted_payment_method_data,
network_token_requestor_reference_id: nt_data
.clone()
.map(|data| data.network_token_requestor_reference_id),
network_token_locker_id: nt_data.clone().map(|data| data.network_token_locker_id),
network_token_payment_method_data: nt_data.map(|data| data.network_token_pmd.into()),
connector_mandate_details: connector_mandate_details_update,
locker_fingerprint_id: vault_fingerprint_id,
external_vault_source,
};
Ok(pm_update)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn vault_payment_method_internal(
state: &SessionState,
pmd: &domain::PaymentMethodVaultingData,
merchant_context: &domain::MerchantContext,
existing_vault_id: Option<domain::VaultId>,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<pm_types::AddVaultResponse> {
let db = &*state.store;
// get fingerprint_id from vault
let fingerprint_id_from_vault =
vault::get_fingerprint_id_from_vault(state, pmd, customer_id.get_string_repr().to_owned())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get fingerprint_id from vault")?;
// throw back error if payment method is duplicated
when(
db.find_payment_method_by_fingerprint_id(
&(state.into()),
merchant_context.get_merchant_key_store(),
&fingerprint_id_from_vault,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to find payment method by fingerprint_id")
.inspect_err(|e| logger::error!("Vault Fingerprint_id error: {:?}", e))
.is_ok(),
|| {
Err(report!(errors::ApiErrorResponse::DuplicatePaymentMethod)
.attach_printable("Cannot vault duplicate payment method"))
},
)?;
let mut resp_from_vault = vault::add_payment_method_to_vault(
state,
merchant_context,
pmd,
existing_vault_id,
customer_id,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to add payment method in vault")?;
// add fingerprint_id to the response
resp_from_vault.fingerprint_id = Some(fingerprint_id_from_vault);
Ok(resp_from_vault)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn vault_payment_method_external(
state: &SessionState,
pmd: &domain::PaymentMethodVaultingData,
merchant_account: &domain::MerchantAccount,
merchant_connector_account: domain::MerchantConnectorAccountTypeDetails,
) -> RouterResult<pm_types::AddVaultResponse> {
let router_data = core_utils::construct_vault_router_data(
state,
merchant_account,
&merchant_connector_account,
Some(pmd.clone()),
None,
None,
)
.await?;
let mut old_router_data = VaultConnectorFlowData::to_old_router_data(router_data)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Cannot construct router data for making the external vault insert api call",
)?;
let connector_name = merchant_connector_account
.get_connector_name()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Connector name not present for external vault")?; // always get the connector name from this call
let connector_data = api::ConnectorData::get_external_vault_connector_by_name(
&state.conf.connectors,
&connector_name,
api::GetToken::Connector,
merchant_connector_account.get_mca_id(),
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to get the connector data")?;
let connector_integration: services::BoxedVaultConnectorIntegrationInterface<
ExternalVaultInsertFlow,
types::VaultRequestData,
types::VaultResponseData,
> = connector_data.connector.get_connector_integration();
let router_data_resp = services::execute_connector_processing_step(
state,
connector_integration,
&old_router_data,
payments_core::CallConnectorAction::Trigger,
None,
None,
)
.await
.to_vault_failed_response()?;
get_vault_response_for_insert_payment_method_data(router_data_resp)
}
#[cfg(feature = "v2")]
pub fn get_vault_response_for_insert_payment_method_data<F>(
router_data: VaultRouterData<F>,
) -> RouterResult<pm_types::AddVaultResponse> {
match router_data.response {
Ok(response) => match response {
types::VaultResponseData::ExternalVaultInsertResponse {
connector_vault_id,
fingerprint_id,
} => Ok(pm_types::AddVaultResponse {
vault_id: domain::VaultId::generate(connector_vault_id),
fingerprint_id: Some(fingerprint_id),
entity_id: None,
}),
types::VaultResponseData::ExternalVaultRetrieveResponse { .. }
| types::VaultResponseData::ExternalVaultDeleteResponse { .. }
| types::VaultResponseData::ExternalVaultCreateResponse { .. } => {
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid Vault Response"))
}
},
Err(err) => {
logger::error!("Error vaulting payment method: {:?}", err);
Err(report!(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to vault payment method"))
}
}
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn vault_payment_method(
state: &SessionState,
pmd: &domain::PaymentMethodVaultingData,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
existing_vault_id: Option<domain::VaultId>,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<(
pm_types::AddVaultResponse,
Option<id_type::MerchantConnectorAccountId>,
)> {
let is_external_vault_enabled = profile.is_external_vault_enabled();
match is_external_vault_enabled {
true => {
let external_vault_source: id_type::MerchantConnectorAccountId = profile
.external_vault_connector_details
.clone()
.map(|connector_details| connector_details.vault_connector_id.clone())
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("mca_id not present for external vault")?;
let merchant_connector_account =
domain::MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(Box::new(
payments_core::helpers::get_merchant_connector_account_v2(
state,
merchant_context.get_merchant_key_store(),
Some(&external_vault_source),
)
.await
.attach_printable(
"failed to fetch merchant connector account for external vault insert",
)?,
));
vault_payment_method_external(
state,
pmd,
merchant_context.get_merchant_account(),
merchant_connector_account,
)
.await
.map(|value| (value, Some(external_vault_source)))
}
false => vault_payment_method_internal(
state,
pmd,
merchant_context,
existing_vault_id,
customer_id,
)
.await
.map(|value| (value, None)),
}
}
#[cfg(feature = "v2")]
fn get_pm_list_context(
payment_method_type: enums::PaymentMethod,
payment_method: &domain::PaymentMethod,
is_payment_associated: bool,
) -> Result<Option<PaymentMethodListContext>, error_stack::Report<errors::ApiErrorResponse>> {
let payment_method_data = payment_method
.payment_method_data
.clone()
.map(|payment_method_data| payment_method_data.into_inner());
let payment_method_retrieval_context = match payment_method_data {
Some(payment_methods::PaymentMethodsData::Card(card)) => {
Some(PaymentMethodListContext::Card {
card_details: api::CardDetailFromLocker::from(card),
token_data: is_payment_associated.then_some(
storage::PaymentTokenData::permanent_card(
payment_method.get_id().clone(),
payment_method
.locker_id
.as_ref()
.map(|id| id.get_string_repr().to_owned())
.or_else(|| Some(payment_method.get_id().get_string_repr().to_owned())),
payment_method
.locker_id
.as_ref()
.map(|id| id.get_string_repr().to_owned())
.unwrap_or_else(|| {
payment_method.get_id().get_string_repr().to_owned()
}),
),
),
})
}
Some(payment_methods::PaymentMethodsData::BankDetails(bank_details)) => {
let get_bank_account_token_data =
|| -> CustomResult<payment_methods::BankAccountTokenData,errors::ApiErrorResponse> {
let connector_details = bank_details
.connector_details
.first()
.cloned()
.ok_or(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to obtain bank account connector details")?;
let payment_method_subtype = payment_method
.get_payment_method_subtype()
.get_required_value("payment_method_subtype")
.attach_printable("PaymentMethodType not found")?;
Ok(payment_methods::BankAccountTokenData {
payment_method_type: payment_method_subtype,
payment_method: payment_method_type,
connector_details,
})
};
// Retrieve the pm_auth connector details so that it can be tokenized
let bank_account_token_data = get_bank_account_token_data()
.inspect_err(|error| logger::error!(?error))
.ok();
bank_account_token_data.map(|data| {
let token_data = storage::PaymentTokenData::AuthBankDebit(data);
PaymentMethodListContext::Bank {
token_data: is_payment_associated.then_some(token_data),
}
})
}
Some(payment_methods::PaymentMethodsData::WalletDetails(_)) | None => {
Some(PaymentMethodListContext::TemporaryToken {
token_data: is_payment_associated.then_some(
storage::PaymentTokenData::temporary_generic(generate_id(
consts::ID_LENGTH,
"token",
)),
),
})
}
};
Ok(payment_method_retrieval_context)
}
#[cfg(feature = "v2")]
fn get_pm_list_token_data(
payment_method_type: enums::PaymentMethod,
payment_method: &domain::PaymentMethod,
) -> Result<Option<storage::PaymentTokenData>, error_stack::Report<errors::ApiErrorResponse>> {
let pm_list_context = get_pm_list_context(payment_method_type, payment_method, true)?
.get_required_value("PaymentMethodListContext")?;
match pm_list_context {
PaymentMethodListContext::Card {
card_details: _,
token_data,
} => Ok(token_data),
PaymentMethodListContext::Bank { token_data } => Ok(token_data),
PaymentMethodListContext::BankTransfer {
bank_transfer_details: _,
token_data,
} => Ok(token_data),
PaymentMethodListContext::TemporaryToken { token_data } => Ok(token_data),
}
}
#[cfg(all(feature = "v2", feature = "olap"))]
pub async fn list_payment_methods_core(
state: &SessionState,
merchant_context: &domain::MerchantContext,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<payment_methods::CustomerPaymentMethodsListResponse> {
let db = &*state.store;
let key_manager_state = &(state).into();
let saved_payment_methods = db
.find_payment_method_by_global_customer_id_merchant_id_status(
key_manager_state,
merchant_context.get_merchant_key_store(),
customer_id,
merchant_context.get_merchant_account().get_id(),
common_enums::PaymentMethodStatus::Active,
None,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let customer_payment_methods = saved_payment_methods
.into_iter()
.map(ForeignTryFrom::foreign_try_from)
.collect::<Result<Vec<payment_methods::PaymentMethodResponseItem>, _>>()
.change_context(errors::ApiErrorResponse::InternalServerError)?;
let response = payment_methods::CustomerPaymentMethodsListResponse {
customer_payment_methods,
};
Ok(response)
}
#[cfg(all(feature = "v2", feature = "oltp"))]
pub async fn list_customer_payment_methods_core(
state: &SessionState,
merchant_context: &domain::MerchantContext,
customer_id: &id_type::GlobalCustomerId,
) -> RouterResult<Vec<payment_methods::CustomerPaymentMethodResponseItem>> {
let db = &*state.store;
let key_manager_state = &(state).into();
let saved_payment_methods = db
.find_payment_method_by_global_customer_id_merchant_id_status(
key_manager_state,
merchant_context.get_merchant_key_store(),
customer_id,
merchant_context.get_merchant_account().get_id(),
common_enums::PaymentMethodStatus::Active,
None,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let mut customer_payment_methods = Vec::new();
let payment_method_results: Result<Vec<_>, error_stack::Report<errors::ApiErrorResponse>> =
saved_payment_methods
.into_iter()
.map(|pm| async move {
let parent_payment_method_token = generate_id(consts::ID_LENGTH, "token");
// For payment methods that are active we should always have the payment method type
let payment_method_type = pm
.payment_method_type
.get_required_value("payment_method_type")?;
let intent_fulfillment_time = common_utils::consts::DEFAULT_INTENT_FULFILLMENT_TIME;
let token_data = get_pm_list_token_data(payment_method_type, &pm)?;
if let Some(token_data) = token_data {
pm_routes::ParentPaymentMethodToken::create_key_for_token((
&parent_payment_method_token,
payment_method_type,
))
.insert(intent_fulfillment_time, token_data, state)
.await?;
let final_pm = api::CustomerPaymentMethodResponseItem::foreign_try_from((
pm,
parent_payment_method_token,
))
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert payment method to response format")?;
Ok(Some(final_pm))
} else {
Ok(None)
}
})
.collect::<futures::stream::FuturesUnordered<_>>()
.try_collect::<Vec<_>>()
.await;
customer_payment_methods.extend(payment_method_results?.into_iter().flatten());
Ok(customer_payment_methods)
}
#[cfg(all(feature = "v2", feature = "olap"))]
pub async fn get_total_payment_method_count_core(
state: &SessionState,
merchant_context: &domain::MerchantContext,
) -> RouterResult<api::TotalPaymentMethodCountResponse> {
let db = &*state.store;
let total_count = db
.get_payment_method_count_by_merchant_id_status(
merchant_context.get_merchant_account().get_id(),
common_enums::PaymentMethodStatus::Active,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to get total payment method count")?;
let response = api::TotalPaymentMethodCountResponse { total_count };
Ok(response)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn retrieve_payment_method(
state: SessionState,
pm: api::PaymentMethodId,
merchant_context: domain::MerchantContext,
) -> RouterResponse<api::PaymentMethodResponse> {
let db = state.store.as_ref();
let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm.payment_method_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodId")?;
let payment_method = db
.find_payment_method(
&((&state).into()),
merchant_context.get_merchant_key_store(),
&pm_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let single_use_token_in_cache = get_single_use_token_from_store(
&state.clone(),
payment_method_data::SingleUseTokenKey::store_key(&pm_id.clone()),
)
.await
.unwrap_or_default();
transformers::generate_payment_method_response(&payment_method, &single_use_token_in_cache)
.map(services::ApplicationResponse::Json)
}
// TODO: When we separate out microservices, this function will be an endpoint in payment_methods
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn update_payment_method_status_internal(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
storage_scheme: enums::MerchantStorageScheme,
status: enums::PaymentMethodStatus,
payment_method_id: &id_type::GlobalPaymentMethodId,
) -> RouterResult<domain::PaymentMethod> {
let db = &*state.store;
let key_manager_state = &state.into();
let payment_method = db
.find_payment_method(
&((state).into()),
key_store,
payment_method_id,
storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(status),
};
let updated_pm = db
.update_payment_method(
key_manager_state,
key_store,
payment_method.clone(),
pm_update,
storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
Ok(updated_pm)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn update_payment_method(
state: SessionState,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
req: api::PaymentMethodUpdate,
payment_method_id: &id_type::GlobalPaymentMethodId,
) -> RouterResponse<api::PaymentMethodResponse> {
let response =
update_payment_method_core(&state, &merchant_context, &profile, req, payment_method_id)
.await?;
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn update_payment_method_core(
state: &SessionState,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
request: api::PaymentMethodUpdate,
payment_method_id: &id_type::GlobalPaymentMethodId,
) -> RouterResult<api::PaymentMethodResponse> {
let db = state.store.as_ref();
let payment_method = db
.find_payment_method(
&((state).into()),
merchant_context.get_merchant_key_store(),
payment_method_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
let current_vault_id = payment_method.locker_id.clone();
when(
payment_method.status == enums::PaymentMethodStatus::AwaitingData,
|| {
Err(errors::ApiErrorResponse::InvalidRequestData {
message: "This Payment method is awaiting data and hence cannot be updated"
.to_string(),
})
},
)?;
let pmd: domain::PaymentMethodVaultingData = vault::retrieve_payment_method_from_vault(
state,
merchant_context,
profile,
&payment_method,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to retrieve payment method from vault")?
.data;
let vault_request_data = request.payment_method_data.map(|payment_method_data| {
pm_transforms::generate_pm_vaulting_req_from_update_request(pmd, payment_method_data)
});
let vaulting_response = match vault_request_data {
// cannot use async map because of problems related to lifetimes
// to overcome this, we will have to use a move closure and add some clones
Some(ref vault_request_data) => {
let (vault_response, _) = vault_payment_method(
state,
vault_request_data,
merchant_context,
profile,
// using current vault_id for now,
// will have to refactor this to generate new one on each vaulting later on
current_vault_id,
&payment_method.customer_id,
)
.await
.attach_printable("Failed to add payment method in vault")?;
Some(vault_response)
}
None => None,
};
let (vault_id, fingerprint_id) = match vaulting_response {
Some(vaulting_response) => {
let vault_id = vaulting_response.vault_id.get_string_repr().to_owned();
(Some(vault_id), vaulting_response.fingerprint_id)
}
None => (None, None),
};
let pm_update = create_pm_additional_data_update(
vault_request_data.as_ref(),
state,
merchant_context.get_merchant_key_store(),
vault_id,
fingerprint_id,
&payment_method,
request.connector_token_details,
None,
None,
None,
None,
)
.await
.attach_printable("Unable to create Payment method data")?;
let payment_method = db
.update_payment_method(
&((state).into()),
merchant_context.get_merchant_key_store(),
payment_method,
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
let response = pm_transforms::generate_payment_method_response(&payment_method, &None)?;
// Add a PT task to handle payment_method delete from vault
Ok(response)
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn delete_payment_method(
state: SessionState,
pm_id: api::PaymentMethodId,
merchant_context: domain::MerchantContext,
profile: domain::Profile,
) -> RouterResponse<api::PaymentMethodDeleteResponse> {
let pm_id = id_type::GlobalPaymentMethodId::generate_from_string(pm_id.payment_method_id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodId")?;
let response = delete_payment_method_core(&state, pm_id, &merchant_context, &profile).await?;
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn delete_payment_method_core(
state: &SessionState,
pm_id: id_type::GlobalPaymentMethodId,
merchant_context: &domain::MerchantContext,
profile: &domain::Profile,
) -> RouterResult<api::PaymentMethodDeleteResponse> {
let db = state.store.as_ref();
let key_manager_state = &(state).into();
let payment_method = db
.find_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
&pm_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentMethodNotFound)?;
when(
payment_method.status == enums::PaymentMethodStatus::Inactive,
|| Err(errors::ApiErrorResponse::PaymentMethodNotFound),
)?;
let _customer = db
.find_customer_by_global_id(
key_manager_state,
&payment_method.customer_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Customer not found for the payment method")?;
// Soft delete
let pm_update = storage::PaymentMethodUpdate::StatusUpdate {
status: Some(enums::PaymentMethodStatus::Inactive),
};
db.update_payment_method(
&(state.into()),
merchant_context.get_merchant_key_store(),
payment_method.clone(),
pm_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update payment method in db")?;
vault::delete_payment_method_data_from_vault(state, merchant_context, profile, &payment_method)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to delete payment method from vault")?;
let response = api::PaymentMethodDeleteResponse { id: pm_id };
Ok(response)
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
trait EncryptableData {
type Output;
async fn encrypt_data(
&self,
key_manager_state: &common_utils::types::keymanager::KeyManagerState,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<Self::Output>;
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl EncryptableData for payment_methods::PaymentMethodSessionRequest {
type Output = hyperswitch_domain_models::payment_methods::DecryptedPaymentMethodSession;
async fn encrypt_data(
&self,
key_manager_state: &common_utils::types::keymanager::KeyManagerState,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<Self::Output> {
use common_utils::types::keymanager::ToEncryptable;
let encrypted_billing_address = self
.billing
.clone()
.map(|address| address.encode_to_value())
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode billing address")?
.map(Secret::new);
let batch_encrypted_data = domain_types::crypto_operation(
key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::payment_methods::PaymentMethodSession),
domain_types::CryptoOperation::BatchEncrypt(
hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::to_encryptable(
hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession {
billing: encrypted_billing_address,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(key_store.merchant_id.clone()),
key_store.key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment methods session details".to_string())?;
let encrypted_data =
hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::from_encryptable(
batch_encrypted_data,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment methods session detailss")?;
Ok(encrypted_data)
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl EncryptableData for payment_methods::PaymentMethodsSessionUpdateRequest {
type Output = hyperswitch_domain_models::payment_methods::DecryptedPaymentMethodSession;
async fn encrypt_data(
&self,
key_manager_state: &common_utils::types::keymanager::KeyManagerState,
key_store: &domain::MerchantKeyStore,
) -> RouterResult<Self::Output> {
use common_utils::types::keymanager::ToEncryptable;
let encrypted_billing_address = self
.billing
.clone()
.map(|address| address.encode_to_value())
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encode billing address")?
.map(Secret::new);
let batch_encrypted_data = domain_types::crypto_operation(
key_manager_state,
common_utils::type_name!(hyperswitch_domain_models::payment_methods::PaymentMethodSession),
domain_types::CryptoOperation::BatchEncrypt(
hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::to_encryptable(
hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession {
billing: encrypted_billing_address,
},
),
),
common_utils::types::keymanager::Identifier::Merchant(key_store.merchant_id.clone()),
key_store.key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment methods session details".to_string())?;
let encrypted_data =
hyperswitch_domain_models::payment_methods::FromRequestEncryptablePaymentMethodSession::from_encryptable(
batch_encrypted_data,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed while encrypting payment methods session detailss")?;
Ok(encrypted_data)
}
}
#[cfg(feature = "v2")]
pub async fn payment_methods_session_create(
state: SessionState,
merchant_context: domain::MerchantContext,
request: payment_methods::PaymentMethodSessionRequest,
) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
db.find_customer_by_global_id(
key_manager_state,
&request.customer_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)?;
let payment_methods_session_id =
id_type::GlobalPaymentMethodSessionId::generate(&state.conf.cell_information.id)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to generate GlobalPaymentMethodSessionId")?;
let encrypted_data = request
.encrypt_data(key_manager_state, merchant_context.get_merchant_key_store())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encrypt payment methods session data")?;
let billing = encrypted_data
.billing
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to decode billing address")?;
// If not passed in the request, use the default value from constants
let expires_in = request
.expires_in
.unwrap_or(consts::DEFAULT_PAYMENT_METHOD_SESSION_EXPIRY)
.into();
let expires_at = common_utils::date_time::now().saturating_add(Duration::seconds(expires_in));
let client_secret = payment_helpers::create_client_secret(
&state,
merchant_context.get_merchant_account().get_id(),
util_types::authentication::ResourceId::PaymentMethodSession(
payment_methods_session_id.clone(),
),
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to create client secret")?;
let payment_method_session_domain_model =
hyperswitch_domain_models::payment_methods::PaymentMethodSession {
id: payment_methods_session_id,
customer_id: request.customer_id,
billing,
psp_tokenization: request.psp_tokenization,
network_tokenization: request.network_tokenization,
tokenization_data: request.tokenization_data,
expires_at,
return_url: request.return_url,
associated_payment_methods: None,
associated_payment: None,
associated_token_id: None,
};
db.insert_payment_methods_session(
key_manager_state,
merchant_context.get_merchant_key_store(),
payment_method_session_domain_model.clone(),
expires_in,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to insert payment methods session in db")?;
let response = transformers::generate_payment_method_session_response(
payment_method_session_domain_model,
client_secret.secret,
None,
None,
);
Ok(services::ApplicationResponse::Json(response))
}
#[cfg(feature = "v2")]
pub async fn payment_methods_session_update(
state: SessionState,
merchant_context: domain::MerchantContext,
payment_method_session_id: id_type::GlobalPaymentMethodSessionId,
request: payment_methods::PaymentMethodsSessionUpdateRequest,
) -> RouterResponse<payment_methods::PaymentMethodSessionResponse> {
let db = state.store.as_ref();
let key_manager_state = &(&state).into();
let existing_payment_method_session_state = db
.get_payment_methods_session(
key_manager_state,
merchant_context.get_merchant_key_store(),
&payment_method_session_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::GenericNotFoundError {
message: "payment methods session does not exist or has expired".to_string(),
})
.attach_printable("Failed to retrieve payment methods session from db")?;
let encrypted_data = request
.encrypt_data(key_manager_state, merchant_context.get_merchant_key_store())
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to encrypt payment methods session data")?;
let billing = encrypted_data
.billing
.as_ref()
.map(|data| {
data.clone()
.deserialize_inner_value(|value| value.parse_value("Address"))
})
.transpose()
|
crates/router/src/core/payment_methods.rs#chunk2
|
router
|
chunk
| 8,188
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl ConnectorValidation for Powertranz {}
|
crates/hyperswitch_connectors/src/connectors/powertranz.rs
|
hyperswitch_connectors
|
impl_block
| 8
|
rust
| null |
Powertranz
|
ConnectorValidation for
|
impl ConnectorValidation for for Powertranz
| null | null | null | null | null | null | null | null |
pub struct WellsfargopayoutRouterData<T> {
pub amount: StringMinorUnit, // The type of amount that a connector accepts, for example, String, i64, f64, etc.
pub router_data: T,
}
|
crates/hyperswitch_connectors/src/connectors/wellsfargopayout/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 53
|
rust
|
WellsfargopayoutRouterData
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn find_payment_merchant_connector_account(
&self,
state: &SessionState,
key_store: &domain::MerchantKeyStore,
billing_connector_account: &domain::MerchantConnectorAccount,
) -> CustomResult<Option<domain::MerchantConnectorAccount>, errors::RevenueRecoveryError> {
let payment_merchant_connector_account_id = billing_connector_account
.get_payment_merchant_connector_account_id_using_account_reference_id(
self.0.connector_account_reference_id.clone(),
);
let db = &*state.store;
let key_manager_state = &(state).into();
let payment_merchant_connector_account = payment_merchant_connector_account_id
.as_ref()
.async_map(|mca_id| async move {
db.find_merchant_connector_account_by_id(key_manager_state, mca_id, key_store)
.await
})
.await
.transpose()
.change_context(errors::RevenueRecoveryError::PaymentMerchantConnectorAccountNotFound)
.attach_printable(
"failed to fetch payment merchant connector id using account reference id",
)?;
Ok(payment_merchant_connector_account)
}
|
crates/router/src/core/webhooks/recovery_incoming.rs
|
router
|
function_signature
| 240
|
rust
| null | null | null | null |
find_payment_merchant_connector_account
| null | null | null | null | null | null | null |
pub fn get_auth_string_from_header(&self) -> RouterResult<&str> {
self.headers
.get(headers::AUTHORIZATION)
.get_required_value(headers::AUTHORIZATION)?
.to_str()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: headers::AUTHORIZATION,
})
.attach_printable("Failed to convert authorization header to string")
}
|
crates/router/src/services/authentication.rs
|
router
|
function_signature
| 84
|
rust
| null | null | null | null |
get_auth_string_from_header
| null | null | null | null | null | null | null |
impl api::ConnectorAccessToken for Silverflow {}
|
crates/hyperswitch_connectors/src/connectors/silverflow.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Silverflow
|
api::ConnectorAccessToken for
|
impl api::ConnectorAccessToken for for Silverflow
| null | null | null | null | null | null | null | null |
pub struct WisePayoutSyncResponse {
id: u64,
status: WiseSyncStatus,
}
|
crates/hyperswitch_connectors/src/connectors/wise/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 23
|
rust
|
WisePayoutSyncResponse
| null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.SdkInformation
{
"type": "object",
"description": "SDK Information if request is from SDK",
"required": [
"sdk_app_id",
"sdk_enc_data",
"sdk_ephem_pub_key",
"sdk_trans_id",
"sdk_reference_number",
"sdk_max_timeout"
],
"properties": {
"sdk_app_id": {
"type": "string",
"description": "Unique ID created on installations of the 3DS Requestor App on a Consumer Device"
},
"sdk_enc_data": {
"type": "string",
"description": "JWE Object containing data encrypted by the SDK for the DS to decrypt"
},
"sdk_ephem_pub_key": {
"type": "object",
"description": "Public key component of the ephemeral key pair generated by the 3DS SDK",
"additionalProperties": {
"type": "string"
}
},
"sdk_trans_id": {
"type": "string",
"description": "Unique transaction identifier assigned by the 3DS SDK"
},
"sdk_reference_number": {
"type": "string",
"description": "Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App"
},
"sdk_max_timeout": {
"type": "integer",
"format": "int32",
"description": "Indicates maximum amount of time in minutes",
"minimum": 0
},
"sdk_type": {
"allOf": [
{
"$ref": "#/components/schemas/SdkType"
}
],
"nullable": true
}
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 377
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"SdkInformation"
] | null | null | null | null |
File: crates/router/src/types/payment_methods.rs
Public functions: 1
Public structs: 39
use std::fmt::Debug;
use api_models::enums as api_enums;
#[cfg(feature = "v1")]
use cards::CardNumber;
#[cfg(feature = "v2")]
use cards::{CardNumber, NetworkToken};
#[cfg(feature = "v2")]
use common_types::primitive_wrappers;
#[cfg(feature = "v2")]
use common_utils::generate_id;
use common_utils::id_type;
#[cfg(feature = "v2")]
use hyperswitch_domain_models::payment_method_data::NetworkTokenDetails;
use masking::Secret;
use serde::{Deserialize, Serialize};
use crate::types::api;
#[cfg(feature = "v2")]
use crate::{
consts,
types::{domain, storage},
};
#[cfg(feature = "v2")]
pub trait VaultingInterface {
fn get_vaulting_request_url() -> &'static str;
fn get_vaulting_flow_name() -> &'static str;
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultFingerprintRequest {
pub data: String,
pub key: String,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultFingerprintResponse {
pub fingerprint_id: String,
}
#[cfg(any(feature = "v2", feature = "tokenization_v2"))]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AddVaultRequest<D> {
pub entity_id: id_type::GlobalCustomerId,
pub vault_id: domain::VaultId,
pub data: D,
pub ttl: i64,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AddVaultResponse {
pub entity_id: Option<id_type::GlobalCustomerId>,
pub vault_id: domain::VaultId,
pub fingerprint_id: Option<String>,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct AddVault;
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct GetVaultFingerprint;
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultRetrieve;
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultDelete;
#[cfg(feature = "v2")]
impl VaultingInterface for AddVault {
fn get_vaulting_request_url() -> &'static str {
consts::ADD_VAULT_REQUEST_URL
}
fn get_vaulting_flow_name() -> &'static str {
consts::VAULT_ADD_FLOW_TYPE
}
}
#[cfg(feature = "v2")]
impl VaultingInterface for GetVaultFingerprint {
fn get_vaulting_request_url() -> &'static str {
consts::VAULT_FINGERPRINT_REQUEST_URL
}
fn get_vaulting_flow_name() -> &'static str {
consts::VAULT_GET_FINGERPRINT_FLOW_TYPE
}
}
#[cfg(feature = "v2")]
impl VaultingInterface for VaultRetrieve {
fn get_vaulting_request_url() -> &'static str {
consts::VAULT_RETRIEVE_REQUEST_URL
}
fn get_vaulting_flow_name() -> &'static str {
consts::VAULT_RETRIEVE_FLOW_TYPE
}
}
#[cfg(feature = "v2")]
impl VaultingInterface for VaultDelete {
fn get_vaulting_request_url() -> &'static str {
consts::VAULT_DELETE_REQUEST_URL
}
fn get_vaulting_flow_name() -> &'static str {
consts::VAULT_DELETE_FLOW_TYPE
}
}
#[cfg(feature = "v2")]
pub struct SavedPMLPaymentsInfo {
pub payment_intent: storage::PaymentIntent,
pub profile: domain::Profile,
pub collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>,
pub off_session_payment_flag: bool,
pub is_connector_agnostic_mit_enabled: bool,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultRetrieveRequest {
pub entity_id: id_type::GlobalCustomerId,
pub vault_id: domain::VaultId,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultRetrieveResponse {
pub data: domain::PaymentMethodVaultingData,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultDeleteRequest {
pub entity_id: id_type::GlobalCustomerId,
pub vault_id: domain::VaultId,
}
#[cfg(feature = "v2")]
#[derive(Debug, serde::Deserialize, serde::Serialize)]
pub struct VaultDeleteResponse {
pub entity_id: id_type::GlobalCustomerId,
pub vault_id: domain::VaultId,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardData {
pub card_number: CardNumber,
pub exp_month: Secret<String>,
pub exp_year: Secret<String>,
pub card_security_code: Option<Secret<String>>,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardData {
pub card_number: CardNumber,
pub exp_month: Secret<String>,
pub exp_year: Secret<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub card_security_code: Option<Secret<String>>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderData {
pub consent_id: String,
pub customer_id: id_type::CustomerId,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct OrderData {
pub consent_id: String,
pub customer_id: id_type::GlobalCustomerId,
}
#[derive(Debug, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct ApiPayload {
pub service: String,
pub card_data: Secret<String>, //encrypted card data
pub order_data: OrderData,
pub key_id: String,
pub should_send_token: bool,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct CardNetworkTokenResponse {
pub payload: Secret<String>, //encrypted payload
}
#[cfg(feature = "v1")]
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardNetworkTokenResponsePayload {
pub card_brand: api_enums::CardNetwork,
pub card_fingerprint: Option<Secret<String>>,
pub card_reference: String,
pub correlation_id: String,
pub customer_id: String,
pub par: String,
pub token: CardNumber,
pub token_expiry_month: Secret<String>,
pub token_expiry_year: Secret<String>,
pub token_isin: String,
pub token_last_four: String,
pub token_status: String,
}
#[cfg(feature = "v2")]
#[derive(Debug, Clone, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct GenerateNetworkTokenResponsePayload {
pub card_brand: api_enums::CardNetwork,
pub card_fingerprint: Option<Secret<String>>,
pub card_reference: String,
pub correlation_id: String,
pub customer_id: String,
pub par: String,
pub token: NetworkToken,
pub token_expiry_month: Secret<String>,
pub token_expiry_year: Secret<String>,
pub token_isin: String,
pub token_last_four: String,
pub token_status: String,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize)]
pub struct GetCardToken {
pub card_reference: String,
pub customer_id: id_type::CustomerId,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize)]
pub struct GetCardToken {
pub card_reference: String,
pub customer_id: id_type::GlobalCustomerId,
}
#[cfg(feature = "v1")]
#[derive(Debug, Deserialize)]
pub struct AuthenticationDetails {
pub cryptogram: Secret<String>,
pub token: CardNumber, //network token
}
#[cfg(feature = "v2")]
#[derive(Debug, Deserialize)]
pub struct AuthenticationDetails {
pub cryptogram: Secret<String>,
pub token: NetworkToken, //network token
}
#[derive(Debug, Serialize, Deserialize)]
pub struct TokenDetails {
pub exp_month: Secret<String>,
pub exp_year: Secret<String>,
}
#[derive(Debug, Deserialize)]
pub struct TokenResponse {
pub authentication_details: AuthenticationDetails,
pub network: api_enums::CardNetwork,
pub token_details: TokenDetails,
pub eci: Option<String>,
pub card_type: Option<String>,
pub issuer: Option<String>,
pub nickname: Option<Secret<String>>,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
pub struct DeleteCardToken {
pub card_reference: String, //network token requestor ref id
pub customer_id: id_type::CustomerId,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
pub struct DeleteCardToken {
pub card_reference: String, //network token requestor ref id
pub customer_id: id_type::GlobalCustomerId,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum DeleteNetworkTokenStatus {
Success,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct NetworkTokenErrorInfo {
pub code: String,
pub developer_message: String,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct NetworkTokenErrorResponse {
pub error_message: String,
pub error_info: NetworkTokenErrorInfo,
}
#[derive(Debug, Deserialize, Eq, PartialEq)]
pub struct DeleteNetworkTokenResponse {
pub status: DeleteNetworkTokenStatus,
}
#[cfg(feature = "v1")]
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckTokenStatus {
pub card_reference: String,
pub customer_id: id_type::CustomerId,
}
#[cfg(feature = "v2")]
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckTokenStatus {
pub card_reference: String,
pub customer_id: id_type::GlobalCustomerId,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum TokenStatus {
Active,
Inactive,
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CheckTokenStatusResponsePayload {
pub token_expiry_month: Secret<String>,
pub token_expiry_year: Secret<String>,
pub token_status: TokenStatus,
}
#[derive(Debug, Deserialize)]
pub struct CheckTokenStatusResponse {
pub payload: CheckTokenStatusResponsePayload,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NetworkTokenRequestorData {
pub card_reference: String,
pub customer_id: String,
pub expiry_year: Secret<String>,
pub expiry_month: Secret<String>,
}
impl NetworkTokenRequestorData {
pub fn is_update_required(
&self,
data_stored_in_vault: api::payment_methods::CardDetailFromLocker,
) -> bool {
//if the expiry year and month in the vault are not the same as the ones in the requestor data,
//then we need to update the vault data with the updated expiry year and month.
!((data_stored_in_vault.expiry_year.unwrap_or_default() == self.expiry_year)
&& (data_stored_in_vault.expiry_month.unwrap_or_default() == self.expiry_month))
}
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct NetworkTokenMetaDataUpdateBody {
pub token: NetworkTokenRequestorData,
}
#[derive(Debug, Clone, Deserialize, Serialize)]
pub struct PanMetadataUpdateBody {
pub card: NetworkTokenRequestorData,
}
|
crates/router/src/types/payment_methods.rs
|
router
|
full_file
| 2,558
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn delete_totp_from_redis(state: &SessionState, user_id: &str) -> UserResult<()> {
let redis_conn = super::get_redis_connection_for_global_tenant(state)?;
let key = format!("{}{}", consts::user::REDIS_TOTP_PREFIX, user_id);
redis_conn
.delete_key(&key.into())
.await
.change_context(UserErrors::InternalServerError)
.map(|_| ())
}
|
crates/router/src/utils/user/two_factor_auth.rs
|
router
|
function_signature
| 93
|
rust
| null | null | null | null |
delete_totp_from_redis
| null | null | null | null | null | null | null |
pub struct HyperswitchVaultCreateResponse {
id: Secret<String>,
client_secret: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/hyperswitch_vault/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 23
|
rust
|
HyperswitchVaultCreateResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub struct CustomerInfo {
card_holder_name: Secret<String>,
billing_address: Option<BillingAddress>,
shipping_address: Option<ShippingAddress>,
}
|
crates/hyperswitch_connectors/src/connectors/nexixpay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 32
|
rust
|
CustomerInfo
| null | null | null | null | null | null | null | null | null | null | null |
pub struct ZenCardDetails {
number: CardNumber,
expiry_date: Secret<String>,
cvv: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/zen/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 27
|
rust
|
ZenCardDetails
| null | null | null | null | null | null | null | null | null | null | null |
Web Documentation: Smart Routing | Hyperswitch
# Type: Web Doc
Prerequisites
To get started with Smart Router, ensure to have one or more payment processors integrated. You can integrate the payment processor of your choice on the Control Center by following the
Connector Integration
guide.
What is smart payment routing?
Selling globally or otherwise invariably brings in a requirement to adopt multiple payment processors to cater to a wide range of payment method needs of the customers and gives you the flexibility to switch between processors to manage down-time and , it could be vital to optimising your payment processing costs as your business can choose the most optimal payment processors for every payment based on the cost, region and customer.
Hence, Hyperswitch’s smart router is designed as a no-code tool to provide complete control and transparency in creating and modifying payment routing rules. Hyperswitch supports below formats of Smart Routing.
Volume Based Configuration:
Define volume distribution among multiple payment processors using percentages.
Rule Based Configuration:
More granular control which allows to define custom routing logics based on different parameters of payment.
Default Fallback Routing :
If the active routing rules are not applicable, the priority order of all configured payment processors is used to route payments. This priority order is configurable from the Dashboard.
Cost Based Configuration
(submit a feature request
here
)
:
Automatically routes transaction to the payment processor charging the least MDR (merchant discount rate) for the opted payment method.
How does the Smart Router work?
Hyperswitch Smart Router Engine evaluates every payment request against your predefined routing logic and makes a decision on the best payment processor for the payment, and executes the transaction. If the payment fails or if the payment processor is down, the payment is automatically retried through a different processor.
How to configure the Smart Router?
Hyperswitch dashboard
provides a simple, intuitive UI to configure multiple Routing rules on your dashboard under the
Routing
tab. There are three routing rule formats that Hyperswitch currently supports.
\
Rule Based Routing
Volume Based Routing
Default Fallback Routing
To test the Smart Router, after activating one rule, we can make a Test Payment using the
Hyperswitch Dashboard
Test a payment
FAQs
1. What parameters can I use to configure routing rules?
The rule-based routing supports setting up advanced rule configuration based on all critical /payments parameters such as Payment Method, Payment Method Type, Country, Currency, Amount etc.
2. Why did my payment go through 'Y' connector even though I have specified 'X' in my routing configuration? OR Why is it showing me 'Abc' payment method in SDK checkout even though I have not enabled it for the 'X' connector that I'm routing my payments through?
There can be multiple reasons why this happened but all of them can be boiled down to a "connector eligibility failure" for a given payment. We'll walk through a common scenario to examine what this really means.
Imagine that you configured two connectors for your account. Say
Stripe
, then
Adyen
, in that order. Since you configured them in that order, your default fallback looks like this:
[Stripe, Adyen]
(connectors are appended to the end of your default fallback list when configured for the first time)
In your connectors dashboard, you enable Cards for Stripe, and ApplePay for Adyen.
Now you create a new Volume-based routing configuration, and you configure it to route 100% of your traffic through Stripe for now.
Now you go ahead and open up the Hyperswitch SDK to make a test payment. In the payment method selection area, you can see two buttons, one for
Cards
and one for
ApplePay
.
This is where you run into your first question. "Why is it showing me ApplePay even though I have configured 100% of my payments to go through Stripe, and ApplePay is not enabled for Stripe?"
The answer to this is, the payment methods that are shown to the customer in the SDK aren't conscious of your routing configuration. We prioritize giving your customers the complete spread of all enabled payment methods across all of your enabled connectors. Therefore, if you specifically do not wish for ApplePay to appear on your checkout screen, you need to disable it in
Adyen
here, even though your routing configuration makes no mention of Adyen.
Now you select
ApplePay
, go through the required steps, confirm the payment, and it succeeds. You go to your payments dashboard and see that the payment went through
Adyen
.
This is where you run into the second question. "Why is the payment going through
Adyen
even though I have set my routing configuration to route 100% of my payments through
Stripe
?
ApplePay
on the checkout screen even though it wasn't enabled for your preferred connector
Stripe
, we need to adhere to your connector payment method configuration and ensure the payment goes through the right connector, here,
Adyen
since
ApplePay
is only enabled for Adyen. To briefly explain how Hyperswitch reaches this conclusion :-
Hyperswitch runs your configured routing algorithm. Since this is
100% Stripe
, Hyperswitch receives
Stripe
as the outuput.
Hyperswitch then runs an Eligibility Analysis on the output (
Stripe
) to gauge its eligibility for the current payment. The Eligibility Analysis fails once Hyperswitch realizes that the payment is made through
ApplePay
which is not enabled for
Stripe
The application then goes into fallback mode and loads your
default fallback
, which is
[Stripe, Adyen]
as seen earlier.
The application looks through the list in order. It ignores
Stripe
since it has already failed the Eligibility Analysis. It instead subjects
Adyen
This time the analysis passes since
ApplePay
is enabled for
Adyen
.
Hyperswitch takes
Adyen
as the final connector to make the payment through even though your configuration says
100% Stripe
.
This fallback flow is taken when none of the connectors in the output of routing are eligible for the payment. This is done in an effort to maximize the success rate of the payment even if it means deviating from the currently active routing configuration.
10 months ago
Was this helpful?
|
https://docs.hyperswitch.io/explore-hyperswitch/payment-orchestration/smart-router
| null |
web_doc_file
| 1,294
|
doc
| null | null | null | null | null |
web
| null | null | null |
https://docs.hyperswitch.io/explore-hyperswitch/payment-orchestration/smart-router
|
Smart Routing | Hyperswitch
| null |
File: crates/hyperswitch_connectors/src/connectors/payload.rs
Public functions: 1
Public structs: 1
mod requests;
mod responses;
pub mod transformers;
use std::sync::LazyLock;
use base64::Engine;
use common_enums::enums;
use common_utils::{
consts::BASE64_ENGINE,
errors::{CustomResult, ReportSwitchExt},
ext_traits::{ByteSliceExt, BytesExt},
request::{Method, Request, RequestBuilder, RequestContent},
types::{AmountConvertor, StringMajorUnit, StringMajorUnitForConnector},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::{
access_token_auth::AccessTokenAuth,
payments::{Authorize, Capture, PSync, PaymentMethodToken, Session, SetupMandate, Void},
refunds::{Execute, RSync},
},
router_request_types::{
AccessTokenRequestData, PaymentMethodTokenizationData, PaymentsAuthorizeData,
PaymentsCancelData, PaymentsCaptureData, PaymentsSessionData, PaymentsSyncData,
RefundsData, SetupMandateRequestData,
},
router_response_types::{
ConnectorInfo, PaymentMethodDetails, PaymentsResponseData, RefundsResponseData,
SupportedPaymentMethods, SupportedPaymentMethodsExt,
},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
PaymentsSyncRouterData, RefundSyncRouterData, RefundsRouterData, SetupMandateRouterData,
},
};
use hyperswitch_interfaces::{
api::{
self, ConnectorCommon, ConnectorCommonExt, ConnectorIntegration, ConnectorSpecifications,
ConnectorValidation,
},
configs::Connectors,
errors,
events::connector_api_logs::ConnectorEvent,
types::{self, PaymentsVoidType, Response, SetupMandateType},
webhooks,
};
use masking::{ExposeInterface, Mask, Secret};
use transformers as payload;
use crate::{constants::headers, types::ResponseRouterData, utils};
#[derive(Clone)]
pub struct Payload {
amount_converter: &'static (dyn AmountConvertor<Output = StringMajorUnit> + Sync),
}
impl Payload {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMajorUnitForConnector,
}
}
}
impl api::Payment for Payload {}
impl api::PaymentSession for Payload {}
impl api::ConnectorAccessToken for Payload {}
impl api::MandateSetup for Payload {}
impl api::PaymentAuthorize for Payload {}
impl api::PaymentSync for Payload {}
impl api::PaymentCapture for Payload {}
impl api::PaymentVoid for Payload {}
impl api::Refund for Payload {}
impl api::RefundExecute for Payload {}
impl api::RefundSync for Payload {}
impl api::PaymentToken for Payload {}
impl ConnectorIntegration<PaymentMethodToken, PaymentMethodTokenizationData, PaymentsResponseData>
for Payload
{
// Not Implemented (R)
}
impl<Flow, Request, Response> ConnectorCommonExt<Flow, Request, Response> for Payload
where
Self: ConnectorIntegration<Flow, Request, Response>,
{
fn build_headers(
&self,
req: &RouterData<Flow, Request, Response>,
_connectors: &Connectors,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let mut header = vec![(
headers::CONTENT_TYPE.to_string(),
Self::common_get_content_type(self).to_string().into(),
)];
let mut api_key = self.get_auth_header(&req.connector_auth_type)?;
header.append(&mut api_key);
Ok(header)
}
}
impl ConnectorCommon for Payload {
fn id(&self) -> &'static str {
"payload"
}
fn get_currency_unit(&self) -> api::CurrencyUnit {
api::CurrencyUnit::Minor
}
fn common_get_content_type(&self) -> &'static str {
"application/x-www-form-urlencoded"
}
fn base_url<'a>(&self, connectors: &'a Connectors) -> &'a str {
connectors.payload.base_url.as_ref()
}
fn get_auth_header(
&self,
auth_type: &ConnectorAuthType,
) -> CustomResult<Vec<(String, masking::Maskable<String>)>, errors::ConnectorError> {
let auth = payload::PayloadAuthType::try_from(auth_type)
.change_context(errors::ConnectorError::FailedToObtainAuthType)?;
// The API key is the same for all currencies, so we can take any.
let api_key = auth
.auths
.values()
.next()
.ok_or(errors::ConnectorError::FailedToObtainAuthType)?
.api_key
.clone();
let encoded_api_key = BASE64_ENGINE.encode(format!("{}:", api_key.expose()));
Ok(vec![(
headers::AUTHORIZATION.to_string(),
format!("Basic {encoded_api_key}").into_masked(),
)])
}
fn build_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
let response: responses::PayloadErrorResponse = res
.response
.parse_struct("PayloadErrorResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
Ok(ErrorResponse {
status_code: res.status_code,
code: response.error_type,
message: response.error_description,
reason: response
.details
.as_ref()
.map(|details_value| details_value.to_string()),
attempt_status: None,
connector_transaction_id: None,
network_advice_code: None,
network_decline_code: None,
network_error_message: None,
connector_metadata: None,
})
}
}
impl ConnectorValidation for Payload {
fn validate_mandate_payment(
&self,
pm_type: Option<enums::PaymentMethodType>,
pm_data: PaymentMethodData,
) -> CustomResult<(), errors::ConnectorError> {
let mandate_supported_pmd =
std::collections::HashSet::from([utils::PaymentMethodDataType::Card]);
utils::is_mandate_supported(pm_data, pm_type, mandate_supported_pmd, self.id())
}
}
impl ConnectorIntegration<Session, PaymentsSessionData, PaymentsResponseData> for Payload {}
impl ConnectorIntegration<AccessTokenAuth, AccessTokenRequestData, AccessToken> for Payload {}
impl ConnectorIntegration<SetupMandate, SetupMandateRequestData, PaymentsResponseData> for Payload {
fn get_headers(
&self,
req: &SetupMandateRouterData,
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: &SetupMandateRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
Ok(format!("{}/transactions", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &SetupMandateRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_req = requests::PayloadCardsRequestData::try_from(req)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RouterData<SetupMandate, SetupMandateRequestData, PaymentsResponseData>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&SetupMandateType::get_url(self, req, connectors)?)
.headers(SetupMandateType::get_headers(self, req, connectors)?)
.set_body(SetupMandateType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &SetupMandateRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<SetupMandateRouterData, errors::ConnectorError> {
let response: responses::PayloadPaymentsResponse = res
.response
.parse_struct("PayloadPaymentsResponse")
.change_context(errors::ConnectorError::ResponseDeserializationFailed)?;
event_builder.map(|i| i.set_response_body(&response));
router_env::logger::info!(connector_response=?response);
RouterData::try_from(ResponseRouterData {
response,
data: data.clone(),
http_code: res.status_code,
})
}
fn get_error_response(
&self,
res: Response,
event_builder: Option<&mut ConnectorEvent>,
) -> CustomResult<ErrorResponse, errors::ConnectorError> {
self.build_error_response(res, event_builder)
}
}
impl ConnectorIntegration<Authorize, PaymentsAuthorizeData, PaymentsResponseData> for Payload {
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> {
Ok(format!("{}/transactions", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &PaymentsAuthorizeRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount,
req.request.currency,
)?;
let connector_router_data = payload::PayloadRouterData::from((amount, req));
let connector_req = requests::PayloadPaymentsRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsAuthorizeRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Post)
.url(&types::PaymentsAuthorizeType::get_url(
self, req, connectors,
)?)
.attach_default_headers()
.headers(types::PaymentsAuthorizeType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsAuthorizeType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsAuthorizeRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsAuthorizeRouterData, errors::ConnectorError> {
let response: responses::PayloadPaymentsResponse = res
.response
.parse_struct("PayloadPaymentsResponse")
.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 Payload {
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> {
let payment_id = req
.request
.connector_transaction_id
.get_connector_transaction_id()
.change_context(errors::ConnectorError::MissingConnectorTransactionID)?;
Ok(format!(
"{}/transactions/{}",
self.base_url(connectors),
payment_id
))
}
fn build_request(
&self,
req: &PaymentsSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::PaymentsSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsSyncType::get_headers(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsSyncRouterData, errors::ConnectorError> {
let response: responses::PayloadPaymentsResponse = res
.response
.parse_struct("PayloadPaymentsSyncResponse")
.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 Payload {
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> {
let connector_transaction_id = req.request.connector_transaction_id.clone();
Ok(format!(
"{}/transactions/{}",
self.base_url(connectors),
connector_transaction_id
))
}
fn get_request_body(
&self,
req: &PaymentsCaptureRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let amount = utils::convert_amount(
self.amount_converter,
req.request.minor_amount_to_capture,
req.request.currency,
)?;
let connector_router_data = payload::PayloadRouterData::from((amount, req));
let connector_req = requests::PayloadCaptureRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCaptureRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Put)
.url(&types::PaymentsCaptureType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::PaymentsCaptureType::get_headers(
self, req, connectors,
)?)
.set_body(types::PaymentsCaptureType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &PaymentsCaptureRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<PaymentsCaptureRouterData, errors::ConnectorError> {
let response: responses::PayloadPaymentsResponse = res
.response
.parse_struct("PayloadPaymentsCaptureResponse")
.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 Payload {
fn get_headers(
&self,
req: &PaymentsCancelRouterData,
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: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<String, errors::ConnectorError> {
let payment_id = &req.request.connector_transaction_id;
Ok(format!(
"{}/transactions/{}",
self.base_url(connectors),
payment_id
))
}
fn get_request_body(
&self,
req: &PaymentsCancelRouterData,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let connector_router_data = payload::PayloadRouterData::from((Default::default(), req));
let connector_req = requests::PayloadCancelRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &PaymentsCancelRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Put)
.url(&PaymentsVoidType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(PaymentsVoidType::get_headers(self, req, connectors)?)
.set_body(PaymentsVoidType::get_request_body(self, req, connectors)?)
.build(),
))
}
fn handle_response(
&self,
data: &RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<
RouterData<Void, PaymentsCancelData, PaymentsResponseData>,
errors::ConnectorError,
> {
let response: responses::PayloadPaymentsResponse = res
.response
.parse_struct("PayloadPaymentsCancelResponse")
.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<Execute, RefundsData, RefundsResponseData> for Payload {
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> {
Ok(format!("{}/transactions", self.base_url(connectors)))
}
fn get_request_body(
&self,
req: &RefundsRouterData<Execute>,
_connectors: &Connectors,
) -> CustomResult<RequestContent, errors::ConnectorError> {
let refund_amount = utils::convert_amount(
self.amount_converter,
req.request.minor_refund_amount,
req.request.currency,
)?;
let connector_router_data = payload::PayloadRouterData::from((refund_amount, req));
let connector_req = requests::PayloadRefundRequest::try_from(&connector_router_data)?;
Ok(RequestContent::FormUrlEncoded(Box::new(connector_req)))
}
fn build_request(
&self,
req: &RefundsRouterData<Execute>,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
let request = RequestBuilder::new()
.method(Method::Post)
.url(&types::RefundExecuteType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundExecuteType::get_headers(
self, req, connectors,
)?)
.set_body(types::RefundExecuteType::get_request_body(
self, req, connectors,
)?)
.build();
Ok(Some(request))
}
fn handle_response(
&self,
data: &RefundsRouterData<Execute>,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundsRouterData<Execute>, errors::ConnectorError> {
let response: responses::PayloadRefundResponse = res
.response
.parse_struct("PayloadRefundResponse")
.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 Payload {
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> {
let connector_refund_id = req
.request
.connector_refund_id
.as_ref()
.ok_or_else(|| errors::ConnectorError::MissingConnectorRefundID)?;
Ok(format!(
"{}/transactions/{}",
self.base_url(connectors),
connector_refund_id
))
}
fn build_request(
&self,
req: &RefundSyncRouterData,
connectors: &Connectors,
) -> CustomResult<Option<Request>, errors::ConnectorError> {
Ok(Some(
RequestBuilder::new()
.method(Method::Get)
.url(&types::RefundSyncType::get_url(self, req, connectors)?)
.attach_default_headers()
.headers(types::RefundSyncType::get_headers(self, req, connectors)?)
.set_body(types::RefundSyncType::get_request_body(
self, req, connectors,
)?)
.build(),
))
}
fn handle_response(
&self,
data: &RefundSyncRouterData,
event_builder: Option<&mut ConnectorEvent>,
res: Response,
) -> CustomResult<RefundSyncRouterData, errors::ConnectorError> {
let response: responses::PayloadRefundResponse = res
.response
.parse_struct("PayloadRefundSyncResponse")
.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 Payload {
async fn verify_webhook_source(
&self,
_request: &webhooks::IncomingWebhookRequestDetails<'_>,
_merchant_id: &common_utils::id_type::MerchantId,
_connector_webhook_details: Option<common_utils::pii::SecretSerdeValue>,
_connector_account_details: common_utils::crypto::Encryptable<Secret<serde_json::Value>>,
_connector_label: &str,
) -> CustomResult<bool, errors::ConnectorError> {
// Payload does not support source verification
// It does, but the client id and client secret generation is not possible at present
// It requires OAuth connect which falls under Access Token flow and it also requires multiple calls to be made
// We return false just so that a PSync call is triggered internally
Ok(false)
}
fn get_webhook_object_reference_id(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::ObjectReferenceId, errors::ConnectorError> {
let webhook_body: responses::PayloadWebhookEvent = request
.body
.parse_struct("PayloadWebhookEvent")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let reference_id = match webhook_body.trigger {
responses::PayloadWebhooksTrigger::Payment
| responses::PayloadWebhooksTrigger::Processed
| responses::PayloadWebhooksTrigger::Authorized
| responses::PayloadWebhooksTrigger::Credit
| responses::PayloadWebhooksTrigger::Reversal
| responses::PayloadWebhooksTrigger::Void
| responses::PayloadWebhooksTrigger::AutomaticPayment
| responses::PayloadWebhooksTrigger::Decline
| responses::PayloadWebhooksTrigger::Deposit
| responses::PayloadWebhooksTrigger::Reject
| responses::PayloadWebhooksTrigger::PaymentActivationStatus
| responses::PayloadWebhooksTrigger::PaymentLinkStatus
| responses::PayloadWebhooksTrigger::ProcessingStatus
| responses::PayloadWebhooksTrigger::BankAccountReject
| responses::PayloadWebhooksTrigger::Chargeback
| responses::PayloadWebhooksTrigger::ChargebackReversal
| responses::PayloadWebhooksTrigger::TransactionOperation
| responses::PayloadWebhooksTrigger::TransactionOperationClear => {
api_models::webhooks::ObjectReferenceId::PaymentId(
api_models::payments::PaymentIdType::ConnectorTransactionId(
webhook_body
.triggered_on
.transaction_id
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,
),
)
}
responses::PayloadWebhooksTrigger::Refund => {
api_models::webhooks::ObjectReferenceId::RefundId(
api_models::webhooks::RefundIdType::ConnectorRefundId(
webhook_body
.triggered_on
.transaction_id
.ok_or(errors::ConnectorError::WebhookReferenceIdNotFound)?,
),
)
}
};
Ok(reference_id)
}
fn get_webhook_event_type(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<api_models::webhooks::IncomingWebhookEvent, errors::ConnectorError> {
let webhook_body: responses::PayloadWebhookEvent =
request.body.parse_struct("PayloadWebhookEvent").switch()?;
Ok(api_models::webhooks::IncomingWebhookEvent::from(
webhook_body.trigger,
))
}
fn get_webhook_resource_object(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, errors::ConnectorError> {
let webhook_body: responses::PayloadWebhookEvent = request
.body
.parse_struct("PayloadWebhookEvent")
.change_context(errors::ConnectorError::WebhookReferenceIdNotFound)?;
Ok(Box::new(webhook_body))
}
}
static PAYLOAD_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let mut payload_supported_payment_methods = SupportedPaymentMethods::new();
let supported_capture_methods = vec![
enums::CaptureMethod::Automatic,
enums::CaptureMethod::Manual,
enums::CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::AmericanExpress,
common_enums::CardNetwork::Discover,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Visa,
];
payload_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
payload_supported_payment_methods.add(
enums::PaymentMethod::Card,
enums::PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: enums::FeatureStatus::Supported,
refunds: enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::NotSupported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
payload_supported_payment_methods
});
static PAYLOAD_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Payload",
description: "Payload is an embedded finance solution for modern platforms and businesses, automating inbound and outbound payments with an industry-leading platform and driving innovation into the future.",
connector_type: enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: enums::ConnectorIntegrationStatus::Alpha,
};
static PAYLOAD_SUPPORTED_WEBHOOK_FLOWS: [enums::EventClass; 3] = [
enums::EventClass::Disputes,
enums::EventClass::Payments,
enums::EventClass::Refunds,
];
impl ConnectorSpecifications for Payload {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&PAYLOAD_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*PAYLOAD_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [enums::EventClass]> {
Some(&PAYLOAD_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/payload.rs
|
hyperswitch_connectors
|
full_file
| 7,059
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct AuthenticationErrorMessageAccumulator {
pub count: Option<i64>,
}
|
crates/analytics/src/auth_events/accumulator.rs
|
analytics
|
struct_definition
| 18
|
rust
|
AuthenticationErrorMessageAccumulator
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn create_gsm_rule(
state: SessionState,
gsm_rule: gsm_api_types::GsmCreateRequest,
) -> RouterResponse<gsm_api_types::GsmResponse> {
let db = state.store.as_ref();
GsmInterface::add_gsm_rule(db, gsm_rule.foreign_into())
.await
.to_duplicate_response(errors::ApiErrorResponse::GenericDuplicateError {
message: "GSM with given key already exists in our records".to_string(),
})
.map(|gsm| services::ApplicationResponse::Json(gsm.foreign_into()))
}
|
crates/router/src/core/gsm.rs
|
router
|
function_signature
| 128
|
rust
| null | null | null | null |
create_gsm_rule
| null | null | null | null | null | null | null |
pub struct GooglePayWalletData {
/// The type of payment method
pub pm_type: String,
/// User-facing message to describe the payment method that funds this transaction.
pub description: String,
/// The information of the payment method
pub info: GooglePayPaymentMethodInfo,
/// The tokenization data of Google pay
pub tokenization_data: common_types::payments::GpayTokenizationData,
}
|
crates/hyperswitch_domain_models/src/payment_method_data.rs
|
hyperswitch_domain_models
|
struct_definition
| 89
|
rust
|
GooglePayWalletData
| null | null | null | null | null | null | null | null | null | null | null |
pub struct PaymentThreshold {
pub overpayment_absolute_threshold: OverpaymentAbsoluteThreshold,
pub overpayment_relative_threshold: String,
pub underpayment_absolute_threshold: OverpaymentAbsoluteThreshold,
pub underpayment_relative_threshold: String,
}
|
crates/hyperswitch_connectors/src/connectors/coinbase/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 48
|
rust
|
PaymentThreshold
| null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: paths."/gsm/delete"
{
"post": {
"tags": [
"Gsm"
],
"summary": "Gsm - Delete",
"description": "Deletes a Gsm Rule",
"operationId": "Delete Gsm Rule",
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/GsmDeleteRequest"
}
}
},
"required": true
},
"responses": {
"200": {
"description": "Gsm deleted",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/GsmDeleteResponse"
}
}
}
},
"400": {
"description": "Missing Mandatory fields"
}
},
"security": [
{
"admin_api_key": []
}
]
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 211
|
.json
| null | null | null | null | null |
openapi_spec
|
paths
|
[
"/gsm/delete"
] | null | null | null | null |
pub struct EliminationEventResponse {
pub labels_with_status: Vec<LabelWithStatusEliminationEventResponse>,
}
|
crates/router/src/core/payments/routing/utils.rs
|
router
|
struct_definition
| 24
|
rust
|
EliminationEventResponse
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs
Public functions: 1
Public structs: 33
use common_enums::{enums, AttemptStatus, BankNames};
use common_utils::{
errors::ParsingError,
pii::{Email, IpAddress},
request::Method,
types::{FloatMajorUnit, MinorUnit},
};
use error_stack::ResultExt;
use hyperswitch_domain_models::{
payment_method_data::{BankRedirectData, PayLaterData, PaymentMethodData, WalletData},
router_data::{ConnectorAuthType, ErrorResponse, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::ResponseId,
router_response_types::{
MandateReference, PaymentsResponseData, RedirectForm, RefundsResponseData,
},
types::{self},
};
use hyperswitch_interfaces::{
consts::{NO_ERROR_CODE, NO_ERROR_MESSAGE},
errors,
};
use masking::{ExposeInterface, Secret};
use serde::{Deserialize, Serialize};
use url::Url;
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
self, AddressDetailsData, CardData as _, PaymentsAuthorizeRequestData, RouterData as _,
},
};
#[derive(Debug, Serialize)]
pub struct MultisafepayRouterData<T> {
amount: MinorUnit,
router_data: T,
}
impl<T> From<(MinorUnit, T)> for MultisafepayRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "lowercase")]
pub enum Type {
Direct,
Redirect,
}
#[derive(Clone, Debug, Eq, Hash, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum Gateway {
Amex,
CreditCard,
Discover,
Maestro,
MasterCard,
Visa,
Klarna,
Googlepay,
Paypal,
Ideal,
Giropay,
Trustly,
Alipay,
#[serde(rename = "WECHAT")]
WeChatPay,
Eps,
MbWay,
#[serde(rename = "DIRECTBANK")]
Sofort,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Coupons {
pub allow: Option<Vec<Secret<String>>>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Mistercash {
pub mobile_pay_button_position: Option<String>,
pub disable_mobile_pay_button: Option<String>,
pub qr_only: Option<String>,
pub qr_size: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "UPPERCASE")]
pub struct Gateways {
pub mistercash: Option<Mistercash>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Settings {
pub coupons: Option<Coupons>,
pub gateways: Option<Gateways>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct PaymentOptions {
pub notification_url: Option<String>,
pub notification_method: Option<String>,
pub redirect_url: String,
pub cancel_url: String,
pub close_window: Option<bool>,
pub settings: Option<Settings>,
pub template_id: Option<String>,
pub allowed_countries: Option<Vec<String>>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Browser {
pub javascript_enabled: Option<bool>,
pub java_enabled: Option<bool>,
pub cookies_enabled: Option<bool>,
pub language: Option<String>,
pub screen_color_depth: Option<i32>,
pub screen_height: Option<i32>,
pub screen_width: Option<i32>,
pub time_zone: Option<i32>,
pub user_agent: Option<String>,
pub platform: Option<String>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct Customer {
pub browser: Option<Browser>,
pub locale: Option<String>,
pub ip_address: Option<Secret<String, IpAddress>>,
pub forward_ip: Option<Secret<String, IpAddress>>,
pub first_name: Option<Secret<String>>,
pub last_name: Option<Secret<String>>,
pub gender: Option<Secret<String>>,
pub birthday: Option<Secret<String>>,
pub address1: Option<Secret<String>>,
pub address2: Option<Secret<String>>,
pub house_number: Option<Secret<String>>,
pub zip_code: Option<Secret<String>>,
pub city: Option<String>,
pub state: Option<String>,
pub country: Option<String>,
pub phone: Option<Secret<String>>,
pub email: Option<Email>,
pub user_agent: Option<String>,
pub referrer: Option<String>,
pub reference: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct CardInfo {
pub card_number: Option<cards::CardNumber>,
pub card_holder_name: Option<Secret<String>>,
pub card_expiry_date: Option<Secret<i32>>,
pub card_cvc: Option<Secret<String>>,
pub flexible_3d: Option<bool>,
pub moto: Option<bool>,
pub term_url: Option<String>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct GpayInfo {
pub payment_token: Option<Secret<String>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
pub struct PayLaterInfo {
pub email: Option<Email>,
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum GatewayInfo {
Card(CardInfo),
Wallet(WalletInfo),
PayLater(PayLaterInfo),
BankRedirect(BankRedirectInfo),
}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum WalletInfo {
GooglePay(GpayInfo),
Alipay(AlipayInfo),
WeChatPay(WeChatPayInfo),
MbWay(MbWayInfo),
}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct MbWayInfo {}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct WeChatPayInfo {}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct AlipayInfo {}
#[derive(Clone, Debug, Eq, PartialEq, Serialize)]
#[serde(untagged)]
pub enum BankRedirectInfo {
Ideal(IdealInfo),
Trustly(TrustlyInfo),
Eps(EpsInfo),
Sofort(SofortInfo),
}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct SofortInfo {}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct EpsInfo {}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct TrustlyInfo {}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub struct IdealInfo {
pub issuer_id: MultisafepayBankNames,
}
#[derive(Debug, Clone, Serialize, Eq, PartialEq)]
pub enum MultisafepayBankNames {
#[serde(rename = "0031")]
AbnAmro,
#[serde(rename = "0761")]
AsnBank,
#[serde(rename = "4371")]
Bunq,
#[serde(rename = "0721")]
Ing,
#[serde(rename = "0801")]
Knab,
#[serde(rename = "9926")]
N26,
#[serde(rename = "9927")]
NationaleNederlanden,
#[serde(rename = "0021")]
Rabobank,
#[serde(rename = "0771")]
Regiobank,
#[serde(rename = "1099")]
Revolut,
#[serde(rename = "0751")]
SnsBank,
#[serde(rename = "0511")]
TriodosBank,
#[serde(rename = "0161")]
VanLanschot,
#[serde(rename = "0806")]
Yoursafe,
#[serde(rename = "1235")]
Handelsbanken,
}
impl TryFrom<&BankNames> for MultisafepayBankNames {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(bank: &BankNames) -> Result<Self, Self::Error> {
match bank {
BankNames::AbnAmro => Ok(Self::AbnAmro),
BankNames::AsnBank => Ok(Self::AsnBank),
BankNames::Bunq => Ok(Self::Bunq),
BankNames::Ing => Ok(Self::Ing),
BankNames::Knab => Ok(Self::Knab),
BankNames::N26 => Ok(Self::N26),
BankNames::NationaleNederlanden => Ok(Self::NationaleNederlanden),
BankNames::Rabobank => Ok(Self::Rabobank),
BankNames::Regiobank => Ok(Self::Regiobank),
BankNames::Revolut => Ok(Self::Revolut),
BankNames::SnsBank => Ok(Self::SnsBank),
BankNames::TriodosBank => Ok(Self::TriodosBank),
BankNames::VanLanschot => Ok(Self::VanLanschot),
BankNames::Yoursafe => Ok(Self::Yoursafe),
BankNames::Handelsbanken => Ok(Self::Handelsbanken),
BankNames::AmericanExpress
| BankNames::AffinBank
| BankNames::AgroBank
| BankNames::AllianceBank
| BankNames::AmBank
| BankNames::BankOfAmerica
| BankNames::BankOfChina
| BankNames::BankIslam
| BankNames::BankMuamalat
| BankNames::BankRakyat
| BankNames::BankSimpananNasional
| BankNames::Barclays
| BankNames::BlikPSP
| BankNames::CapitalOne
| BankNames::Chase
| BankNames::Citi
| BankNames::CimbBank
| BankNames::Discover
| BankNames::NavyFederalCreditUnion
| BankNames::PentagonFederalCreditUnion
| BankNames::SynchronyBank
| BankNames::WellsFargo
| BankNames::HongLeongBank
| BankNames::HsbcBank
| BankNames::KuwaitFinanceHouse
| BankNames::Moneyou
| BankNames::ArzteUndApothekerBank
| BankNames::AustrianAnadiBankAg
| BankNames::BankAustria
| BankNames::Bank99Ag
| BankNames::BankhausCarlSpangler
| BankNames::BankhausSchelhammerUndSchatteraAg
| BankNames::BankMillennium
| BankNames::BankPEKAOSA
| BankNames::BawagPskAg
| BankNames::BksBankAg
| BankNames::BrullKallmusBankAg
| BankNames::BtvVierLanderBank
| BankNames::CapitalBankGraweGruppeAg
| BankNames::CeskaSporitelna
| BankNames::Dolomitenbank
| BankNames::EasybankAg
| BankNames::EPlatbyVUB
| BankNames::ErsteBankUndSparkassen
| BankNames::FrieslandBank
| BankNames::HypoAlpeadriabankInternationalAg
| BankNames::HypoNoeLbFurNiederosterreichUWien
| BankNames::HypoOberosterreichSalzburgSteiermark
| BankNames::HypoTirolBankAg
| BankNames::HypoVorarlbergBankAg
| BankNames::HypoBankBurgenlandAktiengesellschaft
| BankNames::KomercniBanka
| BankNames::MBank
| BankNames::MarchfelderBank
| BankNames::Maybank
| BankNames::OberbankAg
| BankNames::OsterreichischeArzteUndApothekerbank
| BankNames::OcbcBank
| BankNames::PayWithING
| BankNames::PlaceZIPKO
| BankNames::PlatnoscOnlineKartaPlatnicza
| BankNames::PosojilnicaBankEGen
| BankNames::PostovaBanka
| BankNames::PublicBank
| BankNames::RaiffeisenBankengruppeOsterreich
| BankNames::RhbBank
| BankNames::SchelhammerCapitalBankAg
| BankNames::StandardCharteredBank
| BankNames::SchoellerbankAg
| BankNames::SpardaBankWien
| BankNames::SporoPay
| BankNames::SantanderPrzelew24
| BankNames::TatraPay
| BankNames::Viamo
| BankNames::VolksbankGruppe
| BankNames::VolkskreditbankAg
| BankNames::VrBankBraunau
| BankNames::UobBank
| BankNames::PayWithAliorBank
| BankNames::BankiSpoldzielcze
| BankNames::PayWithInteligo
| BankNames::BNPParibasPoland
| BankNames::BankNowySA
| BankNames::CreditAgricole
| BankNames::PayWithBOS
| BankNames::PayWithCitiHandlowy
| BankNames::PayWithPlusBank
| BankNames::ToyotaBank
| BankNames::VeloBank
| BankNames::ETransferPocztowy24
| BankNames::PlusBank
| BankNames::EtransferPocztowy24
| BankNames::BankiSpbdzielcze
| BankNames::BankNowyBfgSa
| BankNames::GetinBank
| BankNames::Blik
| BankNames::NoblePay
| BankNames::IdeaBank
| BankNames::EnveloBank
| BankNames::NestPrzelew
| BankNames::MbankMtransfer
| BankNames::Inteligo
| BankNames::PbacZIpko
| BankNames::BnpParibas
| BankNames::BankPekaoSa
| BankNames::VolkswagenBank
| BankNames::AliorBank
| BankNames::Boz
| BankNames::BangkokBank
| BankNames::KrungsriBank
| BankNames::KrungThaiBank
| BankNames::TheSiamCommercialBank
| BankNames::KasikornBank
| BankNames::OpenBankSuccess
| BankNames::OpenBankFailure
| BankNames::OpenBankCancelled
| BankNames::Aib
| BankNames::BankOfScotland
| BankNames::DanskeBank
| BankNames::FirstDirect
| BankNames::FirstTrust
| BankNames::Halifax
| BankNames::Lloyds
| BankNames::Monzo
| BankNames::NatWest
| BankNames::NationwideBank
| BankNames::RoyalBankOfScotland
| BankNames::Starling
| BankNames::TsbBank
| BankNames::TescoBank
| BankNames::UlsterBank => Err(Into::into(errors::ConnectorError::NotSupported {
message: String::from("BankRedirect"),
connector: "Multisafepay",
})),
}
}
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
pub struct DeliveryObject {
first_name: Secret<String>,
last_name: Secret<String>,
address1: Secret<String>,
house_number: Secret<String>,
zip_code: Secret<String>,
city: String,
country: api_models::enums::CountryAlpha2,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct DefaultObject {
shipping_taxed: bool,
rate: f64,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct TaxObject {
pub default: DefaultObject,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct CheckoutOptions {
pub validate_cart: Option<bool>,
pub tax_tables: TaxObject,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct Item {
pub name: String,
pub unit_price: FloatMajorUnit,
pub description: Option<String>,
pub quantity: i64,
}
#[derive(Clone, Debug, PartialEq, Deserialize, Serialize)]
pub struct ShoppingCart {
pub items: Vec<Item>,
}
#[serde_with::skip_serializing_none]
#[derive(Clone, Debug, PartialEq, Serialize)]
pub struct MultisafepayPaymentsRequest {
#[serde(rename = "type")]
pub payment_type: Type,
pub gateway: Option<Gateway>,
pub order_id: String,
pub currency: String,
pub amount: MinorUnit,
pub description: String,
pub payment_options: Option<PaymentOptions>,
pub customer: Option<Customer>,
pub gateway_info: Option<GatewayInfo>,
pub delivery: Option<DeliveryObject>,
pub checkout_options: Option<CheckoutOptions>,
pub shopping_cart: Option<ShoppingCart>,
pub items: Option<String>,
pub recurring_model: Option<MandateType>,
pub recurring_id: Option<Secret<String>>,
pub capture: Option<String>,
pub days_active: Option<i32>,
pub seconds_active: Option<i32>,
pub var1: Option<String>,
pub var2: Option<String>,
pub var3: Option<String>,
}
impl TryFrom<utils::CardIssuer> for Gateway {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(issuer: utils::CardIssuer) -> Result<Self, Self::Error> {
match issuer {
utils::CardIssuer::AmericanExpress => Ok(Self::Amex),
utils::CardIssuer::Master => Ok(Self::MasterCard),
utils::CardIssuer::Maestro => Ok(Self::Maestro),
utils::CardIssuer::Discover => Ok(Self::Discover),
utils::CardIssuer::Visa => Ok(Self::Visa),
utils::CardIssuer::DinersClub
| utils::CardIssuer::JCB
| utils::CardIssuer::CarteBlanche
| utils::CardIssuer::CartesBancaires => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("Multisafe pay"),
)
.into()),
}
}
}
impl TryFrom<&MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>>
for MultisafepayPaymentsRequest
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &MultisafepayRouterData<&types::PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
let payment_type = match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref _ccard) => Type::Direct,
PaymentMethodData::MandatePayment => Type::Direct,
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletData::GooglePay(_) => Type::Direct,
WalletData::PaypalRedirect(_) => Type::Redirect,
WalletData::AliPayRedirect(_) => Type::Redirect,
WalletData::WeChatPayRedirect(_) => Type::Redirect,
WalletData::MbWayRedirect(_) => Type::Redirect,
WalletData::AliPayQr(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
},
PaymentMethodData::BankRedirect(ref bank_data) => match bank_data {
BankRedirectData::Giropay { .. } => Type::Redirect,
BankRedirectData::Ideal { .. } => Type::Direct,
BankRedirectData::Trustly { .. } => Type::Redirect,
BankRedirectData::Eps { .. } => Type::Redirect,
BankRedirectData::Sofort { .. } => Type::Redirect,
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?
}
},
PaymentMethodData::PayLater(ref _paylater) => Type::Redirect,
_ => Type::Redirect,
};
let gateway = match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => {
Some(Gateway::try_from(ccard.get_card_issuer()?)?)
}
PaymentMethodData::Wallet(ref wallet_data) => Some(match wallet_data {
WalletData::GooglePay(_) => Gateway::Googlepay,
WalletData::PaypalRedirect(_) => Gateway::Paypal,
WalletData::AliPayRedirect(_) => Gateway::Alipay,
WalletData::WeChatPayRedirect(_) => Gateway::WeChatPay,
WalletData::MbWayRedirect(_) => Gateway::MbWay,
WalletData::AliPayQr(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
}),
PaymentMethodData::BankRedirect(ref bank_data) => Some(match bank_data {
BankRedirectData::Giropay { .. } => Gateway::Giropay,
BankRedirectData::Ideal { .. } => Gateway::Ideal,
BankRedirectData::Trustly { .. } => Gateway::Trustly,
BankRedirectData::Eps { .. } => Gateway::Eps,
BankRedirectData::Sofort { .. } => Gateway::Sofort,
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?
}
}),
PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect {}) => Some(Gateway::Klarna),
PaymentMethodData::MandatePayment => None,
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?
}
};
let description = item.router_data.get_description()?;
let payment_options = PaymentOptions {
notification_url: None,
redirect_url: item.router_data.request.get_router_return_url()?,
cancel_url: item.router_data.request.get_router_return_url()?,
close_window: None,
notification_method: None,
settings: None,
template_id: None,
allowed_countries: None,
};
let customer = Customer {
browser: None,
locale: None,
ip_address: None,
forward_ip: None,
first_name: None,
last_name: None,
gender: None,
birthday: None,
address1: None,
address2: None,
house_number: None,
zip_code: None,
city: None,
state: None,
country: None,
phone: None,
email: item.router_data.request.email.clone(),
user_agent: None,
referrer: None,
reference: Some(item.router_data.connector_request_reference_id.clone()),
};
let billing_address = item
.router_data
.get_billing()?
.address
.as_ref()
.ok_or_else(utils::missing_field_err("billing.address"))?;
let first_name = billing_address.get_first_name()?;
let delivery = DeliveryObject {
first_name: first_name.clone(),
last_name: billing_address
.get_last_name()
.unwrap_or(first_name)
.clone(),
address1: billing_address.get_line1()?.to_owned(),
house_number: billing_address.get_line2()?.to_owned(),
zip_code: billing_address.get_zip()?.to_owned(),
city: billing_address.get_city()?.to_owned(),
country: billing_address.get_country()?.to_owned(),
};
let gateway_info = match item.router_data.request.payment_method_data {
PaymentMethodData::Card(ref ccard) => Some(GatewayInfo::Card(CardInfo {
card_number: Some(ccard.card_number.clone()),
card_expiry_date: Some(Secret::new(
(format!(
"{}{}",
ccard.get_card_expiry_year_2_digit()?.expose(),
ccard.card_exp_month.clone().expose()
))
.parse::<i32>()
.unwrap_or_default(),
)),
card_cvc: Some(ccard.card_cvc.clone()),
card_holder_name: None,
flexible_3d: None,
moto: None,
term_url: None,
})),
PaymentMethodData::Wallet(ref wallet_data) => match wallet_data {
WalletData::GooglePay(ref google_pay) => {
Some(GatewayInfo::Wallet(WalletInfo::GooglePay({
GpayInfo {
payment_token: Some(Secret::new(
google_pay
.tokenization_data
.get_encrypted_google_pay_token()
.change_context(errors::ConnectorError::MissingRequiredField {
field_name: "google_pay_token",
})?
.clone(),
)),
}
})))
}
WalletData::AliPayRedirect(_) => {
Some(GatewayInfo::Wallet(WalletInfo::Alipay(AlipayInfo {})))
}
WalletData::PaypalRedirect(_) => None,
WalletData::WeChatPayRedirect(_) => {
Some(GatewayInfo::Wallet(WalletInfo::WeChatPay(WeChatPayInfo {})))
}
WalletData::MbWayRedirect(_) => {
Some(GatewayInfo::Wallet(WalletInfo::MbWay(MbWayInfo {})))
}
WalletData::AliPayQr(_)
| WalletData::AliPayHkRedirect(_)
| WalletData::AmazonPay(_)
| WalletData::AmazonPayRedirect(_)
| WalletData::Paysera(_)
| WalletData::Skrill(_)
| WalletData::BluecodeRedirect {}
| WalletData::MomoRedirect(_)
| WalletData::KakaoPayRedirect(_)
| WalletData::GoPayRedirect(_)
| WalletData::GcashRedirect(_)
| WalletData::ApplePay(_)
| WalletData::ApplePayRedirect(_)
| WalletData::ApplePayThirdPartySdk(_)
| WalletData::DanaRedirect {}
| WalletData::GooglePayRedirect(_)
| WalletData::GooglePayThirdPartySdk(_)
| WalletData::MobilePayRedirect(_)
| WalletData::PaypalSdk(_)
| WalletData::Paze(_)
| WalletData::SamsungPay(_)
| WalletData::TwintRedirect {}
| WalletData::VippsRedirect {}
| WalletData::TouchNGoRedirect(_)
| WalletData::WeChatPayQr(_)
| WalletData::CashappQr(_)
| WalletData::SwishQr(_)
| WalletData::Mifinity(_)
| WalletData::RevolutPay(_) => Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?,
},
PaymentMethodData::PayLater(ref paylater) => {
Some(GatewayInfo::PayLater(PayLaterInfo {
email: Some(match paylater {
PayLaterData::KlarnaRedirect {} => item.router_data.get_billing_email()?,
PayLaterData::KlarnaSdk { token: _ }
| PayLaterData::AffirmRedirect {}
| PayLaterData::FlexitiRedirect {}
| PayLaterData::AfterpayClearpayRedirect {}
| PayLaterData::PayBrightRedirect {}
| PayLaterData::WalleyRedirect {}
| PayLaterData::AlmaRedirect {}
| PayLaterData::AtomeRedirect {}
| PayLaterData::BreadpayRedirect {} => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message(
"multisafepay",
),
))?
}
}),
}))
}
PaymentMethodData::BankRedirect(ref bank_redirect_data) => match bank_redirect_data {
BankRedirectData::Ideal { bank_name, .. } => Some(GatewayInfo::BankRedirect(
BankRedirectInfo::Ideal(IdealInfo {
issuer_id: MultisafepayBankNames::try_from(&bank_name.ok_or(
errors::ConnectorError::MissingRequiredField {
field_name: "ideal.bank_name",
},
)?)?,
}),
)),
BankRedirectData::Trustly { .. } => Some(GatewayInfo::BankRedirect(
BankRedirectInfo::Trustly(TrustlyInfo {}),
)),
BankRedirectData::Eps { .. } => {
Some(GatewayInfo::BankRedirect(BankRedirectInfo::Eps(EpsInfo {})))
}
BankRedirectData::Sofort { .. } => Some(GatewayInfo::BankRedirect(
BankRedirectInfo::Sofort(SofortInfo {}),
)),
BankRedirectData::BancontactCard { .. }
| BankRedirectData::Bizum { .. }
| BankRedirectData::Blik { .. }
| BankRedirectData::Eft { .. }
| BankRedirectData::Giropay { .. }
| BankRedirectData::Interac { .. }
| BankRedirectData::OnlineBankingCzechRepublic { .. }
| BankRedirectData::OnlineBankingFinland { .. }
| BankRedirectData::OnlineBankingPoland { .. }
| BankRedirectData::OnlineBankingSlovakia { .. }
| BankRedirectData::OpenBankingUk { .. }
| BankRedirectData::Przelewy24 { .. }
| BankRedirectData::OnlineBankingFpx { .. }
| BankRedirectData::OnlineBankingThailand { .. }
| BankRedirectData::LocalBankRedirect {} => None,
},
PaymentMethodData::MandatePayment => None,
PaymentMethodData::CardRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::NetworkToken(_)
| PaymentMethodData::CardDetailsForNetworkTransactionId(_) => {
Err(errors::ConnectorError::NotImplemented(
utils::get_unimplemented_payment_method_error_message("multisafepay"),
))?
}
};
Ok(Self {
payment_type,
gateway,
order_id: item.router_data.connector_request_reference_id.to_string(),
currency: item.router_data.request.currency.to_string(),
amount: item.amount,
description,
payment_options: Some(payment_options),
customer: Some(customer),
delivery: Some(delivery),
gateway_info,
checkout_options: None,
shopping_cart: None,
capture: None,
items: None,
recurring_model: if item.router_data.request.is_mandate_payment() {
Some(MandateType::Unscheduled)
} else {
None
},
recurring_id: item
.router_data
.request
.mandate_id
.clone()
.and_then(|mandate_ids| match mandate_ids.mandate_reference_id {
Some(api_models::payments::MandateReferenceId::ConnectorMandateId(
connector_mandate_ids,
)) => connector_mandate_ids
.get_connector_mandate_id()
.map(Secret::new),
_ => None,
}),
days_active: Some(30),
seconds_active: Some(259200),
|
crates/hyperswitch_connectors/src/connectors/multisafepay/transformers.rs#chunk0
|
hyperswitch_connectors
|
chunk
| 8,190
| null | null | null | null | null | null | null | null | null | null | null | null | null |
/// Panics if `json_payload` array does not contain one `GetPaymentIntentMetricRequest` element.
pub async fn get_profile_payment_intent_metrics(
state: web::Data<AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<[GetPaymentIntentMetricRequest; 1]>,
) -> impl Responder {
// safety: This shouldn't panic owing to the data type
#[allow(clippy::expect_used)]
let payload = json_payload
.into_inner()
.to_vec()
.pop()
.expect("Couldn't get GetPaymentIntentMetricRequest");
let flow = AnalyticsFlow::GetPaymentIntentMetrics;
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth: AuthenticationData, req, _| async move {
let org_id = auth.merchant_account.get_org_id();
let merchant_id = auth.merchant_account.get_id();
let profile_id = auth
.profile_id
.ok_or(report!(UserErrors::JwtProfileIdMissing))
.change_context(AnalyticsError::AccessForbiddenError)?;
let auth: AuthInfo = AuthInfo::ProfileLevel {
org_id: org_id.clone(),
merchant_id: merchant_id.clone(),
profile_ids: vec![profile_id.clone()],
};
let validator_response = request_validator(
AnalyticsRequest {
payment_intent: Some(req.clone()),
..Default::default()
},
&state,
)
.await?;
let ex_rates = validator_response;
analytics::payment_intents::get_metrics(&state.pool, &ex_rates, &auth, req)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/analytics.rs
|
router
|
function_signature
| 405
|
rust
| null | null | null | null |
get_profile_payment_intent_metrics
| null | null | null | null | null | null | null |
pub struct EbanxPayoutCreateRequest {
integration_key: Secret<String>,
external_reference: String,
country: String,
amount: FloatMajorUnit,
currency: Currency,
target: EbanxPayoutType,
target_account: Secret<String>,
payee: EbanxPayoutDetails,
}
|
crates/hyperswitch_connectors/src/connectors/ebanx/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 69
|
rust
|
EbanxPayoutCreateRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn get_decision_based_on_params(
state: &SessionState,
intent_status: enums::IntentStatus,
called_connector: enums::PaymentConnectorTransmission,
active_attempt_id: Option<id_type::GlobalAttemptId>,
revenue_recovery_data: &storage::revenue_recovery::RevenueRecoveryPaymentData,
payment_id: &id_type::GlobalPaymentId,
) -> RecoveryResult<Self> {
logger::info!("Entering get_decision_based_on_params");
Ok(match (intent_status, called_connector, active_attempt_id) {
(
enums::IntentStatus::Failed,
enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
None,
) => Self::Execute,
(
enums::IntentStatus::Processing,
enums::PaymentConnectorTransmission::ConnectorCallSucceeded,
Some(_),
) => {
let psync_data = revenue_recovery_core::api::call_psync_api(
state,
payment_id,
revenue_recovery_data,
)
.await
.change_context(errors::RecoveryError::PaymentCallFailed)
.attach_printable("Error while executing the Psync call")?;
let payment_attempt = psync_data.payment_attempt;
Self::Psync(payment_attempt.status, payment_attempt.get_id().clone())
}
(
enums::IntentStatus::Failed,
enums::PaymentConnectorTransmission::ConnectorCallUnsuccessful,
Some(_),
) => {
let psync_data = revenue_recovery_core::api::call_psync_api(
state,
payment_id,
revenue_recovery_data,
)
.await
.change_context(errors::RecoveryError::PaymentCallFailed)
.attach_printable("Error while executing the Psync call")?;
let payment_attempt = psync_data.payment_attempt;
let attempt_triggered_by = payment_attempt
.feature_metadata
.and_then(|metadata| {
metadata.revenue_recovery.map(|revenue_recovery_metadata| {
revenue_recovery_metadata.attempt_triggered_by
})
})
.get_required_value("Attempt Triggered By")
.change_context(errors::RecoveryError::ValueNotFound)?;
Self::ReviewForFailedPayment(attempt_triggered_by)
}
(enums::IntentStatus::Succeeded, _, _) => Self::ReviewForSuccessfulPayment,
_ => Self::InvalidDecision,
})
}
|
crates/router/src/core/revenue_recovery/types.rs
|
router
|
function_signature
| 492
|
rust
| null | null | null | null |
get_decision_based_on_params
| null | null | null | null | null | null | null |
pub struct TsysRouterData<T> {
pub amount: StringMinorUnit,
pub router_data: T,
}
|
crates/hyperswitch_connectors/src/connectors/tsys/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 25
|
rust
|
TsysRouterData
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn reinitialize_limbo_processes(
conn: &PgPooledConn,
ids: Vec<String>,
schedule_time: PrimitiveDateTime,
) -> StorageResult<usize> {
generics::generic_update::<<Self as HasTable>::Table, _, _>(
conn,
dsl::status
.eq(enums::ProcessTrackerStatus::ProcessStarted)
.and(dsl::id.eq_any(ids)),
(
dsl::status.eq(enums::ProcessTrackerStatus::Processing),
dsl::schedule_time.eq(schedule_time),
),
)
.await
}
|
crates/diesel_models/src/query/process_tracker.rs
|
diesel_models
|
function_signature
| 126
|
rust
| null | null | null | null |
reinitialize_limbo_processes
| null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.BlocklistRequest
{
"oneOf": [
{
"type": "object",
"required": [
"type",
"data"
],
"properties": {
"type": {
"type": "string",
"enum": [
"card_bin"
]
},
"data": {
"type": "string"
}
}
},
{
"type": "object",
"required": [
"type",
"data"
],
"properties": {
"type": {
"type": "string",
"enum": [
"fingerprint"
]
},
"data": {
"type": "string"
}
}
},
{
"type": "object",
"required": [
"type",
"data"
],
"properties": {
"type": {
"type": "string",
"enum": [
"extended_card_bin"
]
},
"data": {
"type": "string"
}
}
}
],
"discriminator": {
"propertyName": "type"
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 257
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"BlocklistRequest"
] | null | null | null | null |
impl ConnectorValidation for Volt {
//TODO: implement functions when support enabled
}
|
crates/hyperswitch_connectors/src/connectors/volt.rs
|
hyperswitch_connectors
|
impl_block
| 17
|
rust
| null |
Volt
|
ConnectorValidation for
|
impl ConnectorValidation for for Volt
| null | null | null | null | null | null | null | null |
pub async fn batch_insert(
reverse_lookups: Vec<Self>,
conn: &PgPooledConn,
) -> StorageResult<()> {
generics::generic_insert::<_, _, ReverseLookup>(conn, reverse_lookups).await?;
Ok(())
}
|
crates/diesel_models/src/query/reverse_lookup.rs
|
diesel_models
|
function_signature
| 54
|
rust
| null | null | null | null |
batch_insert
| null | null | null | null | null | null | null |
impl api::PaymentToken for Boku {}
|
crates/hyperswitch_connectors/src/connectors/boku.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Boku
|
api::PaymentToken for
|
impl api::PaymentToken for for Boku
| null | null | null | null | null | null | null | null |
File: crates/router/tests/connectors/bambora.rs
use std::str::FromStr;
use common_utils::types::MinorUnit;
use masking::Secret;
use router::types::{self, domain, storage::enums};
use crate::{
connector_auth,
utils::{self, ConnectorActions},
};
#[derive(Clone, Copy)]
struct BamboraTest;
impl ConnectorActions for BamboraTest {}
impl utils::Connector for BamboraTest {
fn get_data(&self) -> types::api::ConnectorData {
use router::connector::Bambora;
utils::construct_connector_data_old(
Box::new(Bambora::new()),
types::Connector::Bambora,
types::api::GetToken::Connector,
None,
)
}
fn get_auth_token(&self) -> types::ConnectorAuthType {
utils::to_connector_auth_type(
connector_auth::ConnectorAuthentication::new()
.bambora
.expect("Missing connector authentication configuration")
.into(),
)
}
fn get_name(&self) -> String {
"bambora".to_string()
}
}
static CONNECTOR: BamboraTest = BamboraTest {};
fn get_default_payment_authorize_data() -> Option<types::PaymentsAuthorizeData> {
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("4030000010001234").unwrap(),
card_exp_year: Secret::new("25".to_string()),
card_cvc: Secret::new("123".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
})
}
// Cards Positive Tests
// Creates a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_only_authorize_payment() {
let response = CONNECTOR
.authorize_payment(get_default_payment_authorize_data(), None)
.await
.expect("Authorize payment response");
assert_eq!(response.status, enums::AttemptStatus::Authorized);
}
// Captures a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_capture_authorized_payment() {
let response = CONNECTOR
.authorize_and_capture_payment(get_default_payment_authorize_data(), None, None)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// 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(
get_default_payment_authorize_data(),
Some(types::PaymentsCaptureData {
amount_to_capture: 50,
..utils::PaymentCaptureType::default().0
}),
None,
)
.await
.expect("Capture payment response");
assert_eq!(response.status, enums::AttemptStatus::Charged);
}
// 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(get_default_payment_authorize_data(), None)
.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 {
mandate_id: None,
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
capture_method: Some(diesel_models::enums::CaptureMethod::Manual),
sync_type: types::SyncRequestType::SinglePaymentSync,
connector_meta: None,
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
integrity_object: None,
amount: MinorUnit::new(100),
..Default::default()
}),
None,
)
.await
.expect("PSync response");
assert_eq!(response.status, enums::AttemptStatus::Authorized,);
}
// Voids a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_void_authorized_payment() {
let response = CONNECTOR
.authorize_and_void_payment(
get_default_payment_authorize_data(),
Some(types::PaymentsCancelData {
connector_transaction_id: String::from(""),
cancellation_reason: Some("requested_by_customer".to_string()),
..Default::default()
}),
None,
)
.await
.expect("Void payment response");
assert_eq!(response.status, enums::AttemptStatus::Voided);
}
// 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(get_default_payment_authorize_data(), None, None, None)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Partially refunds a payment using the manual capture flow (Non 3DS).
#[actix_web::test]
async fn should_partially_refund_manually_captured_payment() {
let response = CONNECTOR
.capture_payment_and_refund(
get_default_payment_authorize_data(),
None,
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
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(get_default_payment_authorize_data(), None, None, None)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Creates a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_make_payment() {
let authorize_response = CONNECTOR
.make_payment(get_default_payment_authorize_data(), None)
.await
.unwrap();
assert_eq!(authorize_response.status, enums::AttemptStatus::Charged);
}
// Synchronizes a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_auto_captured_payment() {
let authorize_response = CONNECTOR
.make_payment(get_default_payment_authorize_data(), None)
.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 response = CONNECTOR
.psync_retry_till_status_matches(
enums::AttemptStatus::Charged,
Some(types::PaymentsSyncData {
mandate_id: None,
connector_transaction_id: types::ResponseId::ConnectorTransactionId(
txn_id.unwrap(),
),
encoded_data: None,
capture_method: Some(enums::CaptureMethod::Automatic),
sync_type: types::SyncRequestType::SinglePaymentSync,
connector_meta: None,
payment_method_type: None,
currency: enums::Currency::USD,
payment_experience: None,
integrity_object: None,
amount: MinorUnit::new(100),
..Default::default()
}),
None,
)
.await
.unwrap();
assert_eq!(response.status, enums::AttemptStatus::Charged,);
}
// Refunds a payment using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_refund_auto_captured_payment() {
let response = CONNECTOR
.make_payment_and_refund(get_default_payment_authorize_data(), None, None)
.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 refund_response = CONNECTOR
.make_payment_and_refund(
get_default_payment_authorize_data(),
Some(types::RefundsData {
refund_amount: 50,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
refund_response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Synchronizes a refund using the automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_sync_refund() {
let refund_response = CONNECTOR
.make_payment_and_refund(get_default_payment_authorize_data(), None, None)
.await
.unwrap();
let response = CONNECTOR
.rsync_retry_till_status_matches(
enums::RefundStatus::Success,
refund_response.response.unwrap().connector_refund_id,
None,
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success,
);
}
// Cards Negative scenarios
// Creates a payment with incorrect card number.
#[actix_web::test]
async fn should_fail_payment_for_incorrect_card_number() {
let response = CONNECTOR
.make_payment(
Some(types::PaymentsAuthorizeData {
payment_method_data: domain::PaymentMethodData::Card(domain::Card {
card_number: cards::CardNumber::from_str("1234567891011").unwrap(),
card_exp_year: Secret::new("25".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().message,
"Invalid Card Number".to_string(),
);
}
// Creates a payment with incorrect CVC.
#[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_exp_year: Secret::new("25".to_string()),
card_cvc: Secret::new("12345".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().reason,
Some(r#"[{"field":"card:cvd","message":"Invalid card CVD"},{"field":"card:cvd","message":"Invalid card CVD"}]"#.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()),
card_number: cards::CardNumber::from_str("4030000010001234").unwrap(),
card_exp_year: Secret::new("25".to_string()),
card_cvc: Secret::new("123".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().reason,
Some(r#"[{"field":"card:expiry_month","message":"Invalid expiry date"}]"#.to_string())
);
}
// 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()),
card_number: cards::CardNumber::from_str("4030000010001234").unwrap(),
card_cvc: Secret::new("123".to_string()),
..utils::CCardType::default().0
}),
..utils::PaymentAuthorizeType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap_err().reason,
Some(r#"[{"field":"card:expiry_year","message":"Invalid expiration year"}]"#.to_string())
);
}
// Voids a payment using automatic capture flow (Non 3DS).
#[actix_web::test]
async fn should_fail_void_payment_for_auto_capture() {
let authorize_response = CONNECTOR
.make_payment(get_default_payment_authorize_data(), None)
.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, None)
.await
.unwrap();
assert_eq!(
void_response.response.unwrap_err().message,
"Transaction cannot be adjusted"
);
}
// 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("123456789".to_string(), None, None)
.await
.unwrap();
assert_eq!(
capture_response.response.unwrap_err().message,
String::from("Missing or invalid payment information - Please validate all required payment information.")
);
}
// Refunds a payment with refund amount higher than payment amount.
#[actix_web::test]
async fn should_succeed_for_refund_amount_higher_than_payment_amount() {
let response = CONNECTOR
.make_payment_and_refund(
get_default_payment_authorize_data(),
Some(types::RefundsData {
refund_amount: 150,
..utils::PaymentRefundType::default().0
}),
None,
)
.await
.unwrap();
assert_eq!(
response.response.unwrap().refund_status,
enums::RefundStatus::Success
);
}
|
crates/router/tests/connectors/bambora.rs
|
router
|
full_file
| 3,353
| null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/diesel_models/src/ephemeral_key.rs
Public functions: 1
Public structs: 4
#[cfg(feature = "v2")]
use masking::{PeekInterface, Secret};
#[cfg(feature = "v2")]
pub struct ClientSecretTypeNew {
pub id: common_utils::id_type::ClientSecretId,
pub merchant_id: common_utils::id_type::MerchantId,
pub secret: Secret<String>,
pub resource_id: common_utils::types::authentication::ResourceId,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct ClientSecretType {
pub id: common_utils::id_type::ClientSecretId,
pub merchant_id: common_utils::id_type::MerchantId,
pub resource_id: common_utils::types::authentication::ResourceId,
pub created_at: time::PrimitiveDateTime,
pub expires: time::PrimitiveDateTime,
pub secret: Secret<String>,
}
#[cfg(feature = "v2")]
impl ClientSecretType {
pub fn generate_secret_key(&self) -> String {
format!("cs_{}", self.secret.peek())
}
}
pub struct EphemeralKeyNew {
pub id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: common_utils::id_type::CustomerId,
pub secret: String,
}
#[derive(Clone, Debug, serde::Serialize, serde::Deserialize)]
pub struct EphemeralKey {
pub id: String,
pub merchant_id: common_utils::id_type::MerchantId,
pub customer_id: common_utils::id_type::CustomerId,
pub created_at: i64,
pub expires: i64,
pub secret: String,
}
impl common_utils::events::ApiEventMetric for EphemeralKey {
fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> {
Some(common_utils::events::ApiEventsType::Miscellaneous)
}
}
|
crates/diesel_models/src/ephemeral_key.rs
|
diesel_models
|
full_file
| 423
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct CardNetworkTokenizeExecutor<'a, D> {
pub state: &'a SessionState,
pub merchant_account: &'a domain::MerchantAccount,
key_store: &'a domain::MerchantKeyStore,
data: &'a D,
customer: &'a domain_request_types::CustomerDetails,
}
|
crates/router/src/core/payment_methods/tokenize.rs
|
router
|
struct_definition
| 66
|
rust
|
CardNetworkTokenizeExecutor
| null | null | null | null | null | null | null | null | null | null | null |
impl PaymentIntents {
pub fn server(state: routes::AppState) -> Scope {
let mut route = web::scope("/payment_intents").app_data(web::Data::new(state));
#[cfg(feature = "olap")]
{
route = route.service(web::resource("/list").route(web::get().to(payment_intent_list)))
}
route = route
.service(web::resource("").route(web::post().to(payment_intents_create)))
.service(
web::resource("/sync")
.route(web::post().to(payment_intents_retrieve_with_gateway_creds)),
)
.service(
web::resource("/{payment_id}")
.route(web::get().to(payment_intents_retrieve))
.route(web::post().to(payment_intents_update)),
)
.service(
web::resource("/{payment_id}/confirm")
.route(web::post().to(payment_intents_confirm)),
)
.service(
web::resource("/{payment_id}/capture")
.route(web::post().to(payment_intents_capture)),
)
.service(
web::resource("/{payment_id}/cancel").route(web::post().to(payment_intents_cancel)),
);
route
}
}
|
crates/router/src/compatibility/stripe/app.rs
|
router
|
impl_block
| 260
|
rust
| null |
PaymentIntents
| null |
impl PaymentIntents
| null | null | null | null | null | null | null | null |
pub fn validate(&self) -> Result<(), ApplicationError> {
common_utils::fp_utils::when(self.host.is_default_or_empty(), || {
Err(ApplicationError::InvalidConfigurationValueError(
"server host must not be empty".into(),
))
})
}
|
crates/scheduler/src/configs/validations.rs
|
scheduler
|
function_signature
| 57
|
rust
| null | null | null | null |
validate
| null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.FrmAction
{
"type": "string",
"enum": [
"cancel_txn",
"auto_refund",
"manual_review"
]
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 44
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"FrmAction"
] | null | null | null | null |
impl MerchantAccount {
#[cfg(feature = "v1")]
/// Get the unique identifier of MerchantAccount
pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
&self.merchant_id
}
#[cfg(feature = "v2")]
/// Get the unique identifier of MerchantAccount
pub fn get_id(&self) -> &common_utils::id_type::MerchantId {
&self.id
}
/// Get the organization_id from MerchantAccount
pub fn get_org_id(&self) -> &common_utils::id_type::OrganizationId {
&self.organization_id
}
/// Get the merchant_details from MerchantAccount
pub fn get_merchant_details(&self) -> &OptionalEncryptableValue {
&self.merchant_details
}
/// Extract merchant_tax_registration_id from merchant_details
pub fn get_merchant_tax_registration_id(&self) -> Option<Secret<String>> {
self.merchant_details.as_ref().and_then(|details| {
details
.get_inner()
.peek()
.get("merchant_tax_registration_id")
.and_then(|id| id.as_str().map(|s| Secret::new(s.to_string())))
})
}
/// Check whether the merchant account is a platform account
pub fn is_platform_account(&self) -> bool {
matches!(
self.merchant_account_type,
common_enums::MerchantAccountType::Platform
)
}
}
|
crates/hyperswitch_domain_models/src/merchant_account.rs
|
hyperswitch_domain_models
|
impl_block
| 311
|
rust
| null |
MerchantAccount
| null |
impl MerchantAccount
| null | null | null | null | null | null | null | null |
File: crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs
use std::collections::HashSet;
use api_models::analytics::{
disputes::{DisputeDimensions, DisputeFilters, DisputeMetricsBucketIdentifier},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::DisputeMetricRow;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(super) struct TotalDisputeLostAmount {}
#[async_trait::async_trait]
impl<T> super::DisputeMetric<T> for TotalDisputeLostAmount
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
PrimitiveDateTime: ToSql<T>,
AnalyticsCollection: ToSql<T>,
Granularity: GroupByClause<T>,
Aggregate<&'static str>: ToSql<T>,
Window<&'static str>: ToSql<T>,
{
async fn load_metrics(
&self,
dimensions: &[DisputeDimensions],
auth: &AuthInfo,
filters: &DisputeFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(DisputeMetricsBucketIdentifier, DisputeMetricRow)>>
where
T: AnalyticsDataSource + super::DisputeMetricAnalytics,
{
let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::Dispute);
for dim in dimensions.iter() {
query_builder.add_select_column(dim).switch()?;
}
query_builder
.add_select_column(Aggregate::Sum {
field: "dispute_amount",
alias: Some("total"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Min {
field: "created_at",
alias: Some("start_bucket"),
})
.switch()?;
query_builder
.add_select_column(Aggregate::Max {
field: "created_at",
alias: Some("end_bucket"),
})
.switch()?;
filters.set_filter_clause(&mut query_builder).switch()?;
auth.set_filter_clause(&mut query_builder).switch()?;
time_range
.set_filter_clause(&mut query_builder)
.attach_printable("Error filtering time range")
.switch()?;
for dim in dimensions.iter() {
query_builder.add_group_by_clause(dim).switch()?;
}
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.switch()?;
}
query_builder
.add_filter_clause("dispute_status", "dispute_lost")
.switch()?;
query_builder
.execute_query::<DisputeMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
DisputeMetricsBucketIdentifier::new(
i.dispute_stage.as_ref().map(|i| i.0),
i.connector.clone(),
i.currency.as_ref().map(|i| i.0),
TimeRange {
start_time: match (granularity, i.start_bucket) {
(Some(g), Some(st)) => g.clip_to_start(st)?,
_ => time_range.start_time,
},
end_time: granularity.as_ref().map_or_else(
|| Ok(time_range.end_time),
|g| i.end_bucket.map(|et| g.clip_to_end(et)).transpose(),
)?,
},
),
i,
))
})
.collect::<error_stack::Result<HashSet<_>, crate::query::PostProcessingError>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
|
crates/analytics/src/disputes/metrics/total_dispute_lost_amount.rs
|
analytics
|
full_file
| 851
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn schedule_refund_execution(
state: &SessionState,
refund: diesel_refund::Refund,
refund_type: api_models::refunds::RefundType,
merchant_context: &domain::MerchantContext,
payment_attempt: &storage::PaymentAttempt,
payment_intent: &storage::PaymentIntent,
merchant_connector_details: Option<common_types::domain::MerchantConnectorAuthDetails>,
) -> errors::RouterResult<diesel_refund::Refund> {
let db = &*state.store;
let runner = storage::ProcessTrackerRunner::RefundWorkflowRouter;
let task = "EXECUTE_REFUND";
let task_id = format!("{runner}_{task}_{}", refund.id.get_string_repr());
let refund_process = db
.find_process_by_id(&task_id)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to find the process id")?;
let result = match refund.refund_status {
enums::RefundStatus::Pending | enums::RefundStatus::ManualReview => {
match (refund.sent_to_gateway, refund_process) {
(false, None) => {
// Execute the refund task based on refund_type
match refund_type {
api_models::refunds::RefundType::Scheduled => {
add_refund_execute_task(db, &refund, runner)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Failed while pushing refund execute task to scheduler, refund_id: {}", refund.id.get_string_repr()))?;
Ok(refund)
}
api_models::refunds::RefundType::Instant => {
let update_refund =
if state.conf.merchant_id_auth.merchant_id_auth_enabled {
let merchant_connector_details =
match merchant_connector_details {
Some(details) => details,
None => {
return Err(report!(
errors::ApiErrorResponse::MissingRequiredField {
field_name: "merchant_connector_details"
}
));
}
};
Box::pin(internal_trigger_refund_to_gateway(
state,
&refund,
merchant_context,
payment_attempt,
payment_intent,
merchant_connector_details,
))
.await
} else {
Box::pin(trigger_refund_to_gateway(
state,
&refund,
merchant_context,
payment_attempt,
payment_intent,
))
.await
};
match update_refund {
Ok(updated_refund_data) => {
add_refund_sync_task(db, &updated_refund_data, runner)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!(
"Failed while pushing refund sync task in scheduler: refund_id: {}",
refund.id.get_string_repr()
))?;
Ok(updated_refund_data)
}
Err(err) => Err(err),
}
}
}
}
_ => {
// Sync the refund for status check
//[#300]: return refund status response
match refund_type {
api_models::refunds::RefundType::Scheduled => {
add_refund_sync_task(db, &refund, runner)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable_lazy(|| format!("Failed while pushing refund sync task in scheduler: refund_id: {}", refund.id.get_string_repr()))?;
Ok(refund)
}
api_models::refunds::RefundType::Instant => {
// [#255]: This is not possible in schedule_refund_execution as it will always be scheduled
// sync_refund_with_gateway(data, &refund).await
Ok(refund)
}
}
}
}
}
// [#255]: This is not allowed to be otherwise or all
_ => Ok(refund),
}?;
Ok(result)
}
|
crates/router/src/core/refunds_v2.rs
|
router
|
function_signature
| 826
|
rust
| null | null | null | null |
schedule_refund_execution
| null | null | null | null | null | null | null |
pub struct ProdIntent {
pub legal_business_name: Option<String>,
pub business_label: Option<String>,
pub business_location: Option<CountryAlpha2>,
pub display_name: Option<String>,
pub poc_email: Option<Secret<String>>,
pub business_type: Option<String>,
pub business_identifier: Option<String>,
pub business_website: Option<String>,
pub poc_name: Option<Secret<String>>,
pub poc_contact: Option<Secret<String>>,
pub comments: Option<String>,
pub is_completed: bool,
#[serde(default)]
pub product_type: MerchantProductType,
pub business_country_name: Option<String>,
}
|
crates/api_models/src/user/dashboard_metadata.rs
|
api_models
|
struct_definition
| 133
|
rust
|
ProdIntent
| null | null | null | null | null | null | null | null | null | null | null |
pub struct ProfileUpdate {
/// The name of profile
#[schema(max_length = 64)]
pub profile_name: Option<String>,
/// The URL to redirect after the completion of the operation
#[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")]
pub return_url: Option<common_utils::types::Url>,
/// A boolean value to indicate if payment response hash needs to be enabled
#[schema(default = true, example = true)]
pub enable_payment_response_hash: Option<bool>,
/// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated.
pub payment_response_hash_key: Option<String>,
/// A boolean value to indicate if redirect to merchant with http post needs to be enabled
#[schema(default = false, example = true)]
pub redirect_to_merchant_with_http_post: Option<bool>,
/// Webhook related details
pub webhook_details: Option<WebhookDetails>,
/// Metadata is useful for storing additional, unstructured information on an object.
#[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)]
pub metadata: Option<pii::SecretSerdeValue>,
/// Will be used to determine the time till which your payment will be active once the payment session starts
#[schema(value_type = Option<u32>, example = 900)]
pub order_fulfillment_time: Option<OrderFulfillmentTime>,
/// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment
#[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")]
pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>,
/// Verified Apple Pay domains for a particular profile
pub applepay_verified_domains: Option<Vec<String>>,
/// Client Secret Default expiry for all payments created under this profile
#[schema(example = 900)]
pub session_expiry: Option<u32>,
/// Default Payment Link config for all payment links created under this profile
pub payment_link_config: Option<BusinessPaymentLinkConfig>,
/// External 3DS authentication details
pub authentication_connector_details: Option<AuthenticationConnectorDetails>,
/// Merchant's config to support extended card info feature
pub extended_card_info_config: Option<ExtendedCardInfoConfig>,
// Whether to use the billing details passed when creating the intent as payment method billing
pub use_billing_as_payment_method_billing: Option<bool>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc)
#[schema(default = false, example = false)]
pub collect_billing_details_from_wallet_connector_if_required: Option<bool>,
/// A boolean value to indicate if customer shipping details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_shipping_details_from_wallet_connector: Option<bool>,
/// A boolean value to indicate if customer billing details needs to be collected from wallet
/// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc)
#[schema(default = false, example = false)]
pub always_collect_billing_details_from_wallet_connector: Option<bool>,
/// Indicates if the MIT (merchant initiated transaction) payments can be made connector
/// agnostic, i.e., MITs may be processed through different connector than CIT (customer
/// initiated transaction) based on the routing rules.
/// If set to `false`, MIT will go through the same connector as the CIT.
pub is_connector_agnostic_mit_enabled: Option<bool>,
/// Default payout link config
#[schema(value_type = Option<BusinessPayoutLinkConfig>)]
pub payout_link_config: Option<BusinessPayoutLinkConfig>,
/// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs.
#[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)]
pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>,
/// Merchant Connector id to be stored for tax_calculator connector
#[schema(value_type = Option<String>)]
pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>,
/// Indicates if tax_calculator connector is enabled or not.
/// If set to `true` tax_connector_id will be checked.
pub is_tax_connector_enabled: Option<bool>,
/// Indicates if network tokenization is enabled or not.
pub is_network_tokenization_enabled: Option<bool>,
/// Indicates if click to pay is enabled or not.
#[schema(default = false, example = false)]
pub is_click_to_pay_enabled: Option<bool>,
/// Product authentication ids
#[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)]
pub authentication_product_ids:
Option<common_types::payments::AuthenticationConnectorAccountMap>,
/// Card Testing Guard Configs
pub card_testing_guard_config: Option<CardTestingGuardConfig>,
///Indicates if clear pan retries is enabled or not.
pub is_clear_pan_retries_enabled: Option<bool>,
/// Indicates if debit routing is enabled or not
#[schema(value_type = Option<bool>)]
pub is_debit_routing_enabled: Option<bool>,
//Merchant country for the profile
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub merchant_business_country: Option<api_enums::CountryAlpha2>,
/// Indicates if external vault is enabled or not.
pub is_external_vault_enabled: Option<bool>,
/// External Vault Connector Details
pub external_vault_connector_details: Option<ExternalVaultConnectorDetails>,
/// Four-digit code assigned based on business type to determine processing fees and risk level
#[schema(value_type = Option<MerchantCategoryCode>, example = "5411")]
pub merchant_category_code: Option<api_enums::MerchantCategoryCode>,
/// Merchant country code.
/// This is a 3-digit ISO 3166-1 numeric country code that represents the country in which the merchant is registered or operates.
/// Merchants typically receive this value based on their business registration information or during onboarding via payment processors or acquiring banks.
/// It is used in payment processing, fraud detection, and regulatory compliance to determine regional rules and routing behavior.
#[schema(value_type = Option<MerchantCountryCode>, example = "840")]
pub merchant_country_code: Option<common_types::payments::MerchantCountryCode>,
/// Indicates the state of revenue recovery algorithm type
#[schema(value_type = Option<RevenueRecoveryAlgorithmType>, example = "cascading")]
pub revenue_recovery_retry_algorithm_type:
Option<common_enums::enums::RevenueRecoveryAlgorithmType>,
/// Enable split payments, i.e., split the amount between multiple payment methods
#[schema(value_type = Option<SplitTxnsEnabled>, default = "skip")]
pub split_txns_enabled: Option<common_enums::SplitTxnsEnabled>,
}
|
crates/api_models/src/admin.rs
|
api_models
|
struct_definition
| 1,710
|
rust
|
ProfileUpdate
| null | null | null | null | null | null | null | null | null | null | null |
pub fn make_dsl_input_for_payouts(
payout_data: &payouts::PayoutData,
) -> RoutingResult<dsl_inputs::BackendInput> {
let mandate = dsl_inputs::MandateData {
mandate_acceptance_type: None,
mandate_type: None,
payment_type: None,
};
let metadata = payout_data
.payouts
.metadata
.clone()
.map(|val| val.parse_value("routing_parameters"))
.transpose()
.change_context(errors::RoutingError::MetadataParsingError)
.attach_printable("Unable to parse routing_parameters from metadata of payouts")
.unwrap_or(None);
let payment = dsl_inputs::PaymentInput {
amount: payout_data.payouts.amount,
card_bin: None,
currency: payout_data.payouts.destination_currency,
authentication_type: None,
capture_method: None,
business_country: payout_data
.payout_attempt
.business_country
.map(api_enums::Country::from_alpha2),
billing_country: payout_data
.billing_address
.as_ref()
.and_then(|ba| ba.address.as_ref())
.and_then(|addr| addr.country)
.map(api_enums::Country::from_alpha2),
business_label: payout_data.payout_attempt.business_label.clone(),
setup_future_usage: None,
};
let payment_method = dsl_inputs::PaymentMethodInput {
payment_method: payout_data
.payouts
.payout_type
.map(api_enums::PaymentMethod::foreign_from),
payment_method_type: payout_data
.payout_method_data
.as_ref()
.map(api_enums::PaymentMethodType::foreign_from)
.or_else(|| {
payout_data.payment_method.as_ref().and_then(|pm| {
#[cfg(feature = "v1")]
{
pm.payment_method_type
}
#[cfg(feature = "v2")]
{
pm.payment_method_subtype
}
})
}),
card_network: None,
};
Ok(dsl_inputs::BackendInput {
mandate,
metadata,
payment,
payment_method,
acquirer_data: None,
customer_device_data: None,
issuer_data: None,
})
}
|
crates/router/src/core/payments/routing.rs
|
router
|
function_signature
| 493
|
rust
| null | null | null | null |
make_dsl_input_for_payouts
| null | null | null | null | null | null | null |
impl api::Payment for HyperswitchVault {}
|
crates/hyperswitch_connectors/src/connectors/hyperswitch_vault.rs
|
hyperswitch_connectors
|
impl_block
| 10
|
rust
| null |
HyperswitchVault
|
api::Payment for
|
impl api::Payment for for HyperswitchVault
| null | null | null | null | null | null | null | null |
impl std::fmt::Display for Op<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Op::Insert => f.write_str("insert"),
Op::Find => f.write_str("find"),
Op::Update(p_key, _, updated_by) => {
f.write_str(&format!("update_{p_key} for updated_by_{updated_by:?}"))
}
}
}
}
|
crates/storage_impl/src/redis/kv_store.rs
|
storage_impl
|
impl_block
| 103
|
rust
| null |
Op
|
std::fmt::Display for
|
impl std::fmt::Display for for Op
| null | null | null | null | null | null | null | null |
impl IncomingWebhook for Payone {
fn get_webhook_object_reference_id(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<ObjectReferenceId, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_event_type(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<IncomingWebhookEvent, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
fn get_webhook_resource_object(
&self,
_request: &IncomingWebhookRequestDetails<'_>,
) -> CustomResult<Box<dyn masking::ErasedMaskSerialize>, ConnectorError> {
Err(report!(ConnectorError::WebhooksNotImplemented))
}
}
|
crates/hyperswitch_connectors/src/connectors/payone.rs
|
hyperswitch_connectors
|
impl_block
| 173
|
rust
| null |
Payone
|
IncomingWebhook for
|
impl IncomingWebhook for for Payone
| null | null | null | null | null | null | null | null |
impl api::PaymentSession for Shift4 {}
|
crates/hyperswitch_connectors/src/connectors/shift4.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Shift4
|
api::PaymentSession for
|
impl api::PaymentSession for for Shift4
| null | null | null | null | null | null | null | null |
### Bug Fixes
- **users:** Fallback to fresh lineage context if cached role_id no longer matches ([#8593](https://github.com/juspay/hyperswitch/pull/8593)) ([`aaa4fca`](https://github.com/juspay/hyperswitch/commit/aaa4fca58d8eaab0eb0163aad226427eebf7c7cd))
### Refactors
- **dynamic_routing:** Make the dynamo configs optional ([#8589](https://github.com/juspay/hyperswitch/pull/8589)) ([`4048aa1`](https://github.com/juspay/hyperswitch/commit/4048aa16cadd98605b81aebc7543da50c36454b9))
### Miscellaneous Tasks
- **stripe:** Eps bank_name should be mandatory ([#8577](https://github.com/juspay/hyperswitch/pull/8577)) ([`fffaa53`](https://github.com/juspay/hyperswitch/commit/fffaa53a5fe4859bea607f2eb6bf866b4a20b949))
**Full Changelog:** [`2025.07.14.1...2025.07.15.0`](https://github.com/juspay/hyperswitch/compare/2025.07.14.1...2025.07.15.0)
- - -
## 2025.07.14.1
### Features
- **connector:** [AUTHORIZEDOTNET] Populated merchant required fields in setupmandate flow ([#8618](https://github.com/juspay/hyperswitch/pull/8618)) ([`cb8dff0`](https://github.com/juspay/hyperswitch/commit/cb8dff008c71586713973d350e7e3789e82085ec))
**Full Changelog:** [`2025.07.14.0...2025.07.14.1`](https://github.com/juspay/hyperswitch/compare/2025.07.14.0...2025.07.14.1)
- - -
## 2025.07.14.0
### Features
- **connector:**
- [AIRWALLEX] - Added Paypal, Trustly, Klarna , Atome, Blik Payment Methods ([#8475](https://github.com/juspay/hyperswitch/pull/8475)) ([`d5f5527`](https://github.com/juspay/hyperswitch/commit/d5f5527499c11ab427bd07c326cc294fc354f342))
- [payload] add webhook support ([#8558](https://github.com/juspay/hyperswitch/pull/8558)) ([`2fe3132`](https://github.com/juspay/hyperswitch/commit/2fe3132da8eedea39018e5c6afec9ab4dd49ddd6))
- **core:** Hyperswitch <|> UCS integration v2 ([#8439](https://github.com/juspay/hyperswitch/pull/8439)) ([`ae9feca`](https://github.com/juspay/hyperswitch/commit/ae9feca82cdc29ff442276284f2aeb4ad01e94ba))
- **payments:** Propagate additional payment method data for apple pay during MIT ([#7170](https://github.com/juspay/hyperswitch/pull/7170)) ([`0f70fc5`](https://github.com/juspay/hyperswitch/commit/0f70fc512c90e4d5603af7b965c137465999b73c))
### Refactors
- **cypress:** Update skip logic and test flow for cypress incremental auth tests ([#8594](https://github.com/juspay/hyperswitch/pull/8594)) ([`3c49871`](https://github.com/juspay/hyperswitch/commit/3c498714e76b400657fc0fc25b7559ca3dca1908))
**Full Changelog:** [`2025.07.11.0...2025.07.14.0`](https://github.com/juspay/hyperswitch/compare/2025.07.11.0...2025.07.14.0)
- - -
## 2025.07.11.0
### Miscellaneous Tasks
- Address Rust 1.88.0 clippy lints ([#8607](https://github.com/juspay/hyperswitch/pull/8607)) ([`b1c9be1`](https://github.com/juspay/hyperswitch/commit/b1c9be1600dbd897c32adcc2d8b98e77ec67c516))
**Full Changelog:** [`2025.07.10.0...2025.07.11.0`](https://github.com/juspay/hyperswitch/compare/2025.07.10.0...2025.07.11.0)
- - -
## 2025.07.10.0
### Refactors
- **connector:** Move connector mappings and endpoints to dedicated modules ([#8562](https://github.com/juspay/hyperswitch/pull/8562)) ([`99885b6`](https://github.com/juspay/hyperswitch/commit/99885b699d7524e87697f78608e6f2b36c9d8a8e))
**Full Changelog:** [`2025.07.09.0...2025.07.10.0`](https://github.com/juspay/hyperswitch/compare/2025.07.09.0...2025.07.10.0)
- - -
## 2025.07.09.0
### Features
- **connector:**
- [silverflow] template code ([#8553](https://github.com/juspay/hyperswitch/pull/8553)) ([`c322eb9`](https://github.com/juspay/hyperswitch/commit/c322eb9cabb2ca7a8ad0c3ed57192dde9bf7eaa4))
- [AUTHIPAY] Integrate cards non 3ds payments ([#8266](https://github.com/juspay/hyperswitch/pull/8266)) ([`ef42ad4`](https://github.com/juspay/hyperswitch/commit/ef42ad43120d8699876990718235b518fa5011ac))
### Bug Fixes
- **payment_method:** Update entity id used for Vault to global customer id ([#8380](https://github.com/juspay/hyperswitch/pull/8380)) ([`cf96c82`](https://github.com/juspay/hyperswitch/commit/cf96c826cad08ea84148238b73bd9ca2de8c0518))
### Refactors
- **routing:** Add conditional check for invoking DE routing flows ([#8559](https://github.com/juspay/hyperswitch/pull/8559)) ([`7508c80`](https://github.com/juspay/hyperswitch/commit/7508c801580f8d83b203b34165dacb6a3814d941))
**Full Changelog:** [`2025.07.08.0...2025.07.09.0`](https://github.com/juspay/hyperswitch/compare/2025.07.08.0...2025.07.09.0)
- - -
## 2025.07.08.0
### Features
- **connector:** [Celero] add Connector Template Code ([#8489](https://github.com/juspay/hyperswitch/pull/8489)) ([`dfed2be`](https://github.com/juspay/hyperswitch/commit/dfed2be2900a53f62a4903376004a264f9da25a8))
- **connectors:** [worldpayvantiv] add connector mandate support ([#8546](https://github.com/juspay/hyperswitch/pull/8546)) ([`de92973`](https://github.com/juspay/hyperswitch/commit/de92973b01c764474c52185842677e2d32058e8d))
- **cypress:** [worldpayvantiv] add cypress test ([#8234](https://github.com/juspay/hyperswitch/pull/8234)) ([`102f278`](https://github.com/juspay/hyperswitch/commit/102f2785199a2f66d9cd3428678f54ba3f015ff7))
- **payment-methods:** Create payment_token in vault confirm / do payment-confirm with temp token from session ([#8525](https://github.com/juspay/hyperswitch/pull/8525)) ([`4aca455`](https://github.com/juspay/hyperswitch/commit/4aca45531b1616a2a2cc028878a96793148dff7f))
**Full Changelog:** [`2025.07.07.0...2025.07.08.0`](https://github.com/juspay/hyperswitch/compare/2025.07.07.0...2025.07.08.0)
- - -
## 2025.07.07.0
### Features
- **connector:** [payload] introduce no-3ds cards ([#8545](https://github.com/juspay/hyperswitch/pull/8545)) ([`baad3f6`](https://github.com/juspay/hyperswitch/commit/baad3f6a37c1c0d948c415f281b6552c5b51e376))
- **core:** Hyperswitch <|> UCS Integration ([#8280](https://github.com/juspay/hyperswitch/pull/8280)) ([`f6574b7`](https://github.com/juspay/hyperswitch/commit/f6574b78288074d1806e5ea78117f89e3e19ae9f))
- **debit_routing:** Add `debit_routing_savings` in analytics payment attempt ([#8519](https://github.com/juspay/hyperswitch/pull/8519)) ([`fc3c64f`](https://github.com/juspay/hyperswitch/commit/fc3c64fad37a4434f103fb0bcdf1eafe67441b56))
### Bug Fixes
- **payout:** Use get_string_repr for formatting payout IDs ([#8547](https://github.com/juspay/hyperswitch/pull/8547)) ([`eb94cfe`](https://github.com/juspay/hyperswitch/commit/eb94cfe7e558348e8da3aeaaa01224a1ea2dbbe2))
### Refactors
- **connector:** [Worldpayvantiv] refactor void flow and handle transaction status ([#8540](https://github.com/juspay/hyperswitch/pull/8540)) ([`41291e5`](https://github.com/juspay/hyperswitch/commit/41291e5cde18c08b4586f3d37a9a858bdcda58b0))
- Extract connector auth and metadata validation into separate module ([#8501](https://github.com/juspay/hyperswitch/pull/8501)) ([`26ae469`](https://github.com/juspay/hyperswitch/commit/26ae469fafcec5c70ca2db36e438170ba8b8aa01))
**Full Changelog:** [`2025.07.04.0...2025.07.07.0`](https://github.com/juspay/hyperswitch/compare/2025.07.04.0...2025.07.07.0)
- - -
## 2025.07.04.0
### Features
- **connector:**
- [shift4] Boleto, Trustly, Alipay, Wechatpay PMs added ([#8476](https://github.com/juspay/hyperswitch/pull/8476)) ([`ac3b2d4`](https://github.com/juspay/hyperswitch/commit/ac3b2d4055cee0ae71a12fcb9119f4ba288417d4))
- [payload] template code ([#8526](https://github.com/juspay/hyperswitch/pull/8526)) ([`7f5ec74`](https://github.com/juspay/hyperswitch/commit/7f5ec7439b3469df7d77b8151ae3f4218847641a))
- [AUTHORIZEDOTNET] Add AVS checks ([#8511](https://github.com/juspay/hyperswitch/pull/8511)) ([`417039d`](https://github.com/juspay/hyperswitch/commit/417039d175c429c687f70cbb18625ef0c98c19ed))
- [shift4] Blik, Klarna, Bitpay PMs added ([#8478](https://github.com/juspay/hyperswitch/pull/8478)) ([`37a95e3`](https://github.com/juspay/hyperswitch/commit/37a95e3733676b24d6fa6924dcd84736eeca9bb4))
- [Redsys] Use merchant payment_id for ds_merchant_order with length check ([#8485](https://github.com/juspay/hyperswitch/pull/8485)) ([`6678ee3`](https://github.com/juspay/hyperswitch/commit/6678ee351748e5629a22e84677d58297cbac62a5))
- **core:** Populate connector raw response and connector_response_reference_id for razorpay ([#8499](https://github.com/juspay/hyperswitch/pull/8499)) ([`2253d98`](https://github.com/juspay/hyperswitch/commit/2253d981c89899e6e838f2072f46388eaa0bd8a0))
### Bug Fixes
- **connector:** [CYBERSOURCE] Passing pares_status for MasterCard & Visa and transaction_type field ([#8518](https://github.com/juspay/hyperswitch/pull/8518)) ([`721f780`](https://github.com/juspay/hyperswitch/commit/721f780c6baf5da5589d2a3242488b0d4383a1d8))
- **core:** Update error for routing instead of Internal Server Error ([#8512](https://github.com/juspay/hyperswitch/pull/8512)) ([`e4b1d45`](https://github.com/juspay/hyperswitch/commit/e4b1d45be76fb6183474177a1eaee26340b2e7d8))
- Update routing_approach for session_token flow ([#8490](https://github.com/juspay/hyperswitch/pull/8490)) ([`c275e13`](https://github.com/juspay/hyperswitch/commit/c275e13caf22362173e77d2260b440159abcabb3))
**Full Changelog:** [`2025.07.03.0...2025.07.04.0`](https://github.com/juspay/hyperswitch/compare/2025.07.03.0...2025.07.04.0)
- - -
## 2025.07.03.0
### Features
- **connector:**
- `multisafepay` added payment methods | TRUSTLY | WeChatpay | Alipay ([#8465](https://github.com/juspay/hyperswitch/pull/8465)) ([`01bd831`](https://github.com/juspay/hyperswitch/commit/01bd831665829bd318da5afe7410893ed5afc51e))
- [CHECKBOOK] Add Template Code ([#8494](https://github.com/juspay/hyperswitch/pull/8494)) ([`95077c6`](https://github.com/juspay/hyperswitch/commit/95077c64e27d6df35c15465f844c6ad7e1945571))
- **masking:** Implement `prost::Message` trait for `Secret` and `StrongSecret` types ([#8458](https://github.com/juspay/hyperswitch/pull/8458)) ([`ad29631`](https://github.com/juspay/hyperswitch/commit/ad29631c537c92fb11f1827fb3f6737cdc741f0f))
### Miscellaneous Tasks
- Address Rust 1.88.0 clippy lints ([#8498](https://github.com/juspay/hyperswitch/pull/8498)) ([`20b52f1`](https://github.com/juspay/hyperswitch/commit/20b52f11c3c010113a37a0b893c39ab0e8b5bfd1))
**Full Changelog:** [`2025.07.02.0...2025.07.03.0`](https://github.com/juspay/hyperswitch/compare/2025.07.02.0...2025.07.03.0)
- - -
## 2025.07.02.0
### Features
- **connector:**
- Implement capture and webhook flow, fix some issues in ACI ([#8349](https://github.com/juspay/hyperswitch/pull/8349)) ([`1ae3024`](https://github.com/juspay/hyperswitch/commit/1ae30247ca1fe94bf72752906462521b58513ca7))
- [ADYENPLATFORM] add card payouts ([#8504](https://github.com/juspay/hyperswitch/pull/8504)) ([`0c64915`](https://github.com/juspay/hyperswitch/commit/0c649158a8ee491e2ff6ff37e922266d5b64b22d))
- [DWOLLA] - Add template code ([#8496](https://github.com/juspay/hyperswitch/pull/8496)) ([`ad52251`](https://github.com/juspay/hyperswitch/commit/ad522513b9c7cd978f79dc1f00e25f9dcabb58dc))
- [SANTANDER] Added Authorize, PSync, Void, Refund & RSync Flows for Pix QR Code Bank Transfer ([#8463](https://github.com/juspay/hyperswitch/pull/8463)) ([`28d6357`](https://github.com/juspay/hyperswitch/commit/28d63575e63d87b1cba7c6215faee803f2fff7d8))
- **connectors:** [Worldpayvantiv] add NTI flow and refactor sync flows ([#8495](https://github.com/juspay/hyperswitch/pull/8495)) ([`f8dc3ec`](https://github.com/juspay/hyperswitch/commit/f8dc3ecfe6a9cb1441228dce474b92c4a6fe2985))
- **data-migration:** Add connector customer and mandate details support for multiple profiles ([#8473](https://github.com/juspay/hyperswitch/pull/8473)) ([`ce2b90b`](https://github.com/juspay/hyperswitch/commit/ce2b90b3d37d9214ef4ad46d5748aa0c864d508d))
- **dummy_connector:** Allow a dummy connector to succeed a failed card ([#8469](https://github.com/juspay/hyperswitch/pull/8469)) ([`69ab255`](https://github.com/juspay/hyperswitch/commit/69ab255394fc537dbc40e01c72f27f3c8dbfb5f1))
- **payouts:** Add domain type for PayoutId ([#8395](https://github.com/juspay/hyperswitch/pull/8395)) ([`a6e3d2c`](https://github.com/juspay/hyperswitch/commit/a6e3d2c71eed53ab400628a482cc61aae3720340))
### Refactors
- **authentication:** Flattened paymentData in authentication trait functions ([#8365](https://github.com/juspay/hyperswitch/pull/8365)) ([`18a779f`](https://github.com/juspay/hyperswitch/commit/18a779f94d418587c10c8ac8766d22ff41d25f6a))
- **connector:** Update add connector script with new connector features ([#8213](https://github.com/juspay/hyperswitch/pull/8213)) ([`2ff93ff`](https://github.com/juspay/hyperswitch/commit/2ff93ff972453ce30ffeff667cb406d35286f60a))
- Exposed auth analytics at merchant,org and profile levels ([#8335](https://github.com/juspay/hyperswitch/pull/8335)) ([`e638f23`](https://github.com/juspay/hyperswitch/commit/e638f239d3f3a0e7a63a5e71a1df6f516ddf9c4a))
**Full Changelog:** [`2025.07.01.0...2025.07.02.0`](https://github.com/juspay/hyperswitch/compare/2025.07.01.0...2025.07.02.0)
- - -
## 2025.07.01.0
### Features
- **core:** Allow setting up status across payments, refunds and payouts for triggering webhooks in core resource flows ([#8433](https://github.com/juspay/hyperswitch/pull/8433)) ([`d305fad`](https://github.com/juspay/hyperswitch/commit/d305fad2e6c403fde11b9eea785fddefbf3477df))
**Full Changelog:** [`2025.06.30.0...2025.07.01.0`](https://github.com/juspay/hyperswitch/compare/2025.06.30.0...2025.07.01.0)
- - -
## 2025.06.30.0
### Features
- **openapi:** Add x-mcp extension to v1 spec ([#8443](https://github.com/juspay/hyperswitch/pull/8443)) ([`a685f6b`](https://github.com/juspay/hyperswitch/commit/a685f6b59cb95b4b8eda33e6951faa31091099a5))
### Bug Fixes
- **connector:** 2 digit state code for ach fixed ([#8466](https://github.com/juspay/hyperswitch/pull/8466)) ([`68db51a`](https://github.com/juspay/hyperswitch/commit/68db51a37a1bd4b4a69cb7d018217ae4fd8babac))
- **env:** Update env for network tokenization service ([#8472](https://github.com/juspay/hyperswitch/pull/8472)) ([`6c66c36`](https://github.com/juspay/hyperswitch/commit/6c66c36a66b6644c43761b7ac9c1326945a6a820))
**Full Changelog:** [`2025.06.27.0...2025.06.30.0`](https://github.com/juspay/hyperswitch/compare/2025.06.27.0...2025.06.30.0)
- - -
## 2025.06.27.0
### Features
- **core:** Accept merchant_connector_details in Refunds create and retrieve flow ([#8441](https://github.com/juspay/hyperswitch/pull/8441)) ([`b185d85`](https://github.com/juspay/hyperswitch/commit/b185d85f6b55a8a99d4942a7a0966f5f731a920c))
- Kv changes for V2 feature ([#8198](https://github.com/juspay/hyperswitch/pull/8198)) ([`d2740f0`](https://github.com/juspay/hyperswitch/commit/d2740f0322a0ec1327515c0159b64c930307f451))
### Bug Fixes
- **connector:** [TRUSTPAY] Consuming Amount in PSync Response ([#8455](https://github.com/juspay/hyperswitch/pull/8455)) ([`537d175`](https://github.com/juspay/hyperswitch/commit/537d1755329c372f318df24aeda984d22f0b7a19))
**Full Changelog:** [`2025.06.26.1...2025.06.27.0`](https://github.com/juspay/hyperswitch/compare/2025.06.26.1...2025.06.27.0)
- - -
## 2025.06.26.1
### Features
- **router:** Add webhooks for network tokenization ([#6695](https://github.com/juspay/hyperswitch/pull/6695)) ([`ec6d0e4`](https://github.com/juspay/hyperswitch/commit/ec6d0e4d62a530163ae1c806dcf40ccfd264b246))
### Bug Fixes
- **recovery:** Populate connector request reference id in revenue recovery record attempt flow. ([#8434](https://github.com/juspay/hyperswitch/pull/8434)) ([`f1c5336`](https://github.com/juspay/hyperswitch/commit/f1c53366b28a89c82db0416ffe3e56b8a704afdf))
### Build System / Dependencies
- **deps:** Bump tonic version from 0.12 to 0.13 ([#8461](https://github.com/juspay/hyperswitch/pull/8461)) ([`9e43592`](https://github.com/juspay/hyperswitch/commit/9e435929f0ef45a6324c8d260c74ae3268470e72))
**Full Changelog:** [`2025.06.26.0...2025.06.26.1`](https://github.com/juspay/hyperswitch/compare/2025.06.26.0...2025.06.26.1)
- - -
## 2025.06.26.0
### Features
- **connector:**
- Add click to pay feature for trustpay ([#8304](https://github.com/juspay/hyperswitch/pull/8304)) ([`46709ae`](https://github.com/juspay/hyperswitch/commit/46709ae3695eb1a6601c356397545f86de9f0f64))
- [jpmorgan] implement refund flow ([#8436](https://github.com/juspay/hyperswitch/pull/8436)) ([`cf92e1a`](https://github.com/juspay/hyperswitch/commit/cf92e1a5e10fe5e1a2f939038bf0a94bcaf01e92))
### Refactors
- **router:** Remove `refunds_v2` feature flag ([#8310](https://github.com/juspay/hyperswitch/pull/8310)) ([`c5c0e67`](https://github.com/juspay/hyperswitch/commit/c5c0e677f2a2d43170a66330c98e0ebc4d771717))
- Move CustomerAcceptance to common_types ([#8299](https://github.com/juspay/hyperswitch/pull/8299)) ([`44d93e5`](https://github.com/juspay/hyperswitch/commit/44d93e572f45c0ff46936c6f352c767f5cd7daf4))
### Miscellaneous Tasks
- **postman:** Update Postman collection files ([`6419ad8`](https://github.com/juspay/hyperswitch/commit/6419ad85fbc08246a207e2601a36e4661bf805ff))
**Full Changelog:** [`2025.06.25.0...2025.06.26.0`](https://github.com/juspay/hyperswitch/compare/2025.06.25.0...2025.06.26.0)
- - -
## 2025.06.25.0
### Features
- **authentication:** Initial commit to modular authentication create ([#8085](https://github.com/juspay/hyperswitch/pull/8085)) ([`2ea5d81`](https://github.com/juspay/hyperswitch/commit/2ea5d81d534840d8ff900b9d768c0c264c4ddf53))
|
CHANGELOG.md#chunk4
| null |
doc_chunk
| 8,142
|
doc
| null | null | null | null | null | null | null | null | null | null | null | null |
pub struct ValidateResult {
pub merchant_id: common_utils::id_type::MerchantId,
pub payment_id: api::PaymentIdType,
pub storage_scheme: enums::MerchantStorageScheme,
pub requeue: bool,
}
|
crates/router/src/core/payments/operations.rs
|
router
|
struct_definition
| 49
|
rust
|
ValidateResult
| null | null | null | null | null | null | null | null | null | null | null |
impl std::fmt::Display for InvalidCrmConfig {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "crm: {}", self.0)
}
}
|
crates/external_services/src/crm.rs
|
external_services
|
impl_block
| 53
|
rust
| null |
InvalidCrmConfig
|
std::fmt::Display for
|
impl std::fmt::Display for for InvalidCrmConfig
| null | null | null | null | null | null | null | null |
pub struct SdkEventMetricsAccumulator {
pub payment_attempts: CountAccumulator,
pub payment_methods_call_count: CountAccumulator,
pub average_payment_time: CountAccumulator,
pub load_time: CountAccumulator,
pub sdk_initiated_count: CountAccumulator,
pub sdk_rendered_count: CountAccumulator,
pub payment_method_selected_count: CountAccumulator,
pub payment_data_filled_count: CountAccumulator,
}
|
crates/analytics/src/sdk_events/accumulator.rs
|
analytics
|
struct_definition
| 102
|
rust
|
SdkEventMetricsAccumulator
| null | null | null | null | null | null | null | null | null | null | null |
/// Derives the [`Serialize`][Serialize] implementation for error responses that are returned by
/// the API server.
///
/// This macro can be only used with enums. In addition to deriving [`Serialize`][Serialize], this
/// macro provides three methods: `error_type()`, `error_code()` and `error_message()`. Each enum
/// variant must have three required fields:
///
/// - `error_type`: This must be an enum variant which is returned by the `error_type()` method.
/// - `code`: A string error code, returned by the `error_code()` method.
/// - `message`: A string error message, returned by the `error_message()` method. The message
/// provided will directly be passed to `format!()`.
///
/// The return type of the `error_type()` method is provided by the `error_type_enum` field
/// annotated to the entire enum. Thus, all enum variants provided to the `error_type` field must
/// be variants of the enum provided to `error_type_enum` field. In addition, the enum passed to
/// the `error_type_enum` field must implement [`Serialize`][Serialize].
///
/// **NOTE:** This macro does not implement the [`Display`][Display] trait.
///
/// # Example
///
/// ```
/// use router_derive::ApiError;
///
/// #[derive(Clone, Debug, serde::Serialize)]
/// enum ErrorType {
/// StartupError,
/// InternalError,
/// SerdeError,
/// }
///
/// #[derive(Debug, ApiError)]
/// #[error(error_type_enum = ErrorType)]
/// enum MyError {
/// #[error(error_type = ErrorType::StartupError, code = "E001", message = "Failed to read configuration")]
/// ConfigurationError,
/// #[error(error_type = ErrorType::InternalError, code = "E002", message = "A database error occurred")]
/// DatabaseError,
/// #[error(error_type = ErrorType::SerdeError, code = "E003", message = "Failed to deserialize object")]
/// DeserializationError,
/// #[error(error_type = ErrorType::SerdeError, code = "E004", message = "Failed to serialize object")]
/// SerializationError,
/// }
///
/// impl ::std::fmt::Display for MyError {
/// fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> {
/// f.write_str(&self.error_message())
/// }
/// }
/// ```
///
/// # The Generated `Serialize` Implementation
///
/// - For a simple enum variant with no fields, the generated [`Serialize`][Serialize]
/// implementation has only three fields, `type`, `code` and `message`:
///
/// ```
/// # use router_derive::ApiError;
/// # #[derive(Clone, Debug, serde::Serialize)]
/// # enum ErrorType {
/// # StartupError,
/// # }
/// #[derive(Debug, ApiError)]
/// #[error(error_type_enum = ErrorType)]
/// enum MyError {
/// #[error(error_type = ErrorType::StartupError, code = "E001", message = "Failed to read configuration")]
/// ConfigurationError,
/// // ...
/// }
/// # impl ::std::fmt::Display for MyError {
/// # fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> {
/// # f.write_str(&self.error_message())
/// # }
/// # }
///
/// let json = serde_json::json!({
/// "type": "StartupError",
/// "code": "E001",
/// "message": "Failed to read configuration"
/// });
/// assert_eq!(serde_json::to_value(MyError::ConfigurationError).unwrap(), json);
/// ```
///
/// - For an enum variant with named fields, the generated [`Serialize`][Serialize] implementation
/// includes three mandatory fields, `type`, `code` and `message`, and any other fields not
/// included in the message:
///
/// ```
/// # use router_derive::ApiError;
/// # #[derive(Clone, Debug, serde::Serialize)]
/// # enum ErrorType {
/// # StartupError,
/// # }
/// #[derive(Debug, ApiError)]
/// #[error(error_type_enum = ErrorType)]
/// enum MyError {
/// #[error(error_type = ErrorType::StartupError, code = "E001", message = "Failed to read configuration file: {file_path}")]
/// ConfigurationError { file_path: String, reason: String },
/// // ...
/// }
/// # impl ::std::fmt::Display for MyError {
/// # fn fmt(&self, f: &mut ::core::fmt::Formatter) -> ::core::result::Result<(), ::core::fmt::Error> {
/// # f.write_str(&self.error_message())
/// # }
/// # }
///
/// let json = serde_json::json!({
/// "type": "StartupError",
/// "code": "E001",
/// "message": "Failed to read configuration file: config.toml",
/// "reason": "File not found"
/// });
/// let error = MyError::ConfigurationError{
/// file_path: "config.toml".to_string(),
/// reason: "File not found".to_string(),
/// };
/// assert_eq!(serde_json::to_value(error).unwrap(), json);
/// ```
///
/// [Serialize]: https://docs.rs/serde/latest/serde/trait.Serialize.html
/// [Display]: ::core::fmt::Display
#[proc_macro_derive(ApiError, attributes(error))]
pub fn api_error_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast = syn::parse_macro_input!(input as syn::DeriveInput);
let tokens =
macros::api_error_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error());
tokens.into()
}
|
crates/router_derive/src/lib.rs
|
router_derive
|
macro
| 1,282
|
rust
| null | null | null | null | null | null | null | null |
proc_derive
| null | null | null |
OpenAPI Block Path: components.schemas.CtpServiceDetails
{
"type": "object",
"properties": {
"merchant_transaction_id": {
"type": "string",
"description": "merchant transaction id",
"nullable": true
},
"correlation_id": {
"type": "string",
"description": "network transaction correlation id",
"nullable": true
},
"x_src_flow_id": {
"type": "string",
"description": "session transaction flow id",
"nullable": true
},
"provider": {
"allOf": [
{
"$ref": "#/components/schemas/CtpServiceProvider"
}
],
"nullable": true
},
"encrypted_payload": {
"type": "string",
"description": "Encrypted payload",
"nullable": true
}
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 193
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"CtpServiceDetails"
] | null | null | null | null |
impl api::PaymentAuthorize for Trustpay {}
|
crates/hyperswitch_connectors/src/connectors/trustpay.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Trustpay
|
api::PaymentAuthorize for
|
impl api::PaymentAuthorize for for Trustpay
| null | null | null | null | null | null | null | null |
File: crates/router/src/types/api/api_keys.rs
pub use api_models::api_keys::{
ApiKeyExpiration, CreateApiKeyRequest, CreateApiKeyResponse, ListApiKeyConstraints,
RetrieveApiKeyResponse, RevokeApiKeyResponse, UpdateApiKeyRequest,
};
|
crates/router/src/types/api/api_keys.rs
|
router
|
full_file
| 51
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl ConnectorValidation for Zen {
fn validate_psync_reference_id(
&self,
_data: &PaymentsSyncData,
_is_three_ds: bool,
_status: enums::AttemptStatus,
_connector_meta_data: Option<common_utils::pii::SecretSerdeValue>,
) -> CustomResult<(), errors::ConnectorError> {
// since we can make psync call with our reference_id, having connector_transaction_id is not an mandatory criteria
Ok(())
}
}
|
crates/hyperswitch_connectors/src/connectors/zen.rs
|
hyperswitch_connectors
|
impl_block
| 104
|
rust
| null |
Zen
|
ConnectorValidation for
|
impl ConnectorValidation for for Zen
| null | null | null | null | null | null | null | null |
pub struct GlobalpayWebhookObjectEventType {
pub status: GlobalpayWebhookStatus,
}
|
crates/hyperswitch_connectors/src/connectors/globalpay/response.rs
|
hyperswitch_connectors
|
struct_definition
| 20
|
rust
|
GlobalpayWebhookObjectEventType
| null | null | null | null | null | null | null | null | null | null | null |
pub struct ItaubankTokenErrorResponse {
pub status: i64,
pub title: Option<String>,
pub detail: Option<String>,
pub user_message: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/itaubank/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 39
|
rust
|
ItaubankTokenErrorResponse
| null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.PaymentsUpdateRequest
{
"type": "object",
"properties": {
"amount": {
"type": "integer",
"format": "int64",
"description": "The primary amount for the payment, provided in the lowest denomination of the specified currency (e.g., 6540 for $65.40 USD). This field is mandatory for creating a payment.",
"example": 6540,
"nullable": true,
"minimum": 0
},
"order_tax_amount": {
"type": "integer",
"format": "int64",
"description": "Total tax amount applicable to the order, in the lowest denomination of the currency.",
"example": 6540,
"nullable": true
},
"currency": {
"allOf": [
{
"$ref": "#/components/schemas/Currency"
}
],
"nullable": true
},
"amount_to_capture": {
"type": "integer",
"format": "int64",
"description": "The amount to be captured from the user's payment method, in the lowest denomination. If not provided, and `capture_method` is `automatic`, the full payment `amount` will be captured. If `capture_method` is `manual`, this can be specified in the `/capture` call. Must be less than or equal to the authorized amount.",
"example": 6540,
"nullable": true
},
"shipping_cost": {
"type": "integer",
"format": "int64",
"description": "The shipping cost for the payment. This is required for tax calculation in some regions.",
"example": 6540,
"nullable": true
},
"payment_id": {
"type": "string",
"description": "Optional. A merchant-provided unique identifier for the payment, contains 30 characters long (e.g., \"pay_mbabizu24mvu3mela5njyhpit4\"). If provided, it ensures idempotency for the payment creation request. If omitted, Hyperswitch generates a unique ID for the payment.",
"example": "pay_mbabizu24mvu3mela5njyhpit4",
"nullable": true,
"maxLength": 30,
"minLength": 30
},
"routing": {
"allOf": [
{
"$ref": "#/components/schemas/StraightThroughAlgorithm"
}
],
"nullable": true
},
"connector": {
"type": "array",
"items": {
"$ref": "#/components/schemas/Connector"
},
"description": "This allows to manually select a connector with which the payment can go through.",
"example": [
"stripe",
"adyen"
],
"nullable": true
},
"capture_method": {
"allOf": [
{
"$ref": "#/components/schemas/CaptureMethod"
}
],
"nullable": true
},
"authentication_type": {
"allOf": [
{
"$ref": "#/components/schemas/AuthenticationType"
}
],
"default": "three_ds",
"nullable": true
},
"billing": {
"allOf": [
{
"$ref": "#/components/schemas/Address"
}
],
"nullable": true
},
"confirm": {
"type": "boolean",
"description": "If set to `true`, Hyperswitch attempts to confirm and authorize the payment immediately after creation, provided sufficient payment method details are included. If `false` or omitted (default is `false`), the payment is created with a status such as `requires_payment_method` or `requires_confirmation`, and a separate `POST /payments/{payment_id}/confirm` call is necessary to proceed with authorization.",
"default": false,
"example": true,
"nullable": true
},
"customer": {
"allOf": [
{
"$ref": "#/components/schemas/CustomerDetails"
}
],
"nullable": true
},
"customer_id": {
"type": "string",
"description": "The identifier for the customer",
"example": "cus_y3oqhf46pyzuxjbcn2giaqnb44",
"nullable": true,
"maxLength": 64,
"minLength": 1
},
"off_session": {
"type": "boolean",
"description": "Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory",
"example": true,
"nullable": true
},
"description": {
"type": "string",
"description": "An arbitrary string attached to the payment. Often useful for displaying to users or for your own internal record-keeping.",
"example": "It's my first payment request",
"nullable": true
},
"return_url": {
"type": "string",
"description": "The URL to redirect the customer to after they complete the payment process or authentication. This is crucial for flows that involve off-site redirection (e.g., 3DS, some bank redirects, wallet payments).",
"example": "https://hyperswitch.io",
"nullable": true,
"maxLength": 2048
},
"setup_future_usage": {
"allOf": [
{
"$ref": "#/components/schemas/FutureUsage"
}
],
"nullable": true
},
"payment_method_data": {
"allOf": [
{
"$ref": "#/components/schemas/PaymentMethodDataRequest"
}
],
"nullable": true
},
"payment_method": {
"allOf": [
{
"$ref": "#/components/schemas/PaymentMethod"
}
],
"nullable": true
},
"payment_token": {
"type": "string",
"description": "As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner.",
"example": "187282ab-40ef-47a9-9206-5099ba31e432",
"nullable": true
},
"shipping": {
"allOf": [
{
"$ref": "#/components/schemas/Address"
}
],
"nullable": true
},
"statement_descriptor_name": {
"type": "string",
"description": "For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters.",
"example": "Hyperswitch Router",
"nullable": true,
"maxLength": 255
},
"statement_descriptor_suffix": {
"type": "string",
"description": "Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor.",
"example": "Payment for shoes purchase",
"nullable": true,
"maxLength": 255
},
"order_details": {
"type": "array",
"items": {
"$ref": "#/components/schemas/OrderDetailsWithAmount"
},
"description": "Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount",
"example": "[{\n \"product_name\": \"Apple iPhone 16\",\n \"quantity\": 1,\n \"amount\" : 69000\n \"product_img_link\" : \"https://dummy-img-link.com\"\n }]",
"nullable": true
},
"mandate_data": {
"allOf": [
{
"$ref": "#/components/schemas/MandateData"
}
],
"nullable": true
},
"customer_acceptance": {
"allOf": [
{
"$ref": "#/components/schemas/CustomerAcceptance"
}
],
"nullable": true
},
"browser_info": {
"allOf": [
{
"$ref": "#/components/schemas/BrowserInformation"
}
],
"nullable": true
},
"payment_experience": {
"allOf": [
{
"$ref": "#/components/schemas/PaymentExperience"
}
],
"nullable": true
},
"payment_method_type": {
"allOf": [
{
"$ref": "#/components/schemas/PaymentMethodType"
}
],
"nullable": true
},
"merchant_connector_details": {
"allOf": [
{
"$ref": "#/components/schemas/MerchantConnectorDetailsWrap"
}
],
"nullable": true
},
"allowed_payment_method_types": {
"type": "array",
"items": {
"$ref": "#/components/schemas/PaymentMethodType"
},
"description": "Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent",
"nullable": true
},
"retry_action": {
"allOf": [
{
"$ref": "#/components/schemas/RetryAction"
}
],
"nullable": true
},
"metadata": {
"type": "object",
"description": "You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object.",
"nullable": true
},
"connector_metadata": {
"allOf": [
{
"$ref": "#/components/schemas/ConnectorMetadata"
}
],
"nullable": true
},
"payment_link": {
"type": "boolean",
"description": "Whether to generate the payment link for this payment or not (if applicable)",
"default": false,
"example": true,
"nullable": true
},
"payment_link_config": {
"allOf": [
{
"$ref": "#/components/schemas/PaymentCreatePaymentLinkConfig"
}
],
"nullable": true
},
"payment_link_config_id": {
"type": "string",
"description": "Custom payment link config id set at business profile, send only if business_specific_configs is configured",
"nullable": true
},
"surcharge_details": {
"allOf": [
{
"$ref": "#/components/schemas/RequestSurchargeDetails"
}
],
"nullable": true
},
"payment_type": {
"allOf": [
{
"$ref": "#/components/schemas/PaymentType"
}
],
"nullable": true
},
"request_incremental_authorization": {
"type": "boolean",
"description": "Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it.",
"nullable": true
},
"session_expiry": {
"type": "integer",
"format": "int32",
"description": "Will be used to expire client secret after certain amount of time to be supplied in seconds\n(900) for 15 mins",
"example": 900,
"nullable": true,
"minimum": 0
},
"frm_metadata": {
"type": "object",
"description": "Additional data related to some frm(Fraud Risk Management) connectors",
"nullable": true
},
"request_external_three_ds_authentication": {
"type": "boolean",
"description": "Whether to perform external authentication (if applicable)",
"example": true,
"nullable": true
},
"recurring_details": {
"allOf": [
{
"$ref": "#/components/schemas/RecurringDetails"
}
],
"nullable": true
},
"split_payments": {
"allOf": [
{
"$ref": "#/components/schemas/SplitPaymentsRequest"
}
],
"nullable": true
},
"request_extended_authorization": {
"type": "boolean",
"description": "Optional boolean value to extent authorization period of this payment\n\ncapture method must be manual or manual_multiple",
"default": false,
"nullable": true
},
"merchant_order_reference_id": {
"type": "string",
"description": "Your unique identifier for this payment or order. This ID helps you reconcile payments on your system. If provided, it is passed to the connector if supported.",
"example": "Custom_Order_id_123",
"nullable": true,
"maxLength": 255
},
"skip_external_tax_calculation": {
"type": "boolean",
"description": "Whether to calculate tax for this payment intent",
"nullable": true
},
"psd2_sca_exemption_type": {
"allOf": [
{
"$ref": "#/components/schemas/ScaExemptionType"
}
],
"nullable": true
},
"ctp_service_details": {
"allOf": [
{
"$ref": "#/components/schemas/CtpServiceDetails"
}
],
"nullable": true
},
"force_3ds_challenge": {
"type": "boolean",
"description": "Indicates if 3ds challenge is forced",
"nullable": true
},
"threeds_method_comp_ind": {
"allOf": [
{
"$ref": "#/components/schemas/ThreeDsCompletionIndicator"
}
],
"nullable": true
},
"is_iframe_redirection_enabled": {
"type": "boolean",
"description": "Indicates if the redirection has to open in the iframe",
"nullable": true
},
"all_keys_required": {
"type": "boolean",
"description": "If enabled, provides whole connector response",
"nullable": true
},
"payment_channel": {
"allOf": [
{
"$ref": "#/components/schemas/PaymentChannel"
}
],
"nullable": true
},
"tax_status": {
"allOf": [
{
"$ref": "#/components/schemas/TaxStatus"
}
],
"nullable": true
},
"discount_amount": {
"type": "integer",
"format": "int64",
"description": "Total amount of the discount you have applied to the order or transaction.",
"example": 6540,
"nullable": true
},
"shipping_amount_tax": {
"allOf": [
{
"$ref": "#/components/schemas/MinorUnit"
}
],
"nullable": true
},
"duty_amount": {
"allOf": [
{
"$ref": "#/components/schemas/MinorUnit"
}
],
"nullable": true
},
"order_date": {
"type": "string",
"format": "date-time",
"description": "Date the payer placed the order.",
"nullable": true
},
"enable_partial_authorization": {
"type": "boolean",
"description": "Allow partial authorization for this payment",
"nullable": true
}
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 3,520
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"PaymentsUpdateRequest"
] | null | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.