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 is_operation_allowed<Op: Debug>(operation: &Op) -> bool {
![
"PaymentSession",
"PaymentApprove",
"PaymentReject",
"PaymentCapture",
"PaymentsCancel",
]
.contains(&format!("{operation:?}").as_str())
}
|
crates/router/src/core/fraud_check.rs
|
router
|
function_signature
| 63
|
rust
| null | null | null | null |
is_operation_allowed
| null | null | null | null | null | null | null |
impl Inespay {
pub fn new() -> &'static Self {
&Self {
amount_converter: &StringMinorUnitForConnector,
}
}
}
|
crates/hyperswitch_connectors/src/connectors/inespay.rs
|
hyperswitch_connectors
|
impl_block
| 35
|
rust
| null |
Inespay
| null |
impl Inespay
| null | null | null | null | null | null | null | null |
File: crates/storage_impl/src/redis/pub_sub.rs
use std::sync::atomic;
use error_stack::ResultExt;
use redis_interface::{errors as redis_errors, PubsubInterface, RedisValue};
use router_env::{logger, tracing::Instrument};
use crate::redis::cache::{
CacheKey, CacheKind, CacheRedact, ACCOUNTS_CACHE, CGRAPH_CACHE, CONFIG_CACHE,
CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE, DECISION_MANAGER_CACHE,
ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE, PM_FILTERS_CGRAPH_CACHE, ROUTING_CACHE,
SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE, SURCHARGE_CACHE,
};
#[async_trait::async_trait]
pub trait PubSubInterface {
async fn subscribe(&self, channel: &str) -> error_stack::Result<(), redis_errors::RedisError>;
async fn publish<'a>(
&self,
channel: &str,
key: CacheKind<'a>,
) -> error_stack::Result<usize, redis_errors::RedisError>;
async fn on_message(&self) -> error_stack::Result<(), redis_errors::RedisError>;
}
#[async_trait::async_trait]
impl PubSubInterface for std::sync::Arc<redis_interface::RedisConnectionPool> {
#[inline]
async fn subscribe(&self, channel: &str) -> error_stack::Result<(), redis_errors::RedisError> {
// Spawns a task that will automatically re-subscribe to any channels or channel patterns used by the client.
self.subscriber.manage_subscriptions();
self.subscriber
.subscribe::<(), &str>(channel)
.await
.change_context(redis_errors::RedisError::SubscribeError)?;
// Spawn only one thread handling all the published messages to different channels
if self
.subscriber
.is_subscriber_handler_spawned
.compare_exchange(
false,
true,
atomic::Ordering::SeqCst,
atomic::Ordering::SeqCst,
)
.is_ok()
{
let redis_clone = self.clone();
let _task_handle = tokio::spawn(
async move {
if let Err(pubsub_error) = redis_clone.on_message().await {
logger::error!(?pubsub_error);
}
}
.in_current_span(),
);
}
Ok(())
}
#[inline]
async fn publish<'a>(
&self,
channel: &str,
key: CacheKind<'a>,
) -> error_stack::Result<usize, redis_errors::RedisError> {
let key = CacheRedact {
kind: key,
tenant: self.key_prefix.clone(),
};
self.publisher
.publish(
channel,
RedisValue::try_from(key).change_context(redis_errors::RedisError::PublishError)?,
)
.await
.change_context(redis_errors::RedisError::SubscribeError)
}
#[inline]
async fn on_message(&self) -> error_stack::Result<(), redis_errors::RedisError> {
logger::debug!("Started on message");
let mut rx = self.subscriber.on_message();
while let Ok(message) = rx.recv().await {
let channel_name = message.channel.to_string();
logger::debug!("Received message on channel: {channel_name}");
match channel_name.as_str() {
super::cache::IMC_INVALIDATION_CHANNEL => {
let message = match CacheRedact::try_from(RedisValue::new(message.value))
.change_context(redis_errors::RedisError::OnMessageError)
{
Ok(value) => value,
Err(err) => {
logger::error!(value_conversion_err=?err);
continue;
}
};
let key = match message.kind {
CacheKind::Config(key) => {
CONFIG_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::Accounts(key) => {
ACCOUNTS_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::CGraph(key) => {
CGRAPH_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::PmFiltersCGraph(key) => {
PM_FILTERS_CGRAPH_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::EliminationBasedDynamicRoutingCache(key) => {
ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::ContractBasedDynamicRoutingCache(key) => {
CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::SuccessBasedDynamicRoutingCache(key) => {
SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::Routing(key) => {
ROUTING_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::DecisionManager(key) => {
DECISION_MANAGER_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::Surcharge(key) => {
SURCHARGE_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
CacheKind::All(key) => {
CONFIG_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
ACCOUNTS_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
CGRAPH_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
PM_FILTERS_CGRAPH_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
SUCCESS_BASED_DYNAMIC_ALGORITHM_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
ELIMINATION_BASED_DYNAMIC_ALGORITHM_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
CONTRACT_BASED_DYNAMIC_ALGORITHM_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
ROUTING_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
DECISION_MANAGER_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
SURCHARGE_CACHE
.remove(CacheKey {
key: key.to_string(),
prefix: message.tenant.clone(),
})
.await;
key
}
};
logger::debug!(
key_prefix=?message.tenant.clone(),
channel_name=?channel_name,
"Done invalidating {key}"
);
}
_ => {
logger::debug!("Received message from unknown channel: {channel_name}");
}
}
}
Ok(())
}
}
|
crates/storage_impl/src/redis/pub_sub.rs
|
storage_impl
|
full_file
| 1,722
| null | null | null | null | null | null | null | null | null | null | null | null | null |
/// Asynchronously retrieves a HashiCorp Vault client based on the provided configuration.
///
/// # Parameters
///
/// - `config`: A reference to a `HashiCorpVaultConfig` containing the configuration details.
pub async fn get_hashicorp_client(
config: &HashiCorpVaultConfig,
) -> error_stack::Result<&'static HashiCorpVault, HashiCorpError> {
HC_CLIENT
.get_or_try_init(|| async { HashiCorpVault::new(config) })
.await
}
|
crates/external_services/src/hashicorp_vault/core.rs
|
external_services
|
function_signature
| 109
|
rust
| null | null | null | null |
get_hashicorp_client
| null | null | null | null | null | null | null |
File: crates/analytics/src/payment_intents/metrics/payments_success_rate.rs
use std::collections::HashSet;
use api_models::analytics::{
payment_intents::{
PaymentIntentDimensions, PaymentIntentFilters, PaymentIntentMetricsBucketIdentifier,
},
Granularity, TimeRange,
};
use common_utils::errors::ReportSwitchExt;
use error_stack::ResultExt;
use time::PrimitiveDateTime;
use super::PaymentIntentMetricRow;
use crate::{
enums::AuthInfo,
query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, SeriesBucket, ToSql, Window},
types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult},
};
#[derive(Default)]
pub(super) struct PaymentsSuccessRate;
#[async_trait::async_trait]
impl<T> super::PaymentIntentMetric<T> for PaymentsSuccessRate
where
T: AnalyticsDataSource + super::PaymentIntentMetricAnalytics,
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: &[PaymentIntentDimensions],
auth: &AuthInfo,
filters: &PaymentIntentFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>>
{
let mut query_builder: QueryBuilder<T> =
QueryBuilder::new(AnalyticsCollection::PaymentIntent);
let mut dimensions = dimensions.to_vec();
dimensions.push(PaymentIntentDimensions::PaymentIntentStatus);
for dim in dimensions.iter() {
query_builder.add_select_column(dim).switch()?;
}
query_builder
.add_select_column(Aggregate::Count {
field: None,
alias: Some("count"),
})
.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)
.attach_printable("Error grouping by dimensions")
.switch()?;
}
if let Some(granularity) = granularity {
granularity
.set_group_by_clause(&mut query_builder)
.attach_printable("Error adding granularity")
.switch()?;
}
query_builder
.execute_query::<PaymentIntentMetricRow, _>(pool)
.await
.change_context(MetricsError::QueryBuildingError)?
.change_context(MetricsError::QueryExecutionFailure)?
.into_iter()
.map(|i| {
Ok((
PaymentIntentMetricsBucketIdentifier::new(
None,
i.currency.as_ref().map(|i| i.0),
i.profile_id.clone(),
i.connector.clone(),
i.authentication_type.as_ref().map(|i| i.0),
i.payment_method.clone(),
i.payment_method_type.clone(),
i.card_network.clone(),
i.merchant_id.clone(),
i.card_last_4.clone(),
i.card_issuer.clone(),
i.error_reason.clone(),
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<(PaymentIntentMetricsBucketIdentifier, PaymentIntentMetricRow)>,
crate::query::PostProcessingError,
>>()
.change_context(MetricsError::PostProcessingFailure)
}
}
|
crates/analytics/src/payment_intents/metrics/payments_success_rate.rs
|
analytics
|
full_file
| 926
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct QuoteRequest {
pub source_id: Secret<String>,
pub source_currency_code: Currency,
pub destination_currency_code: Currency,
pub amount: FloatMajorUnit,
pub include_fee: String,
}
|
crates/hyperswitch_connectors/src/connectors/nomupay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 45
|
rust
|
QuoteRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub fn get_connector_image_link(self, base_url: &str) -> String {
let image_name = match self {
Self::PhonyPay => "PHONYPAY.svg",
Self::FauxPay => "FAUXPAY.svg",
Self::PretendPay => "PRETENDPAY.svg",
Self::StripeTest => "STRIPE_TEST.svg",
Self::PaypalTest => "PAYPAL_TEST.svg",
_ => "PHONYPAY.svg",
};
format!("{base_url}{image_name}")
}
|
crates/router/src/routes/dummy_connector/types.rs
|
router
|
function_signature
| 116
|
rust
| null | null | null | null |
get_connector_image_link
| null | null | null | null | null | null | null |
pub struct TelemetryGuard {
_log_guards: Vec<WorkerGuard>,
}
|
crates/router_env/src/logger/setup.rs
|
router_env
|
struct_definition
| 18
|
rust
|
TelemetryGuard
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn proxy_core(
state: SessionState,
merchant_context: domain::MerchantContext,
req: proxy_api_models::ProxyRequest,
) -> RouterResponse<proxy_api_models::ProxyResponse> {
let req_wrapper = utils::ProxyRequestWrapper(req.clone());
let proxy_record = req_wrapper
.get_proxy_record(
&state,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let vault_data = proxy_record
.get_vault_data(&state, merchant_context)
.await?;
let processed_body =
interpolate_token_references_with_vault_data(req.request_body.clone(), &vault_data)?;
let res = execute_proxy_request(&state, &req_wrapper, processed_body).await?;
let proxy_response = proxy_api_models::ProxyResponse::try_from(ProxyResponseWrapper(res))?;
Ok(services::ApplicationResponse::Json(proxy_response))
}
|
crates/router/src/core/proxy.rs
|
router
|
function_signature
| 200
|
rust
| null | null | null | null |
proxy_core
| null | null | null | null | null | null | null |
Documentation: api-reference/v1/organization/organization--update.mdx
# Type: Doc File
---
openapi: put /organization/{id}
---
|
api-reference/v1/organization/organization--update.mdx
| null |
doc_file
| 32
|
doc
| null | null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.PaymentMethodCollectLinkResponse
{
"allOf": [
{
"$ref": "#/components/schemas/GenericLinkUiConfig"
},
{
"type": "object",
"required": [
"pm_collect_link_id",
"customer_id",
"expiry",
"link"
],
"properties": {
"pm_collect_link_id": {
"type": "string",
"description": "The unique identifier for the collect link.",
"example": "pm_collect_link_2bdacf398vwzq5n422S1"
},
"customer_id": {
"type": "string",
"description": "The unique identifier of the customer.",
"example": "cus_92dnwed8s32bV9D8Snbiasd8v"
},
"expiry": {
"type": "string",
"format": "date-time",
"description": "Time when this link will be expired in ISO8601 format",
"example": "2025-01-18T11:04:09.922Z"
},
"link": {
"type": "string",
"description": "URL to the form's link generated for collecting payment method details.",
"example": "https://sandbox.hyperswitch.io/payment_method/collect/pm_collect_link_2bdacf398vwzq5n422S1"
},
"return_url": {
"type": "string",
"description": "Redirect to this URL post completion",
"example": "https://sandbox.hyperswitch.io/payment_method/collect/pm_collect_link_2bdacf398vwzq5n422S1/status",
"nullable": true
},
"enabled_payment_methods": {
"type": "array",
"items": {
"$ref": "#/components/schemas/EnabledPaymentMethod"
},
"description": "List of payment methods shown on collect UI",
"example": "[{\"payment_method\": \"bank_transfer\", \"payment_method_types\": [\"ach\", \"bacs\"]}]",
"nullable": true
}
}
}
]
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 497
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"PaymentMethodCollectLinkResponse"
] | null | null | null | null |
pub async fn customers_retrieve() {}
|
crates/openapi/src/routes/customers.rs
|
openapi
|
function_signature
| 8
|
rust
| null | null | null | null |
customers_retrieve
| null | null | null | null | null | null | null |
pub struct ErrorResponse {
pub code: String,
pub message: String,
pub reason: Option<String>,
pub status_code: u16,
pub attempt_status: Option<common_enums::enums::AttemptStatus>,
pub connector_transaction_id: Option<String>,
pub network_decline_code: Option<String>,
pub network_advice_code: Option<String>,
pub network_error_message: Option<String>,
pub connector_metadata: Option<Secret<serde_json::Value>>,
}
|
crates/hyperswitch_domain_models/src/router_data.rs
|
hyperswitch_domain_models
|
struct_definition
| 101
|
rust
|
ErrorResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub struct RefundResponse {
id: String,
state: RefundState,
}
|
crates/hyperswitch_connectors/src/connectors/billwerk/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 19
|
rust
|
RefundResponse
| null | null | null | null | null | null | null | null | null | null | null |
impl<T: Eq + PartialEq + Clone + std::hash::Hash> std::hash::Hash for Maskable<T> {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
match self {
Self::Masked(value) => crate::PeekInterface::peek(value).hash(state),
Self::Normal(value) => value.hash(state),
}
}
}
|
crates/masking/src/maskable.rs
|
masking
|
impl_block
| 87
|
rust
| null |
Maskable
|
std::hash::Hash for
|
impl std::hash::Hash for for Maskable
| null | null | null | null | null | null | null | null |
impl<'a, K, V> Iterator for IterMut<'a, K, V>
where
K: EntityId,
{
type Item = (K, &'a mut V);
fn next(&mut self) -> Option<Self::Item> {
self.inner.next().map(|(id, val)| (K::with_id(id), val))
}
}
|
crates/hyperswitch_constraint_graph/src/dense_map.rs
|
hyperswitch_constraint_graph
|
impl_block
| 78
|
rust
| null |
IterMut
|
Iterator for
|
impl Iterator for for IterMut
| null | null | null | null | null | null | null | null |
pub async fn get_payment_filters(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
) -> impl Responder {
let flow = Flow::PaymentsFilters;
Box::pin(api::server_wrap(
flow,
state,
&req,
(),
|state, auth: auth::AuthenticationData, _, _| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::get_payment_filters(state, merchant_context, None)
},
&auth::JWTAuth {
permission: Permission::MerchantPaymentRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/routes/payments.rs
|
router
|
function_signature
| 160
|
rust
| null | null | null | null |
get_payment_filters
| null | null | null | null | null | null | null |
File: crates/config_importer/src/cli.rs
use std::path::PathBuf;
/// Utility to import a hyperswitch TOML configuration file, convert it into environment variable
/// key-value pairs, and export it in the specified format.
#[derive(clap::Parser, Debug)]
#[command(arg_required_else_help = true)]
pub(crate) struct Args {
/// Input TOML configuration file.
#[arg(short, long, value_name = "FILE")]
pub(crate) input_file: PathBuf,
/// The format to convert the environment variables to.
#[arg(
value_enum,
short = 'f',
long,
value_name = "FORMAT",
default_value = "kubernetes-json"
)]
pub(crate) output_format: OutputFormat,
/// Output file. Output will be written to stdout if not specified.
#[arg(short, long, value_name = "FILE")]
pub(crate) output_file: Option<PathBuf>,
/// Prefix to be used for each environment variable in the generated output.
#[arg(short, long, default_value = "ROUTER")]
pub(crate) prefix: String,
}
/// The output format to convert environment variables to.
#[derive(clap::ValueEnum, Clone, Copy, Debug)]
pub(crate) enum OutputFormat {
/// Converts each environment variable to an object containing `name` and `value` fields.
///
/// ```json
/// {
/// "name": "ENVIRONMENT",
/// "value": "PRODUCTION"
/// }
/// ```
KubernetesJson,
}
|
crates/config_importer/src/cli.rs
|
config_importer
|
full_file
| 329
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub async fn find_optional_by_attempt_id_merchant_id(
conn: &PgPooledConn,
attempt_id: String,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Option<Self>> {
generics::generic_find_one_optional::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::attempt_id.eq(attempt_id.to_owned())),
)
.await
}
|
crates/diesel_models/src/query/dynamic_routing_stats.rs
|
diesel_models
|
function_signature
| 111
|
rust
| null | null | null | null |
find_optional_by_attempt_id_merchant_id
| null | null | null | null | null | null | null |
pub fn scope(&self) -> PermissionScope {
match self {
#(#scope_impl_per),*
}
}
|
crates/router_derive/src/macros/generate_permissions.rs
|
router_derive
|
function_signature
| 26
|
rust
| null | null | null | null |
scope
| null | null | null | null | null | null | null |
pub struct ApplepayPaymentMethod {
display_name: String,
network: String,
#[serde(rename = "type")]
token_type: String,
}
|
crates/hyperswitch_connectors/src/connectors/nexinets/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 33
|
rust
|
ApplepayPaymentMethod
| null | null | null | null | null | null | null | null | null | null | null |
pub trait SdkEventMetric<T>
where
T: AnalyticsDataSource + SdkEventMetricAnalytics,
{
async fn load_metrics(
&self,
dimensions: &[SdkEventDimensions],
publishable_key: &str,
filters: &SdkEventFilters,
granularity: Option<Granularity>,
time_range: &TimeRange,
pool: &T,
) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>>;
}
|
crates/analytics/src/sdk_events/metrics.rs
|
analytics
|
trait_definition
| 101
|
rust
| null | null |
SdkEventMetric
| null | null | null | null | null | null | null | null | null |
pub struct CaptureResponse {
#[serde(rename = "@id")]
pub id: String,
#[serde(rename = "@reportGroup")]
pub report_group: String,
#[serde(rename = "@customerId", skip_serializing_if = "Option::is_none")]
pub customer_id: Option<String>,
#[serde(rename = "cnpTxnId")]
pub cnp_txn_id: String,
pub response: WorldpayvantivResponseCode,
pub response_time: String,
pub message: String,
pub location: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/worldpayvantiv/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 115
|
rust
|
CaptureResponse
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_domain_models/src/customer.rs
Public functions: 4
Public structs: 4
use common_enums::enums::MerchantStorageScheme;
#[cfg(feature = "v2")]
use common_enums::DeleteStatus;
use common_utils::{
crypto::{self, Encryptable},
date_time,
encryption::Encryption,
errors::{CustomResult, ValidationError},
id_type, pii,
types::{
keymanager::{self, KeyManagerState, ToEncryptable},
Description,
},
};
use diesel_models::{
customers as storage_types, customers::CustomerUpdateInternal, query::customers as query,
};
use error_stack::ResultExt;
use masking::{PeekInterface, Secret, SwitchStrategy};
use rustc_hash::FxHashMap;
use time::PrimitiveDateTime;
#[cfg(feature = "v2")]
use crate::merchant_connector_account::MerchantConnectorAccountTypeDetails;
use crate::{behaviour, merchant_key_store::MerchantKeyStore, type_encryption as types};
#[cfg(feature = "v1")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct Customer {
pub customer_id: id_type::CustomerId,
pub merchant_id: id_type::MerchantId,
#[encrypt]
pub name: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
#[encrypt]
pub phone: Option<Encryptable<Secret<String>>>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub modified_at: PrimitiveDateTime,
pub connector_customer: Option<pii::SecretSerdeValue>,
pub address_id: Option<String>,
pub default_payment_method_id: Option<String>,
pub updated_by: Option<String>,
pub version: common_enums::ApiVersion,
#[encrypt]
pub tax_registration_id: Option<Encryptable<Secret<String>>>,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug, router_derive::ToEncryption)]
pub struct Customer {
pub merchant_id: id_type::MerchantId,
#[encrypt]
pub name: Option<Encryptable<Secret<String>>>,
#[encrypt]
pub email: Option<Encryptable<Secret<String, pii::EmailStrategy>>>,
#[encrypt]
pub phone: Option<Encryptable<Secret<String>>>,
pub phone_country_code: Option<String>,
pub description: Option<Description>,
pub created_at: PrimitiveDateTime,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Option<common_types::customers::ConnectorCustomerMap>,
pub modified_at: PrimitiveDateTime,
pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>,
pub updated_by: Option<String>,
pub merchant_reference_id: Option<id_type::CustomerId>,
pub default_billing_address: Option<Encryption>,
pub default_shipping_address: Option<Encryption>,
pub id: id_type::GlobalCustomerId,
pub version: common_enums::ApiVersion,
pub status: DeleteStatus,
#[encrypt]
pub tax_registration_id: Option<Encryptable<Secret<String>>>,
}
impl Customer {
/// Get the unique identifier of Customer
#[cfg(feature = "v1")]
pub fn get_id(&self) -> &id_type::CustomerId {
&self.customer_id
}
/// Get the global identifier of Customer
#[cfg(feature = "v2")]
pub fn get_id(&self) -> &id_type::GlobalCustomerId {
&self.id
}
/// Get the connector customer ID for the specified connector label, if present
#[cfg(feature = "v1")]
pub fn get_connector_customer_id(&self, connector_label: &str) -> Option<&str> {
use masking::PeekInterface;
self.connector_customer
.as_ref()
.and_then(|connector_customer_value| {
connector_customer_value.peek().get(connector_label)
})
.and_then(|connector_customer| connector_customer.as_str())
}
/// Get the connector customer ID for the specified merchant connector account ID, if present
#[cfg(feature = "v2")]
pub fn get_connector_customer_id(
&self,
merchant_connector_account: &MerchantConnectorAccountTypeDetails,
) -> Option<&str> {
match merchant_connector_account {
MerchantConnectorAccountTypeDetails::MerchantConnectorAccount(account) => {
let connector_account_id = account.get_id();
self.connector_customer
.as_ref()?
.get(&connector_account_id)
.map(|connector_customer_id| connector_customer_id.as_str())
}
MerchantConnectorAccountTypeDetails::MerchantConnectorDetails(_) => None,
}
}
}
#[cfg(feature = "v1")]
#[async_trait::async_trait]
impl behaviour::Conversion for Customer {
type DstType = diesel_models::customers::Customer;
type NewDstType = diesel_models::customers::CustomerNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::customers::Customer {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
phone_country_code: self.phone_country_code,
description: self.description,
created_at: self.created_at,
metadata: self.metadata,
modified_at: self.modified_at,
connector_customer: self.connector_customer,
address_id: self.address_id,
default_payment_method_id: self.default_payment_method_id,
updated_by: self.updated_by,
version: self.version,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
})
}
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
_key_store_ref_id: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let decrypted = types::crypto_operation(
state,
common_utils::type_name!(Self::DstType),
types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable(
EncryptedCustomer {
name: item.name.clone(),
phone: item.phone.clone(),
email: item.email.clone(),
tax_registration_id: item.tax_registration_id.clone(),
},
)),
keymanager::Identifier::Merchant(item.merchant_id.clone()),
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
})?;
let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
},
)?;
Ok(Self {
customer_id: item.customer_id,
merchant_id: item.merchant_id,
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
phone_country_code: item.phone_country_code,
description: item.description,
created_at: item.created_at,
metadata: item.metadata,
modified_at: item.modified_at,
connector_customer: item.connector_customer,
address_id: item.address_id,
default_payment_method_id: item.default_payment_method_id,
updated_by: item.updated_by,
version: item.version,
tax_registration_id: encryptable_customer.tax_registration_id,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(diesel_models::customers::CustomerNew {
customer_id: self.customer_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
description: self.description,
phone_country_code: self.phone_country_code,
metadata: self.metadata,
created_at: now,
modified_at: now,
connector_customer: self.connector_customer,
address_id: self.address_id,
updated_by: self.updated_by,
version: self.version,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
})
}
}
#[cfg(feature = "v2")]
#[async_trait::async_trait]
impl behaviour::Conversion for Customer {
type DstType = diesel_models::customers::Customer;
type NewDstType = diesel_models::customers::CustomerNew;
async fn convert(self) -> CustomResult<Self::DstType, ValidationError> {
Ok(diesel_models::customers::Customer {
id: self.id,
merchant_reference_id: self.merchant_reference_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
phone_country_code: self.phone_country_code,
description: self.description,
created_at: self.created_at,
metadata: self.metadata,
modified_at: self.modified_at,
connector_customer: self.connector_customer,
default_payment_method_id: self.default_payment_method_id,
updated_by: self.updated_by,
default_billing_address: self.default_billing_address,
default_shipping_address: self.default_shipping_address,
version: self.version,
status: self.status,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
})
}
async fn convert_back(
state: &KeyManagerState,
item: Self::DstType,
key: &Secret<Vec<u8>>,
_key_store_ref_id: keymanager::Identifier,
) -> CustomResult<Self, ValidationError>
where
Self: Sized,
{
let decrypted = types::crypto_operation(
state,
common_utils::type_name!(Self::DstType),
types::CryptoOperation::BatchDecrypt(EncryptedCustomer::to_encryptable(
EncryptedCustomer {
name: item.name.clone(),
phone: item.phone.clone(),
email: item.email.clone(),
tax_registration_id: item.tax_registration_id.clone(),
},
)),
keymanager::Identifier::Merchant(item.merchant_id.clone()),
key.peek(),
)
.await
.and_then(|val| val.try_into_batchoperation())
.change_context(ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
})?;
let encryptable_customer = EncryptedCustomer::from_encryptable(decrypted).change_context(
ValidationError::InvalidValue {
message: "Failed while decrypting customer data".to_string(),
},
)?;
Ok(Self {
id: item.id,
merchant_reference_id: item.merchant_reference_id,
merchant_id: item.merchant_id,
name: encryptable_customer.name,
email: encryptable_customer.email.map(|email| {
let encryptable: Encryptable<Secret<String, pii::EmailStrategy>> = Encryptable::new(
email.clone().into_inner().switch_strategy(),
email.into_encrypted(),
);
encryptable
}),
phone: encryptable_customer.phone,
phone_country_code: item.phone_country_code,
description: item.description,
created_at: item.created_at,
metadata: item.metadata,
modified_at: item.modified_at,
connector_customer: item.connector_customer,
default_payment_method_id: item.default_payment_method_id,
updated_by: item.updated_by,
default_billing_address: item.default_billing_address,
default_shipping_address: item.default_shipping_address,
version: item.version,
status: item.status,
tax_registration_id: encryptable_customer.tax_registration_id,
})
}
async fn construct_new(self) -> CustomResult<Self::NewDstType, ValidationError> {
let now = date_time::now();
Ok(diesel_models::customers::CustomerNew {
id: self.id,
merchant_reference_id: self.merchant_reference_id,
merchant_id: self.merchant_id,
name: self.name.map(Encryption::from),
email: self.email.map(Encryption::from),
phone: self.phone.map(Encryption::from),
description: self.description,
phone_country_code: self.phone_country_code,
metadata: self.metadata,
default_payment_method_id: None,
created_at: now,
modified_at: now,
connector_customer: self.connector_customer,
updated_by: self.updated_by,
default_billing_address: self.default_billing_address,
default_shipping_address: self.default_shipping_address,
version: common_types::consts::API_VERSION,
status: self.status,
tax_registration_id: self.tax_registration_id.map(Encryption::from),
})
}
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub struct CustomerGeneralUpdate {
pub name: crypto::OptionalEncryptableName,
pub email: Box<crypto::OptionalEncryptableEmail>,
pub phone: Box<crypto::OptionalEncryptablePhone>,
pub description: Option<Description>,
pub phone_country_code: Option<String>,
pub metadata: Option<pii::SecretSerdeValue>,
pub connector_customer: Box<Option<common_types::customers::ConnectorCustomerMap>>,
pub default_billing_address: Option<Encryption>,
pub default_shipping_address: Option<Encryption>,
pub default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>,
pub status: Option<DeleteStatus>,
pub tax_registration_id: crypto::OptionalEncryptableSecretString,
}
#[cfg(feature = "v2")]
#[derive(Clone, Debug)]
pub enum CustomerUpdate {
Update(Box<CustomerGeneralUpdate>),
ConnectorCustomer {
connector_customer: Option<common_types::customers::ConnectorCustomerMap>,
},
UpdateDefaultPaymentMethod {
default_payment_method_id: Option<Option<id_type::GlobalPaymentMethodId>>,
},
}
#[cfg(feature = "v2")]
impl From<CustomerUpdate> for CustomerUpdateInternal {
fn from(customer_update: CustomerUpdate) -> Self {
match customer_update {
CustomerUpdate::Update(update) => {
let CustomerGeneralUpdate {
name,
email,
phone,
description,
phone_country_code,
metadata,
connector_customer,
default_billing_address,
default_shipping_address,
default_payment_method_id,
status,
tax_registration_id,
} = *update;
Self {
name: name.map(Encryption::from),
email: email.map(Encryption::from),
phone: phone.map(Encryption::from),
description,
phone_country_code,
metadata,
connector_customer: *connector_customer,
modified_at: date_time::now(),
default_billing_address,
default_shipping_address,
default_payment_method_id,
updated_by: None,
status,
tax_registration_id: tax_registration_id.map(Encryption::from),
}
}
CustomerUpdate::ConnectorCustomer { connector_customer } => Self {
connector_customer,
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
modified_at: date_time::now(),
default_payment_method_id: None,
updated_by: None,
default_billing_address: None,
default_shipping_address: None,
status: None,
tax_registration_id: None,
},
CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id,
} => Self {
default_payment_method_id,
modified_at: date_time::now(),
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
connector_customer: None,
updated_by: None,
default_billing_address: None,
default_shipping_address: None,
status: None,
tax_registration_id: None,
},
}
}
}
#[cfg(feature = "v1")]
#[derive(Clone, Debug)]
pub enum CustomerUpdate {
Update {
name: crypto::OptionalEncryptableName,
email: crypto::OptionalEncryptableEmail,
phone: Box<crypto::OptionalEncryptablePhone>,
description: Option<Description>,
phone_country_code: Option<String>,
metadata: Box<Option<pii::SecretSerdeValue>>,
connector_customer: Box<Option<pii::SecretSerdeValue>>,
address_id: Option<String>,
tax_registration_id: crypto::OptionalEncryptableSecretString,
},
ConnectorCustomer {
connector_customer: Option<pii::SecretSerdeValue>,
},
UpdateDefaultPaymentMethod {
default_payment_method_id: Option<Option<String>>,
},
}
#[cfg(feature = "v1")]
impl From<CustomerUpdate> for CustomerUpdateInternal {
fn from(customer_update: CustomerUpdate) -> Self {
match customer_update {
CustomerUpdate::Update {
name,
email,
phone,
description,
phone_country_code,
metadata,
connector_customer,
address_id,
tax_registration_id,
} => Self {
name: name.map(Encryption::from),
email: email.map(Encryption::from),
phone: phone.map(Encryption::from),
description,
phone_country_code,
metadata: *metadata,
connector_customer: *connector_customer,
modified_at: date_time::now(),
address_id,
default_payment_method_id: None,
updated_by: None,
tax_registration_id: tax_registration_id.map(Encryption::from),
},
CustomerUpdate::ConnectorCustomer { connector_customer } => Self {
connector_customer,
modified_at: date_time::now(),
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
default_payment_method_id: None,
updated_by: None,
address_id: None,
tax_registration_id: None,
},
CustomerUpdate::UpdateDefaultPaymentMethod {
default_payment_method_id,
} => Self {
default_payment_method_id,
modified_at: date_time::now(),
name: None,
email: None,
phone: None,
description: None,
phone_country_code: None,
metadata: None,
connector_customer: None,
updated_by: None,
address_id: None,
tax_registration_id: None,
},
}
}
}
pub struct CustomerListConstraints {
pub limit: u16,
pub offset: Option<u32>,
}
impl From<CustomerListConstraints> for query::CustomerListConstraints {
fn from(value: CustomerListConstraints) -> Self {
Self {
limit: i64::from(value.limit),
offset: value.offset.map(i64::from),
}
}
}
#[async_trait::async_trait]
pub trait CustomerInterface
where
Customer: behaviour::Conversion<
DstType = storage_types::Customer,
NewDstType = storage_types::CustomerNew,
>,
{
type Error;
#[cfg(feature = "v1")]
async fn delete_customer_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, Self::Error>;
#[cfg(feature = "v1")]
async fn find_customer_optional_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<Customer>, Self::Error>;
#[cfg(feature = "v1")]
async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<Customer>, Self::Error>;
#[cfg(feature = "v2")]
async fn find_optional_by_merchant_id_merchant_reference_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<Customer>, Self::Error>;
#[cfg(feature = "v1")]
#[allow(clippy::too_many_arguments)]
async fn update_customer_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
customer: Customer,
customer_update: CustomerUpdate,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
#[cfg(feature = "v1")]
async fn find_customer_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
#[cfg(feature = "v2")]
async fn find_customer_by_merchant_reference_id_merchant_id(
&self,
state: &KeyManagerState,
merchant_reference_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &MerchantKeyStore,
constraints: CustomerListConstraints,
) -> CustomResult<Vec<Customer>, Self::Error>;
async fn insert_customer(
&self,
customer_data: Customer,
state: &KeyManagerState,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
#[cfg(feature = "v2")]
#[allow(clippy::too_many_arguments)]
async fn update_customer_by_global_id(
&self,
state: &KeyManagerState,
id: &id_type::GlobalCustomerId,
customer: Customer,
customer_update: CustomerUpdate,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
#[cfg(feature = "v2")]
async fn find_customer_by_global_id(
&self,
state: &KeyManagerState,
id: &id_type::GlobalCustomerId,
key_store: &MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Customer, Self::Error>;
}
|
crates/hyperswitch_domain_models/src/customer.rs
|
hyperswitch_domain_models
|
full_file
| 4,954
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl CustomerUpdateInternal {
pub fn apply_changeset(self, source: Customer) -> Customer {
let Self {
name,
email,
phone,
description,
phone_country_code,
metadata,
connector_customer,
address_id,
default_payment_method_id,
tax_registration_id,
..
} = self;
Customer {
name: name.map_or(source.name, Some),
email: email.map_or(source.email, Some),
phone: phone.map_or(source.phone, Some),
description: description.map_or(source.description, Some),
phone_country_code: phone_country_code.map_or(source.phone_country_code, Some),
metadata: metadata.map_or(source.metadata, Some),
modified_at: common_utils::date_time::now(),
connector_customer: connector_customer.map_or(source.connector_customer, Some),
address_id: address_id.map_or(source.address_id, Some),
default_payment_method_id: default_payment_method_id
.flatten()
.map_or(source.default_payment_method_id, Some),
tax_registration_id: tax_registration_id.map_or(source.tax_registration_id, Some),
..source
}
}
}
|
crates/diesel_models/src/customers.rs
|
diesel_models
|
impl_block
| 238
|
rust
| null |
CustomerUpdateInternal
| null |
impl CustomerUpdateInternal
| null | null | null | null | null | null | null | null |
impl SerializableSecret for i8 {}
|
crates/masking/src/serde.rs
|
masking
|
impl_block
| 7
|
rust
| null |
i8
|
SerializableSecret for
|
impl SerializableSecret for for i8
| null | null | null | null | null | null | null | null |
pub async fn payments_update_metadata(
state: web::Data<app::AppState>,
req: actix_web::HttpRequest,
json_payload: web::Json<payment_types::PaymentsUpdateMetadataRequest>,
path: web::Path<common_utils::id_type::PaymentId>,
) -> impl Responder {
let flow = Flow::PaymentsUpdateMetadata;
let payment_id = path.into_inner();
let payload = payment_types::PaymentsUpdateMetadataRequest {
payment_id,
..json_payload.into_inner()
};
tracing::Span::current().record("payment_id", payload.payment_id.get_string_repr());
let header_payload = match HeaderPayload::foreign_try_from(req.headers()) {
Ok(headers) => headers,
Err(err) => {
return api::log_and_return_error_response(err);
}
};
let locking_action = payload.get_locking_input(flow.clone());
Box::pin(api::server_wrap(
flow,
state,
&req,
payload,
|state, auth, req, req_state| {
let merchant_context = domain::MerchantContext::NormalMerchant(Box::new(
domain::Context(auth.merchant_account, auth.key_store),
));
payments::payments_core::<
api_types::UpdateMetadata,
payment_types::PaymentsUpdateMetadataResponse,
_,
_,
_,
payments::PaymentData<api_types::UpdateMetadata>,
>(
state,
req_state,
merchant_context,
auth.profile_id,
payments::PaymentUpdateMetadata,
req,
api::AuthFlow::Client,
payments::CallConnectorAction::Trigger,
None,
header_payload.clone(),
)
},
&auth::HeaderAuth(auth::ApiKeyAuth {
is_connected_allowed: false,
is_platform_allowed: true,
}),
locking_action,
))
.await
}
|
crates/router/src/routes/payments.rs
|
router
|
function_signature
| 390
|
rust
| null | null | null | null |
payments_update_metadata
| null | null | null | null | null | null | null |
pub async fn get_authentication_connector_data(
state: &SessionState,
key_store: &domain::MerchantKeyStore,
business_profile: &domain::Profile,
authentication_connector: Option<String>,
) -> RouterResult<(
common_enums::AuthenticationConnectors,
payments::helpers::MerchantConnectorAccountType,
)> {
let authentication_connector = if let Some(authentication_connector) = authentication_connector
{
api_models::enums::convert_authentication_connector(&authentication_connector).ok_or(
errors::ApiErrorResponse::UnprocessableEntity {
message: format!(
"Invalid authentication_connector found in request : {authentication_connector}",
),
},
)?
} else {
let authentication_details = business_profile
.authentication_connector_details
.clone()
.get_required_value("authentication_details")
.change_context(errors::ApiErrorResponse::UnprocessableEntity {
message: "authentication_connector_details is not available in business profile"
.into(),
})
.attach_printable("authentication_connector_details not configured by the merchant")?;
authentication_details
.authentication_connectors
.first()
.ok_or(errors::ApiErrorResponse::UnprocessableEntity {
message: format!(
"No authentication_connector found for profile_id {:?}",
business_profile.get_id()
),
})
.attach_printable(
"No authentication_connector found from merchant_account.authentication_details",
)?
.to_owned()
};
let profile_id = business_profile.get_id();
let authentication_connector_mca = payments::helpers::get_merchant_connector_account(
state,
&business_profile.merchant_id,
None,
key_store,
profile_id,
authentication_connector.to_string().as_str(),
None,
)
.await?;
Ok((authentication_connector, authentication_connector_mca))
}
|
crates/router/src/core/authentication/utils.rs
|
router
|
function_signature
| 379
|
rust
| null | null | null | null |
get_authentication_connector_data
| null | null | null | null | null | null | null |
pub struct Association {
pub avs_code: Option<String>,
pub security_code_response: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/fiserv/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 23
|
rust
|
Association
| null | null | null | null | null | null | null | null | null | null | null |
File: crates/router/tests/refunds.rs
#![allow(clippy::unwrap_used, clippy::print_stdout)]
use utils::{mk_service, AppClient};
mod utils;
// setting the connector in environment variables doesn't work when run in parallel. Neither does passing the paymentid
// do we'll test refund and payment in same tests and later implement thread_local variables.
// When test-connector feature is enabled, you can pass the connector name in description
#[actix_web::test]
// verify the API-KEY/merchant id has stripe as first choice
async fn refund_create_fail_stripe() {
let app = Box::pin(mk_service()).await;
let client = AppClient::guest();
let user_client = client.user("321");
let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let refund: serde_json::Value = user_client.create_refund(&app, &payment_id, 10).await;
assert_eq!(refund.get("error").unwrap().get("message").unwrap(), "Access forbidden, invalid API key was used. Please create your new API key from the Dashboard Settings section.");
}
#[actix_web::test]
// verify the API-KEY/merchant id has adyen as first choice
async fn refund_create_fail_adyen() {
let app = Box::pin(mk_service()).await;
let client = AppClient::guest();
let user_client = client.user("321");
let payment_id = common_utils::id_type::PaymentId::generate_test_payment_id_for_sample_data();
let refund: serde_json::Value = user_client.create_refund(&app, &payment_id, 10).await;
assert_eq!(refund.get("error").unwrap().get("message").unwrap(), "Access forbidden, invalid API key was used. Please create your new API key from the Dashboard Settings section.");
}
#[actix_web::test]
#[ignore]
async fn refunds_todo() {
Box::pin(utils::setup()).await;
let client = awc::Client::default();
let mut response;
let mut response_body;
let get_endpoints = vec!["list"];
let post_endpoints: Vec<&str> = vec![];
for endpoint in get_endpoints {
response = client
.get(format!("http://127.0.0.1:8080/refunds/{endpoint}"))
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{endpoint} =:= {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
}
for endpoint in post_endpoints {
response = client
.post(format!("http://127.0.0.1:8080/refunds/{endpoint}"))
.send()
.await
.unwrap();
response_body = response.body().await;
println!("{endpoint} =:= {response:?} : {response_body:?}");
assert_eq!(response.status(), awc::http::StatusCode::OK);
}
}
|
crates/router/tests/refunds.rs
|
router
|
full_file
| 669
| null | null | null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.SecretInfoToInitiateSdk
{
"type": "object",
"required": [
"display",
"payment"
],
"properties": {
"display": {
"type": "string"
},
"payment": {
"type": "string"
}
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 74
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"SecretInfoToInitiateSdk"
] | null | null | null | null |
pub struct HubspotProxyConfig {
/// The ID of the Hubspot form to be submitted.
pub form_id: String,
/// The URL to which the Hubspot form data will be sent.
pub request_url: String,
}
|
crates/external_services/src/crm.rs
|
external_services
|
struct_definition
| 50
|
rust
|
HubspotProxyConfig
| null | null | null | null | null | null | null | null | null | null | null |
impl api::RefundSync for Square {}
|
crates/hyperswitch_connectors/src/connectors/square.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Square
|
api::RefundSync for
|
impl api::RefundSync for for Square
| null | null | null | null | null | null | null | null |
pub struct CybersourcePayoutFulfillRequest {
client_reference_information: ClientReferenceInformation,
order_information: OrderInformation,
recipient_information: CybersourceRecipientInfo,
sender_information: CybersourceSenderInfo,
processing_information: CybersourceProcessingInfo,
payment_information: PaymentInformation,
}
|
crates/hyperswitch_connectors/src/connectors/cybersource/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 65
|
rust
|
CybersourcePayoutFulfillRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub struct PaymentToFrmData {
pub amount: Amount,
pub payment_intent: PaymentIntent,
pub payment_attempt: PaymentAttempt,
pub merchant_account: MerchantAccount,
pub address: PaymentAddress,
pub connector_details: ConnectorDetailsCore,
pub order_details: Option<Vec<OrderDetailsWithAmount>>,
pub frm_metadata: Option<SecretSerdeValue>,
}
|
crates/router/src/core/fraud_check/types.rs
|
router
|
struct_definition
| 78
|
rust
|
PaymentToFrmData
| null | null | null | null | null | null | null | null | null | null | null |
pub struct PaymentInitiation {
pub ref_id: String,
pub remittance_information_primary: MerchantId,
pub amount: Amount,
pub local_instrument: LocalInstrument,
pub creditor: Creditor,
pub callback_url: Option<String>,
pub flow_type: FlowType,
}
|
crates/hyperswitch_connectors/src/connectors/tokenio/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 63
|
rust
|
PaymentInitiation
| null | null | null | null | null | null | null | null | null | null | null |
pub fn get_pending_connector_capture_ids(&self) -> Vec<String> {
let pending_connector_capture_ids = self
.get_pending_captures()
.into_iter()
.filter_map(|capture| capture.get_optional_connector_transaction_id().cloned())
.collect();
pending_connector_capture_ids
}
|
crates/router/src/core/payments/types.rs
|
router
|
function_signature
| 66
|
rust
| null | null | null | null |
get_pending_connector_capture_ids
| null | null | null | null | null | null | null |
impl api::RefundExecute for Iatapay {}
|
crates/hyperswitch_connectors/src/connectors/iatapay.rs
|
hyperswitch_connectors
|
impl_block
| 12
|
rust
| null |
Iatapay
|
api::RefundExecute for
|
impl api::RefundExecute for for Iatapay
| null | null | null | null | null | null | null | null |
pub async fn config_key_delete(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<String>,
) -> impl Responder {
let flow = Flow::ConfigKeyDelete;
let key = path.into_inner();
api::server_wrap(
flow,
state,
&req,
key,
|state, _, key, _| configs::config_delete(state, key),
&ADMIN_API_AUTH,
api_locking::LockAction::NotApplicable,
)
.await
}
|
crates/router/src/routes/configs.rs
|
router
|
function_signature
| 113
|
rust
| null | null | null | null |
config_key_delete
| null | null | null | null | null | null | null |
impl CustomerInterface for KafkaStore {
type Error = errors::StorageError;
#[cfg(feature = "v1")]
async fn delete_customer_by_customer_id_merchant_id(
&self,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
) -> CustomResult<bool, errors::StorageError> {
self.diesel_store
.delete_customer_by_customer_id_merchant_id(customer_id, merchant_id)
.await
}
#[cfg(feature = "v1")]
async fn find_customer_optional_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
self.diesel_store
.find_customer_optional_by_customer_id_merchant_id(
state,
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
self.diesel_store
.find_customer_optional_with_redacted_customer_details_by_customer_id_merchant_id(
state,
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_optional_by_merchant_id_merchant_reference_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<Option<domain::Customer>, errors::StorageError> {
self.diesel_store
.find_optional_by_merchant_id_merchant_reference_id(
state,
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v1")]
async fn update_customer_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: id_type::CustomerId,
merchant_id: id_type::MerchantId,
customer: domain::Customer,
customer_update: storage::CustomerUpdate,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.update_customer_by_customer_id_merchant_id(
state,
customer_id,
merchant_id,
customer,
customer_update,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn update_customer_by_global_id(
&self,
state: &KeyManagerState,
id: &id_type::GlobalCustomerId,
customer: domain::Customer,
customer_update: storage::CustomerUpdate,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.update_customer_by_global_id(
state,
id,
customer,
customer_update,
key_store,
storage_scheme,
)
.await
}
async fn list_customers_by_merchant_id(
&self,
state: &KeyManagerState,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
constraints: super::customers::CustomerListConstraints,
) -> CustomResult<Vec<domain::Customer>, errors::StorageError> {
self.diesel_store
.list_customers_by_merchant_id(state, merchant_id, key_store, constraints)
.await
}
#[cfg(feature = "v1")]
async fn find_customer_by_customer_id_merchant_id(
&self,
state: &KeyManagerState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.find_customer_by_customer_id_merchant_id(
state,
customer_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_customer_by_merchant_reference_id_merchant_id(
&self,
state: &KeyManagerState,
merchant_reference_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.find_customer_by_merchant_reference_id_merchant_id(
state,
merchant_reference_id,
merchant_id,
key_store,
storage_scheme,
)
.await
}
#[cfg(feature = "v2")]
async fn find_customer_by_global_id(
&self,
state: &KeyManagerState,
id: &id_type::GlobalCustomerId,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.find_customer_by_global_id(state, id, key_store, storage_scheme)
.await
}
async fn insert_customer(
&self,
customer_data: domain::Customer,
state: &KeyManagerState,
key_store: &domain::MerchantKeyStore,
storage_scheme: MerchantStorageScheme,
) -> CustomResult<domain::Customer, errors::StorageError> {
self.diesel_store
.insert_customer(customer_data, state, key_store, storage_scheme)
.await
}
}
|
crates/router/src/db/kafka_store.rs
|
router
|
impl_block
| 1,380
|
rust
| null |
KafkaStore
|
CustomerInterface for
|
impl CustomerInterface for for KafkaStore
| null | null | null | null | null | null | null | null |
impl api::PaymentVoid for Dwolla {}
|
crates/hyperswitch_connectors/src/connectors/dwolla.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Dwolla
|
api::PaymentVoid for
|
impl api::PaymentVoid for for Dwolla
| null | null | null | null | null | null | null | null |
pub fn handle_tokenization_response<F, Req>(
resp: &mut types::RouterData<F, Req, types::PaymentsResponseData>,
) {
let response = resp.response.clone();
if let Err(err) = response {
if let Some(secret_metadata) = &err.connector_metadata {
let metadata = secret_metadata.clone().expose();
if let Some(token) = metadata
.get("payment_method_token")
.and_then(|t| t.as_str())
{
resp.response = Ok(types::PaymentsResponseData::TokenizationResponse {
token: token.to_string(),
});
}
}
}
}
|
crates/router/src/core/payments/tokenization.rs
|
router
|
function_signature
| 133
|
rust
| null | null | null | null |
handle_tokenization_response
| null | null | null | null | null | null | null |
File: crates/router/src/db/user.rs
use diesel_models::user as storage;
use error_stack::report;
use masking::Secret;
use router_env::{instrument, tracing};
use super::{domain, MockDb};
use crate::{
connection,
core::errors::{self, CustomResult},
services::Store,
};
pub mod sample_data;
pub mod theme;
#[async_trait::async_trait]
pub trait UserInterface {
async fn insert_user(
&self,
user_data: storage::UserNew,
) -> CustomResult<storage::User, errors::StorageError>;
async fn find_user_by_email(
&self,
user_email: &domain::UserEmail,
) -> CustomResult<storage::User, errors::StorageError>;
async fn find_user_by_id(
&self,
user_id: &str,
) -> CustomResult<storage::User, errors::StorageError>;
async fn update_user_by_user_id(
&self,
user_id: &str,
user: storage::UserUpdate,
) -> CustomResult<storage::User, errors::StorageError>;
async fn update_user_by_email(
&self,
user_email: &domain::UserEmail,
user: storage::UserUpdate,
) -> CustomResult<storage::User, errors::StorageError>;
async fn delete_user_by_user_id(
&self,
user_id: &str,
) -> CustomResult<bool, errors::StorageError>;
async fn find_users_by_user_ids(
&self,
user_ids: Vec<String>,
) -> CustomResult<Vec<storage::User>, errors::StorageError>;
}
#[async_trait::async_trait]
impl UserInterface for Store {
#[instrument(skip_all)]
async fn insert_user(
&self,
user_data: storage::UserNew,
) -> CustomResult<storage::User, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
user_data
.insert(&conn)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_user_by_email(
&self,
user_email: &domain::UserEmail,
) -> CustomResult<storage::User, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::User::find_by_user_email(&conn, user_email.get_inner())
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn find_user_by_id(
&self,
user_id: &str,
) -> CustomResult<storage::User, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::User::find_by_user_id(&conn, user_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_user_by_user_id(
&self,
user_id: &str,
user: storage::UserUpdate,
) -> CustomResult<storage::User, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::User::update_by_user_id(&conn, user_id, user)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn update_user_by_email(
&self,
user_email: &domain::UserEmail,
user: storage::UserUpdate,
) -> CustomResult<storage::User, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::User::update_by_user_email(&conn, user_email.get_inner(), user)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
#[instrument(skip_all)]
async fn delete_user_by_user_id(
&self,
user_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let conn = connection::pg_connection_write(self).await?;
storage::User::delete_by_user_id(&conn, user_id)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
async fn find_users_by_user_ids(
&self,
user_ids: Vec<String>,
) -> CustomResult<Vec<storage::User>, errors::StorageError> {
let conn = connection::pg_connection_read(self).await?;
storage::User::find_users_by_user_ids(&conn, user_ids)
.await
.map_err(|error| report!(errors::StorageError::from(error)))
}
}
#[async_trait::async_trait]
impl UserInterface for MockDb {
async fn insert_user(
&self,
user_data: storage::UserNew,
) -> CustomResult<storage::User, errors::StorageError> {
let mut users = self.users.lock().await;
if users
.iter()
.any(|user| user.email == user_data.email || user.user_id == user_data.user_id)
{
Err(errors::StorageError::DuplicateValue {
entity: "email or user_id",
key: None,
})?
}
let time_now = common_utils::date_time::now();
let user = storage::User {
user_id: user_data.user_id,
email: user_data.email,
name: user_data.name,
password: user_data.password,
is_verified: user_data.is_verified,
created_at: user_data.created_at.unwrap_or(time_now),
last_modified_at: user_data.created_at.unwrap_or(time_now),
totp_status: user_data.totp_status,
totp_secret: user_data.totp_secret,
totp_recovery_codes: user_data.totp_recovery_codes,
last_password_modified_at: user_data.last_password_modified_at,
lineage_context: user_data.lineage_context,
};
users.push(user.clone());
Ok(user)
}
async fn find_user_by_email(
&self,
user_email: &domain::UserEmail,
) -> CustomResult<storage::User, errors::StorageError> {
let users = self.users.lock().await;
users
.iter()
.find(|user| user.email.eq(user_email.get_inner()))
.cloned()
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No user available for email = {user_email:?}"
))
.into(),
)
}
async fn find_user_by_id(
&self,
user_id: &str,
) -> CustomResult<storage::User, errors::StorageError> {
let users = self.users.lock().await;
users
.iter()
.find(|user| user.user_id == user_id)
.cloned()
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No user available for user_id = {user_id}"
))
.into(),
)
}
async fn update_user_by_user_id(
&self,
user_id: &str,
update_user: storage::UserUpdate,
) -> CustomResult<storage::User, errors::StorageError> {
let mut users = self.users.lock().await;
let last_modified_at = common_utils::date_time::now();
users
.iter_mut()
.find(|user| user.user_id == user_id)
.map(|user| {
*user = match &update_user {
storage::UserUpdate::VerifyUser => storage::User {
last_modified_at,
is_verified: true,
..user.to_owned()
},
storage::UserUpdate::AccountUpdate { name, is_verified } => storage::User {
name: name.clone().map(Secret::new).unwrap_or(user.name.clone()),
last_modified_at,
is_verified: is_verified.unwrap_or(user.is_verified),
..user.to_owned()
},
storage::UserUpdate::TotpUpdate {
totp_status,
totp_secret,
totp_recovery_codes,
} => storage::User {
last_modified_at,
totp_status: totp_status.unwrap_or(user.totp_status),
totp_secret: totp_secret.clone().or(user.totp_secret.clone()),
totp_recovery_codes: totp_recovery_codes
.clone()
.or(user.totp_recovery_codes.clone()),
..user.to_owned()
},
storage::UserUpdate::PasswordUpdate { password } => storage::User {
password: Some(password.clone()),
last_password_modified_at: Some(common_utils::date_time::now()),
..user.to_owned()
},
storage::UserUpdate::LineageContextUpdate { lineage_context } => {
storage::User {
last_modified_at,
lineage_context: Some(lineage_context.clone()),
..user.to_owned()
}
}
};
user.to_owned()
})
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No user available for user_id = {user_id}"
))
.into(),
)
}
async fn update_user_by_email(
&self,
user_email: &domain::UserEmail,
update_user: storage::UserUpdate,
) -> CustomResult<storage::User, errors::StorageError> {
let mut users = self.users.lock().await;
let last_modified_at = common_utils::date_time::now();
users
.iter_mut()
.find(|user| user.email.eq(user_email.get_inner()))
.map(|user| {
*user = match &update_user {
storage::UserUpdate::VerifyUser => storage::User {
last_modified_at,
is_verified: true,
..user.to_owned()
},
storage::UserUpdate::AccountUpdate { name, is_verified } => storage::User {
name: name.clone().map(Secret::new).unwrap_or(user.name.clone()),
last_modified_at,
is_verified: is_verified.unwrap_or(user.is_verified),
..user.to_owned()
},
storage::UserUpdate::TotpUpdate {
totp_status,
totp_secret,
totp_recovery_codes,
} => storage::User {
last_modified_at,
totp_status: totp_status.unwrap_or(user.totp_status),
totp_secret: totp_secret.clone().or(user.totp_secret.clone()),
totp_recovery_codes: totp_recovery_codes
.clone()
.or(user.totp_recovery_codes.clone()),
..user.to_owned()
},
storage::UserUpdate::PasswordUpdate { password } => storage::User {
password: Some(password.clone()),
last_password_modified_at: Some(common_utils::date_time::now()),
..user.to_owned()
},
storage::UserUpdate::LineageContextUpdate { lineage_context } => {
storage::User {
last_modified_at,
lineage_context: Some(lineage_context.clone()),
..user.to_owned()
}
}
};
user.to_owned()
})
.ok_or(
errors::StorageError::ValueNotFound(format!(
"No user available for user_email = {user_email:?}"
))
.into(),
)
}
async fn delete_user_by_user_id(
&self,
user_id: &str,
) -> CustomResult<bool, errors::StorageError> {
let mut users = self.users.lock().await;
let user_index = users
.iter()
.position(|user| user.user_id == user_id)
.ok_or(errors::StorageError::ValueNotFound(format!(
"No user available for user_id = {user_id}"
)))?;
users.remove(user_index);
Ok(true)
}
async fn find_users_by_user_ids(
&self,
_user_ids: Vec<String>,
) -> CustomResult<Vec<storage::User>, errors::StorageError> {
Err(errors::StorageError::MockDbError)?
}
}
|
crates/router/src/db/user.rs
|
router
|
full_file
| 2,579
| null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/test_utils/tests/connectors/bambora_ui.rs
use serial_test::serial;
use thirtyfour::{prelude::*, WebDriver};
use crate::{selenium::*, tester};
struct BamboraSeleniumTest;
impl SeleniumTest for BamboraSeleniumTest {
fn get_connector_name(&self) -> String {
"bambora".to_string()
}
}
async fn should_make_3ds_payment(c: WebDriver) -> Result<(), WebDriverError> {
let mycon = BamboraSeleniumTest {};
mycon
.make_redirection_payment(
c,
vec![
Event::Trigger(Trigger::Goto(&format!("{CHECKOUT_BASE_URL}/saved/33"))),
Event::Trigger(Trigger::Click(By::Id("card-submit-btn"))),
Event::Trigger(Trigger::Click(By::Id("continue-transaction"))),
Event::Assert(Assert::IsPresent("succeeded")),
],
)
.await?;
Ok(())
}
#[test]
#[serial]
fn should_make_3ds_payment_test() {
tester!(should_make_3ds_payment);
}
|
crates/test_utils/tests/connectors/bambora_ui.rs
|
test_utils
|
full_file
| 239
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct Digitalvirgo {
amount_converter: &'static (dyn AmountConvertor<Output = FloatMajorUnit> + Sync),
}
|
crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs
|
hyperswitch_connectors
|
struct_definition
| 28
|
rust
|
Digitalvirgo
| null | null | null | null | null | null | null | null | null | null | null |
impl api::Refund for Thunes {}
|
crates/hyperswitch_connectors/src/connectors/thunes.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Thunes
|
api::Refund for
|
impl api::Refund for for Thunes
| null | null | null | null | null | null | null | null |
pub fn get_id(&self) -> &common_utils::id_type::ProfileId {
&self.id
}
|
crates/diesel_models/src/business_profile.rs
|
diesel_models
|
function_signature
| 25
|
rust
| null | null | null | null |
get_id
| null | null | null | null | null | null | null |
pub struct NmiRefundRequest {
#[serde(rename = "type")]
transaction_type: TransactionType,
security_key: Secret<String>,
transactionid: String,
orderid: String,
amount: FloatMajorUnit,
}
|
crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 50
|
rust
|
NmiRefundRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub struct AirwallexCardDetails {
expiry_month: Secret<String>,
expiry_year: Secret<String>,
number: cards::CardNumber,
cvc: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/airwallex/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 38
|
rust
|
AirwallexCardDetails
| null | null | null | null | null | null | null | null | null | null | null |
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,
}
|
crates/router/src/types/payment_methods.rs
|
router
|
struct_definition
| 70
|
rust
|
SavedPMLPaymentsInfo
| null | null | null | null | null | null | null | null | null | null | null |
impl PartialEq for ApiEventMetricsBucketIdentifier {
fn eq(&self, other: &Self) -> bool {
let mut left = DefaultHasher::new();
self.hash(&mut left);
let mut right = DefaultHasher::new();
other.hash(&mut right);
left.finish() == right.finish()
}
}
|
crates/api_models/src/analytics/api_event.rs
|
api_models
|
impl_block
| 70
|
rust
| null |
ApiEventMetricsBucketIdentifier
|
PartialEq for
|
impl PartialEq for for ApiEventMetricsBucketIdentifier
| null | null | null | null | null | null | null | null |
impl api::PaymentSession for Klarna {}
|
crates/hyperswitch_connectors/src/connectors/klarna.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Klarna
|
api::PaymentSession for
|
impl api::PaymentSession for for Klarna
| null | null | null | null | null | null | null | null |
pub struct ChargebeeRecordbackInvoice {
pub id: common_utils::id_type::PaymentReferenceId,
}
|
crates/hyperswitch_connectors/src/connectors/chargebee/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 23
|
rust
|
ChargebeeRecordbackInvoice
| null | null | null | null | null | null | null | null | null | null | null |
pub async fn toggle_connector_agnostic_mit(
state: web::Data<AppState>,
req: HttpRequest,
path: web::Path<(
common_utils::id_type::MerchantId,
common_utils::id_type::ProfileId,
)
|
crates/router/src/routes/profiles.rs
|
router
|
function_signature
| 54
|
rust
| null | null | null | null |
toggle_connector_agnostic_mit
| null | null | null | null | null | null | null |
impl SdkEventMetricAccumulator for CountAccumulator {
type MetricOutput = Option<u64>;
#[inline]
fn add_metrics_bucket(&mut self, metrics: &SdkEventMetricRow) {
self.count = match (self.count, metrics.count) {
(None, None) => None,
(None, i @ Some(_)) | (i @ Some(_), None) => i,
(Some(a), Some(b)) => Some(a + b),
}
}
#[inline]
fn collect(self) -> Self::MetricOutput {
self.count.and_then(|i| u64::try_from(i).ok())
}
}
|
crates/analytics/src/sdk_events/accumulator.rs
|
analytics
|
impl_block
| 143
|
rust
| null |
CountAccumulator
|
SdkEventMetricAccumulator for
|
impl SdkEventMetricAccumulator for for CountAccumulator
| null | null | null | null | null | null | null | null |
File: crates/router/src/types/api/configs.rs
Public structs: 2
#[derive(Clone, serde::Serialize, Debug, serde::Deserialize)]
pub struct Config {
pub key: String,
pub value: String,
}
#[derive(Clone, serde::Deserialize, Debug, serde::Serialize)]
pub struct ConfigUpdate {
#[serde(skip_deserializing)]
pub key: String,
pub value: String,
}
|
crates/router/src/types/api/configs.rs
|
router
|
full_file
| 88
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct NmiCaptureRequest {
#[serde(rename = "type")]
pub transaction_type: TransactionType,
pub security_key: Secret<String>,
pub transactionid: String,
pub amount: Option<FloatMajorUnit>,
}
|
crates/hyperswitch_connectors/src/connectors/nmi/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 48
|
rust
|
NmiCaptureRequest
| null | null | null | null | null | null | null | null | null | null | null |
pub fn negation(values: &'a [dir::DirValue], metadata: &'a Metadata) -> Self {
Self {
value: CtxValueKind::Negation(values),
metadata,
}
}
|
crates/euclid/src/dssa/types.rs
|
euclid
|
function_signature
| 45
|
rust
| null | null | null | null |
negation
| null | null | null | null | null | null | null |
File: crates/diesel_models/src/query/payment_method.rs
Public functions: 17
use async_bb8_diesel::AsyncRunQueryDsl;
#[cfg(feature = "v1")]
use diesel::Table;
use diesel::{
associations::HasTable, debug_query, pg::Pg, BoolExpressionMethods, ExpressionMethods, QueryDsl,
};
use error_stack::ResultExt;
use super::generics;
#[cfg(feature = "v1")]
use crate::schema::payment_methods::dsl;
#[cfg(feature = "v2")]
use crate::schema_v2::payment_methods::dsl::{self, id as pm_id};
use crate::{
enums as storage_enums, errors,
payment_method::{self, PaymentMethod, PaymentMethodNew},
PgPooledConn, StorageResult,
};
impl PaymentMethodNew {
pub async fn insert(self, conn: &PgPooledConn) -> StorageResult<PaymentMethod> {
generics::generic_insert(conn, self).await
}
}
#[cfg(feature = "v1")]
impl PaymentMethod {
pub async fn delete_by_payment_method_id(
conn: &PgPooledConn,
payment_method_id: String,
) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, Self>(
conn,
dsl::payment_method_id.eq(payment_method_id),
)
.await
}
pub async fn delete_by_merchant_id_payment_method_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
payment_method_id: &str,
) -> StorageResult<Self> {
generics::generic_delete_one_with_result::<<Self as HasTable>::Table, _, Self>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::payment_method_id.eq(payment_method_id.to_owned())),
)
.await
}
pub async fn find_by_locker_id(conn: &PgPooledConn, locker_id: &str) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::locker_id.eq(locker_id.to_owned()),
)
.await
}
pub async fn find_by_payment_method_id(
conn: &PgPooledConn,
payment_method_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::payment_method_id.eq(payment_method_id.to_owned()),
)
.await
}
pub async fn find_by_merchant_id(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<
<Self as HasTable>::Table,
_,
<<Self as HasTable>::Table as Table>::PrimaryKey,
_,
>(
conn,
dsl::merchant_id.eq(merchant_id.to_owned()),
None,
None,
None,
)
.await
}
pub async fn find_by_customer_id_merchant_id(
conn: &PgPooledConn,
customer_id: &common_utils::id_type::CustomerId,
merchant_id: &common_utils::id_type::MerchantId,
limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned())),
limit,
None,
Some(dsl::last_used_at.desc()),
)
.await
}
pub async fn get_count_by_customer_id_merchant_id_status(
conn: &PgPooledConn,
customer_id: &common_utils::id_type::CustomerId,
merchant_id: &common_utils::id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> StorageResult<i64> {
let filter = <Self as HasTable>::table()
.count()
.filter(
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
.and(dsl::status.eq(status.to_owned())),
)
.into_boxed();
router_env::logger::debug!(query = %debug_query::<Pg, _>(&filter).to_string());
generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
filter.get_result_async::<i64>(conn),
generics::db_metrics::DatabaseOperation::Count,
)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Failed to get a count of payment methods")
}
pub async fn get_count_by_merchant_id_status(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> StorageResult<i64> {
let query = <Self as HasTable>::table().count().filter(
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::status.eq(status.to_owned())),
);
router_env::logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
query.get_result_async::<i64>(conn),
generics::db_metrics::DatabaseOperation::Count,
)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Failed to get a count of payment methods")
}
pub async fn find_by_customer_id_merchant_id_status(
conn: &PgPooledConn,
customer_id: &common_utils::id_type::CustomerId,
merchant_id: &common_utils::id_type::MerchantId,
status: storage_enums::PaymentMethodStatus,
limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
.and(dsl::status.eq(status)),
limit,
None,
Some(dsl::last_used_at.desc()),
)
.await
}
pub async fn update_with_payment_method_id(
self,
conn: &PgPooledConn,
payment_method: payment_method::PaymentMethodUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::payment_method_id.eq(self.payment_method_id.to_owned()),
payment_method,
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
}
#[cfg(feature = "v2")]
impl PaymentMethod {
pub async fn find_by_id(
conn: &PgPooledConn,
id: &common_utils::id_type::GlobalPaymentMethodId,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(conn, pm_id.eq(id.to_owned()))
.await
}
pub async fn find_by_global_customer_id_merchant_id_status(
conn: &PgPooledConn,
customer_id: &common_utils::id_type::GlobalCustomerId,
merchant_id: &common_utils::id_type::MerchantId,
status: storage_enums::PaymentMethodStatus,
limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::customer_id
.eq(customer_id.to_owned())
.and(dsl::merchant_id.eq(merchant_id.to_owned()))
.and(dsl::status.eq(status)),
limit,
None,
Some(dsl::last_used_at.desc()),
)
.await
}
pub async fn find_by_global_customer_id(
conn: &PgPooledConn,
customer_id: &common_utils::id_type::GlobalCustomerId,
limit: Option<i64>,
) -> StorageResult<Vec<Self>> {
generics::generic_filter::<<Self as HasTable>::Table, _, _, _>(
conn,
dsl::customer_id.eq(customer_id.to_owned()),
limit,
None,
Some(dsl::last_used_at.desc()),
)
.await
}
pub async fn update_with_id(
self,
conn: &PgPooledConn,
payment_method: payment_method::PaymentMethodUpdateInternal,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(conn, pm_id.eq(self.id.to_owned()), payment_method)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NoFieldsToUpdate => Ok(self),
_ => Err(error),
},
result => result,
}
}
pub async fn find_by_fingerprint_id(
conn: &PgPooledConn,
fingerprint_id: &str,
) -> StorageResult<Self> {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::locker_fingerprint_id.eq(fingerprint_id.to_owned()),
)
.await
}
pub async fn get_count_by_merchant_id_status(
conn: &PgPooledConn,
merchant_id: &common_utils::id_type::MerchantId,
status: common_enums::PaymentMethodStatus,
) -> StorageResult<i64> {
let query = <Self as HasTable>::table().count().filter(
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::status.eq(status.to_owned())),
);
router_env::logger::debug!(query = %debug_query::<Pg, _>(&query).to_string());
generics::db_metrics::track_database_call::<<Self as HasTable>::Table, _, _>(
query.get_result_async::<i64>(conn),
generics::db_metrics::DatabaseOperation::Count,
)
.await
.change_context(errors::DatabaseError::Others)
.attach_printable("Failed to get a count of payment methods")
}
}
|
crates/diesel_models/src/query/payment_method.rs
|
diesel_models
|
full_file
| 2,340
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct GetnetCaptureRequest {
pub payment: CapturePaymentData,
}
|
crates/hyperswitch_connectors/src/connectors/getnet/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 16
|
rust
|
GetnetCaptureRequest
| null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentToken for Elavon {}
|
crates/hyperswitch_connectors/src/connectors/elavon.rs
|
hyperswitch_connectors
|
impl_block
| 10
|
rust
| null |
Elavon
|
api::PaymentToken for
|
impl api::PaymentToken for for Elavon
| null | null | null | null | null | null | null | null |
pub async fn update_by_merchant_id_authentication_id(
conn: &PgPooledConn,
merchant_id: common_utils::id_type::MerchantId,
authentication_id: common_utils::id_type::AuthenticationId,
authorization_update: AuthenticationUpdate,
) -> StorageResult<Self> {
match generics::generic_update_with_unique_predicate_get_result::<
<Self as HasTable>::Table,
_,
_,
_,
>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::authentication_id.eq(authentication_id.to_owned())),
AuthenticationUpdateInternal::from(authorization_update),
)
.await
{
Err(error) => match error.current_context() {
errors::DatabaseError::NotFound => Err(error.attach_printable(
"Authentication with the given Authentication ID does not exist",
)),
errors::DatabaseError::NoFieldsToUpdate => {
generics::generic_find_one::<<Self as HasTable>::Table, _, _>(
conn,
dsl::merchant_id
.eq(merchant_id.to_owned())
.and(dsl::authentication_id.eq(authentication_id.to_owned())),
)
.await
}
_ => Err(error),
},
result => result,
}
}
|
crates/diesel_models/src/query/authentication.rs
|
diesel_models
|
function_signature
| 274
|
rust
| null | null | null | null |
update_by_merchant_id_authentication_id
| null | null | null | null | null | null | null |
pub struct PaymentsCancelData {
pub amount: Option<i64>,
pub currency: Option<storage_enums::Currency>,
pub connector_transaction_id: String,
pub cancellation_reason: Option<String>,
pub connector_meta: Option<serde_json::Value>,
pub browser_info: Option<BrowserInformation>,
pub metadata: Option<serde_json::Value>,
// This metadata is used to store the metadata shared during the payment intent request.
// minor amount data for amount framework
pub minor_amount: Option<MinorUnit>,
pub webhook_url: Option<String>,
pub capture_method: Option<storage_enums::CaptureMethod>,
}
|
crates/hyperswitch_domain_models/src/router_request_types.rs
|
hyperswitch_domain_models
|
struct_definition
| 135
|
rust
|
PaymentsCancelData
| null | null | null | null | null | null | null | null | null | null | null |
impl ProfileWrapper {
pub fn new(profile: domain::Profile) -> Self {
Self { profile }
}
fn get_routing_config_cache_key(self) -> storage_impl::redis::cache::CacheKind<'static> {
let merchant_id = self.profile.merchant_id.clone();
let profile_id = self.profile.get_id().to_owned();
storage_impl::redis::cache::CacheKind::Routing(
format!(
"routing_config_{}_{}",
merchant_id.get_string_repr(),
profile_id.get_string_repr()
)
.into(),
)
}
pub async fn update_profile_and_invalidate_routing_config_for_active_algorithm_id_update(
self,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
algorithm_id: id_type::RoutingId,
transaction_type: &storage::enums::TransactionType,
) -> RouterResult<()> {
let routing_cache_key = self.clone().get_routing_config_cache_key();
let (routing_algorithm_id, payout_routing_algorithm_id) = match transaction_type {
storage::enums::TransactionType::Payment => (Some(algorithm_id), None),
#[cfg(feature = "payouts")]
storage::enums::TransactionType::Payout => (None, Some(algorithm_id)),
//TODO: Handle ThreeDsAuthentication Transaction Type for Three DS Decision Rule Algorithm configuration
storage::enums::TransactionType::ThreeDsAuthentication => todo!(),
};
let profile_update = domain::ProfileUpdate::RoutingAlgorithmUpdate {
routing_algorithm_id,
payout_routing_algorithm_id,
};
let profile = self.profile;
db.update_profile_by_profile_id(
key_manager_state,
merchant_key_store,
profile,
profile_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref in business profile")?;
storage_impl::redis::cache::redact_from_redis_and_publish(
db.get_cache_store().as_ref(),
[routing_cache_key],
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to invalidate routing cache")?;
Ok(())
}
pub fn get_routing_algorithm_id<'a>(
&'a self,
transaction_data: &'a routing::TransactionData<'_>,
) -> Option<id_type::RoutingId> {
match transaction_data {
routing::TransactionData::Payment(_) => self.profile.routing_algorithm_id.clone(),
#[cfg(feature = "payouts")]
routing::TransactionData::Payout(_) => self.profile.payout_routing_algorithm_id.clone(),
}
}
pub fn get_default_fallback_list_of_connector_under_profile(
&self,
) -> RouterResult<Vec<routing_types::RoutableConnectorChoice>> {
let fallback_connectors =
if let Some(default_fallback_routing) = self.profile.default_fallback_routing.clone() {
default_fallback_routing
.expose()
.parse_value::<Vec<routing_types::RoutableConnectorChoice>>(
"Vec<RoutableConnectorChoice>",
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Business Profile default config has invalid structure")?
} else {
Vec::new()
};
Ok(fallback_connectors)
}
pub fn get_default_routing_configs_from_profile(
&self,
) -> RouterResult<routing_types::ProfileDefaultRoutingConfig> {
let profile_id = self.profile.get_id().to_owned();
let connectors = self.get_default_fallback_list_of_connector_under_profile()?;
Ok(routing_types::ProfileDefaultRoutingConfig {
profile_id,
connectors,
})
}
pub async fn update_default_fallback_routing_of_connectors_under_profile(
self,
db: &dyn StorageInterface,
updated_config: &Vec<routing_types::RoutableConnectorChoice>,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
) -> RouterResult<()> {
let default_fallback_routing = Secret::from(
updated_config
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to convert routing ref to value")?,
);
let profile_update = domain::ProfileUpdate::DefaultRoutingFallbackUpdate {
default_fallback_routing: Some(default_fallback_routing),
};
db.update_profile_by_profile_id(
key_manager_state,
merchant_key_store,
self.profile,
profile_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Failed to update routing algorithm ref in business profile")?;
Ok(())
}
pub async fn update_revenue_recovery_algorithm_under_profile(
self,
db: &dyn StorageInterface,
key_manager_state: &KeyManagerState,
merchant_key_store: &domain::MerchantKeyStore,
revenue_recovery_retry_algorithm_type: common_enums::RevenueRecoveryAlgorithmType,
) -> RouterResult<()> {
let recovery_algorithm_data =
diesel_models::business_profile::RevenueRecoveryAlgorithmData {
monitoring_configured_timestamp: date_time::now(),
};
let profile_update = domain::ProfileUpdate::RevenueRecoveryAlgorithmUpdate {
revenue_recovery_retry_algorithm_type,
revenue_recovery_retry_algorithm_data: Some(recovery_algorithm_data),
};
db.update_profile_by_profile_id(
key_manager_state,
merchant_key_store,
self.profile,
profile_update,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable(
"Failed to update revenue recovery retry algorithm in business profile",
)?;
Ok(())
}
}
|
crates/router/src/core/admin.rs
|
router
|
impl_block
| 1,212
|
rust
| null |
ProfileWrapper
| null |
impl ProfileWrapper
| null | null | null | null | null | null | null | null |
impl Routing {
pub fn server(state: AppState) -> Scope {
web::scope("/v2/routing-algorithms")
.app_data(web::Data::new(state.clone()))
.service(
web::resource("").route(web::post().to(|state, req, payload| {
routing::routing_create_config(state, req, payload, TransactionType::Payment)
})),
)
.service(
web::resource("/{algorithm_id}")
.route(web::get().to(routing::routing_retrieve_config)),
)
}
}
|
crates/router/src/routes/app.rs
|
router
|
impl_block
| 115
|
rust
| null |
Routing
| null |
impl Routing
| null | null | null | null | null | null | null | null |
pub async fn get_connector_choice(
state: &SessionState,
merchant_context: &domain::MerchantContext,
connector: Option<String>,
routing_algorithm: Option<serde_json::Value>,
payout_data: &mut PayoutData,
eligible_connectors: Option<Vec<api_enums::PayoutConnectors>>,
) -> RouterResult<api::ConnectorCallType> {
let eligible_routable_connectors = eligible_connectors.map(|connectors| {
connectors
.into_iter()
.map(api::enums::RoutableConnectors::from)
.collect()
});
let connector_choice = helpers::get_default_payout_connector(state, routing_algorithm).await?;
match connector_choice {
api::ConnectorChoice::SessionMultiple(_) => {
Err(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid connector choice - SessionMultiple")?
}
api::ConnectorChoice::StraightThrough(straight_through) => {
let request_straight_through: api::routing::StraightThroughAlgorithm = straight_through
.clone()
.parse_value("StraightThroughAlgorithm")
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid straight through routing rules format")?;
payout_data.payout_attempt.routing_info = Some(straight_through);
let mut routing_data = storage::RoutingData {
routed_through: connector,
merchant_connector_id: None,
algorithm: Some(request_straight_through.clone()),
routing_info: PaymentRoutingInfo {
algorithm: None,
pre_routing_results: None,
},
};
helpers::decide_payout_connector(
state,
merchant_context,
Some(request_straight_through),
&mut routing_data,
payout_data,
eligible_routable_connectors,
)
.await
}
api::ConnectorChoice::Decide => {
let mut routing_data = storage::RoutingData {
routed_through: connector,
merchant_connector_id: None,
algorithm: None,
routing_info: PaymentRoutingInfo {
algorithm: None,
pre_routing_results: None,
},
};
helpers::decide_payout_connector(
state,
merchant_context,
None,
&mut routing_data,
payout_data,
eligible_routable_connectors,
)
.await
}
}
}
|
crates/router/src/core/payouts.rs
|
router
|
function_signature
| 489
|
rust
| null | null | null | null |
get_connector_choice
| null | null | null | null | null | null | null |
File: crates/masking/src/strong_secret.rs
Public functions: 1
Public structs: 1
//! Structure describing secret.
use std::{fmt, marker::PhantomData};
use subtle::ConstantTimeEq;
use zeroize::{self, Zeroize as ZeroizableSecret};
use crate::{strategy::Strategy, PeekInterface};
/// Secret thing.
///
/// To get access to value use method `expose()` of trait [`crate::ExposeInterface`].
pub struct StrongSecret<Secret: ZeroizableSecret, MaskingStrategy = crate::WithType> {
/// Inner secret value
pub(crate) inner_secret: Secret,
pub(crate) masking_strategy: PhantomData<MaskingStrategy>,
}
impl<Secret: ZeroizableSecret, MaskingStrategy> StrongSecret<Secret, MaskingStrategy> {
/// Take ownership of a secret value
pub fn new(secret: Secret) -> Self {
Self {
inner_secret: secret,
masking_strategy: PhantomData,
}
}
}
impl<Secret: ZeroizableSecret, MaskingStrategy> PeekInterface<Secret>
for StrongSecret<Secret, MaskingStrategy>
{
fn peek(&self) -> &Secret {
&self.inner_secret
}
fn peek_mut(&mut self) -> &mut Secret {
&mut self.inner_secret
}
}
impl<Secret: ZeroizableSecret, MaskingStrategy> From<Secret>
for StrongSecret<Secret, MaskingStrategy>
{
fn from(secret: Secret) -> Self {
Self::new(secret)
}
}
impl<Secret: Clone + ZeroizableSecret, MaskingStrategy> Clone
for StrongSecret<Secret, MaskingStrategy>
{
fn clone(&self) -> Self {
Self {
inner_secret: self.inner_secret.clone(),
masking_strategy: PhantomData,
}
}
}
impl<Secret, MaskingStrategy> PartialEq for StrongSecret<Secret, MaskingStrategy>
where
Self: PeekInterface<Secret>,
Secret: ZeroizableSecret + StrongEq,
{
fn eq(&self, other: &Self) -> bool {
StrongEq::strong_eq(self.peek(), other.peek())
}
}
impl<Secret, MaskingStrategy> Eq for StrongSecret<Secret, MaskingStrategy>
where
Self: PeekInterface<Secret>,
Secret: ZeroizableSecret + StrongEq,
{
}
impl<Secret: ZeroizableSecret, MaskingStrategy: Strategy<Secret>> fmt::Debug
for StrongSecret<Secret, MaskingStrategy>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
MaskingStrategy::fmt(&self.inner_secret, f)
}
}
impl<Secret: ZeroizableSecret, MaskingStrategy: Strategy<Secret>> fmt::Display
for StrongSecret<Secret, MaskingStrategy>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
MaskingStrategy::fmt(&self.inner_secret, f)
}
}
impl<Secret: ZeroizableSecret, MaskingStrategy> Default for StrongSecret<Secret, MaskingStrategy>
where
Secret: ZeroizableSecret + Default,
{
fn default() -> Self {
Secret::default().into()
}
}
impl<Secret: ZeroizableSecret, MaskingStrategy> Drop for StrongSecret<Secret, MaskingStrategy> {
fn drop(&mut self) {
self.inner_secret.zeroize();
}
}
trait StrongEq {
fn strong_eq(&self, other: &Self) -> bool;
}
impl StrongEq for String {
fn strong_eq(&self, other: &Self) -> bool {
let lhs = self.as_bytes();
let rhs = other.as_bytes();
bool::from(lhs.ct_eq(rhs))
}
}
impl StrongEq for Vec<u8> {
fn strong_eq(&self, other: &Self) -> bool {
let lhs = &self;
let rhs = &other;
bool::from(lhs.ct_eq(rhs))
}
}
#[cfg(feature = "proto_tonic")]
impl<T> prost::Message for StrongSecret<T, crate::WithType>
where
T: prost::Message + Default + Clone + ZeroizableSecret,
{
fn encode_raw(&self, buf: &mut impl bytes::BufMut) {
self.peek().encode_raw(buf);
}
fn merge_field(
&mut self,
tag: u32,
wire_type: prost::encoding::WireType,
buf: &mut impl bytes::Buf,
ctx: prost::encoding::DecodeContext,
) -> Result<(), prost::DecodeError> {
if tag == 1 {
self.peek_mut().merge_field(tag, wire_type, buf, ctx)
} else {
prost::encoding::skip_field(wire_type, tag, buf, ctx)
}
}
fn encoded_len(&self) -> usize {
self.peek().encoded_len()
}
fn clear(&mut self) {
self.peek_mut().clear();
}
}
|
crates/masking/src/strong_secret.rs
|
masking
|
full_file
| 1,061
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct GetParentGroupsInfoQueryParams {
pub entity_type: Option<EntityType>,
}
|
crates/api_models/src/user_role/role.rs
|
api_models
|
struct_definition
| 19
|
rust
|
GetParentGroupsInfoQueryParams
| null | null | null | null | null | null | null | null | null | null | null |
pub struct MandateOption {
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub accepted_at: Option<PrimitiveDateTime>,
pub user_agent: Option<String>,
pub ip_address: Option<masking::Secret<String, IpAddress>>,
pub mandate_type: Option<StripeMandateType>,
pub amount: Option<i64>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub start_date: Option<PrimitiveDateTime>,
#[serde(default, with = "common_utils::custom_serde::timestamp::option")]
pub end_date: Option<PrimitiveDateTime>,
}
|
crates/router/src/compatibility/stripe/payment_intents/types.rs
|
router
|
struct_definition
| 140
|
rust
|
MandateOption
| null | null | null | null | null | null | null | null | null | null | null |
OpenAPI Block Path: components.schemas.SdkNextAction
{
"type": "object",
"required": [
"next_action"
],
"properties": {
"next_action": {
"$ref": "#/components/schemas/NextActionCall"
}
}
}
|
./hyperswitch/api-reference/v1/openapi_spec_v1.json
| null |
openapi_block
| 62
|
.json
| null | null | null | null | null |
openapi_spec
|
components
|
[
"schemas",
"SdkNextAction"
] | null | null | null | null |
impl Responder {
let flow = AnalyticsFlow::GetSdkEvents;
Box::pin(api::server_wrap(
flow,
state,
&req,
json_payload.into_inner(),
|state, auth: AuthenticationData, req, _| async move {
utils::check_if_profile_id_is_present_in_payment_intent(
req.payment_id.clone(),
&state,
&auth,
)
.await
.change_context(AnalyticsError::AccessForbiddenError)?;
sdk_events_core(&state.pool, req, &auth.merchant_account.publishable_key)
.await
.map(ApplicationResponse::Json)
},
&auth::JWTAuth {
permission: Permission::ProfileAnalyticsRead,
},
api_locking::LockAction::NotApplicable,
))
.await
}
|
crates/router/src/analytics.rs
|
router
|
impl_block
| 171
|
rust
| null |
Responder
| null |
impl Responder
| null | null | null | null | null | null | null | null |
impl ConnectorValidation for Helcim {
fn validate_connector_against_payment_request(
&self,
capture_method: Option<enums::CaptureMethod>,
_payment_method: enums::PaymentMethod,
_pmt: Option<enums::PaymentMethodType>,
) -> CustomResult<(), errors::ConnectorError> {
let capture_method = capture_method.unwrap_or_default();
match capture_method {
enums::CaptureMethod::Automatic
| enums::CaptureMethod::Manual
| enums::CaptureMethod::SequentialAutomatic => Ok(()),
enums::CaptureMethod::ManualMultiple | enums::CaptureMethod::Scheduled => Err(
crate::utils::construct_not_supported_error_report(capture_method, self.id()),
),
}
}
}
|
crates/hyperswitch_connectors/src/connectors/helcim.rs
|
hyperswitch_connectors
|
impl_block
| 155
|
rust
| null |
Helcim
|
ConnectorValidation for
|
impl ConnectorValidation for for Helcim
| null | null | null | null | null | null | null | null |
}
#[derive(Deserialize, Debug, Serialize)]
pub struct ActionResponse {
#[serde(rename = "id")]
pub action_id: String,
pub amount: MinorUnit,
#[serde(rename = "type")]
pub action_type: ActionType,
pub approved: Option<bool>,
pub reference: Option<String>,
}
impl From<&ActionResponse> for enums::RefundStatus {
fn from(item: &ActionResponse) -> Self {
match item.approved {
Some(true) => Self::Success,
Some(false) => Self::Failure,
None => Self::Pending,
}
}
}
impl utils::MultipleCaptureSyncResponse for ActionResponse {
fn get_connector_capture_id(&self) -> String {
self.action_id.clone()
}
fn get_capture_attempt_status(&self) -> AttemptStatus {
match self.approved {
Some(true) => AttemptStatus::Charged,
Some(false) => AttemptStatus::Failure,
None => AttemptStatus::Pending,
}
}
fn get_connector_reference_id(&self) -> Option<String> {
self.reference.clone()
}
fn is_capture_response(&self) -> bool {
self.action_type == ActionType::Capture
}
fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>> {
Ok(Some(self.amount))
}
}
impl utils::MultipleCaptureSyncResponse for Box<PaymentsResponse> {
fn get_connector_capture_id(&self) -> String {
self.action_id.clone().unwrap_or("".into())
}
fn get_capture_attempt_status(&self) -> AttemptStatus {
get_attempt_status_bal((self.status.clone(), self.balances.clone()))
}
fn get_connector_reference_id(&self) -> Option<String> {
self.reference.clone()
}
fn is_capture_response(&self) -> bool {
self.status == CheckoutPaymentStatus::Captured
}
fn get_amount_captured(&self) -> Result<Option<MinorUnit>, error_stack::Report<ParsingError>> {
Ok(self.amount)
}
}
#[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)]
#[serde(rename_all = "lowercase")]
pub enum CheckoutRedirectResponseStatus {
Success,
Failure,
}
#[derive(Debug, Clone, serde::Deserialize, Eq, PartialEq)]
pub struct CheckoutRedirectResponse {
pub status: Option<CheckoutRedirectResponseStatus>,
#[serde(rename = "cko-session-id")]
pub cko_session_id: Option<String>,
}
impl TryFrom<RefundsResponseRouterData<Execute, &ActionResponse>> for RefundsRouterData<Execute> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, &ActionResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.action_id.clone(),
refund_status,
}),
..item.data
})
}
}
impl TryFrom<RefundsResponseRouterData<RSync, &ActionResponse>> for RefundsRouterData<RSync> {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, &ActionResponse>,
) -> Result<Self, Self::Error> {
let refund_status = enums::RefundStatus::from(item.response);
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.action_id.clone(),
refund_status,
}),
..item.data
})
}
}
impl From<CheckoutRedirectResponseStatus> for AttemptStatus {
fn from(item: CheckoutRedirectResponseStatus) -> Self {
match item {
CheckoutRedirectResponseStatus::Success => Self::AuthenticationSuccessful,
CheckoutRedirectResponseStatus::Failure => Self::Failure,
}
}
}
pub fn is_refund_event(event_code: &CheckoutWebhookEventType) -> bool {
matches!(
event_code,
CheckoutWebhookEventType::PaymentRefunded | CheckoutWebhookEventType::PaymentRefundDeclined
)
}
pub fn is_chargeback_event(event_code: &CheckoutWebhookEventType) -> bool {
matches!(
event_code,
CheckoutWebhookEventType::DisputeReceived
| CheckoutWebhookEventType::DisputeExpired
| CheckoutWebhookEventType::DisputeAccepted
| CheckoutWebhookEventType::DisputeCanceled
| CheckoutWebhookEventType::DisputeEvidenceSubmitted
| CheckoutWebhookEventType::DisputeEvidenceAcknowledgedByScheme
| CheckoutWebhookEventType::DisputeEvidenceRequired
| CheckoutWebhookEventType::DisputeArbitrationLost
| CheckoutWebhookEventType::DisputeArbitrationWon
| CheckoutWebhookEventType::DisputeWon
| CheckoutWebhookEventType::DisputeLost
)
}
#[derive(Debug, Deserialize, strum::Display, Clone)]
#[serde(rename_all = "snake_case")]
pub enum CheckoutWebhookEventType {
AuthenticationStarted,
AuthenticationApproved,
AuthenticationAttempted,
AuthenticationExpired,
AuthenticationFailed,
PaymentApproved,
PaymentCaptured,
PaymentDeclined,
PaymentRefunded,
PaymentRefundDeclined,
PaymentAuthenticationFailed,
PaymentCanceled,
PaymentCaptureDeclined,
PaymentVoided,
DisputeReceived,
DisputeExpired,
DisputeAccepted,
DisputeCanceled,
DisputeEvidenceSubmitted,
DisputeEvidenceAcknowledgedByScheme,
DisputeEvidenceRequired,
DisputeArbitrationLost,
DisputeArbitrationWon,
DisputeWon,
DisputeLost,
#[serde(other)]
Unknown,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookEventTypeBody {
#[serde(rename = "type")]
pub transaction_type: CheckoutWebhookEventType,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookData {
pub id: String,
pub payment_id: Option<String>,
pub action_id: Option<String>,
pub reference: Option<String>,
pub amount: MinorUnit,
pub balances: Option<Balances>,
pub response_code: Option<String>,
pub response_summary: Option<String>,
pub currency: String,
pub processed_on: Option<String>,
pub approved: Option<bool>,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookBody {
#[serde(rename = "type")]
pub transaction_type: CheckoutWebhookEventType,
pub data: CheckoutWebhookData,
#[serde(rename = "_links")]
pub links: Links,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct CheckoutDisputeWebhookData {
pub id: String,
pub payment_id: Option<String>,
pub action_id: Option<String>,
pub amount: MinorUnit,
pub currency: enums::Currency,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub evidence_required_by: Option<PrimitiveDateTime>,
pub reason_code: Option<String>,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub date: Option<PrimitiveDateTime>,
}
#[derive(Debug, Deserialize)]
pub struct CheckoutDisputeWebhookBody {
#[serde(rename = "type")]
pub transaction_type: CheckoutDisputeTransactionType,
pub data: CheckoutDisputeWebhookData,
#[serde(default, with = "common_utils::custom_serde::iso8601::option")]
pub created_on: Option<PrimitiveDateTime>,
}
#[derive(Debug, Deserialize, strum::Display, Clone)]
#[serde(rename_all = "snake_case")]
pub enum CheckoutDisputeTransactionType {
DisputeReceived,
DisputeExpired,
DisputeAccepted,
DisputeCanceled,
DisputeEvidenceSubmitted,
DisputeEvidenceAcknowledgedByScheme,
DisputeEvidenceRequired,
DisputeArbitrationLost,
DisputeArbitrationWon,
DisputeWon,
DisputeLost,
}
impl From<CheckoutWebhookEventType> for api_models::webhooks::IncomingWebhookEvent {
fn from(transaction_type: CheckoutWebhookEventType) -> Self {
match transaction_type {
CheckoutWebhookEventType::AuthenticationStarted
| CheckoutWebhookEventType::AuthenticationApproved
| CheckoutWebhookEventType::AuthenticationAttempted => Self::EventNotSupported,
CheckoutWebhookEventType::AuthenticationExpired
| CheckoutWebhookEventType::AuthenticationFailed
| CheckoutWebhookEventType::PaymentAuthenticationFailed => {
Self::PaymentIntentAuthorizationFailure
}
CheckoutWebhookEventType::PaymentApproved => Self::EventNotSupported,
CheckoutWebhookEventType::PaymentCaptured => Self::PaymentIntentSuccess,
CheckoutWebhookEventType::PaymentDeclined => Self::PaymentIntentFailure,
CheckoutWebhookEventType::PaymentRefunded => Self::RefundSuccess,
CheckoutWebhookEventType::PaymentRefundDeclined => Self::RefundFailure,
CheckoutWebhookEventType::PaymentCanceled => Self::PaymentIntentCancelFailure,
CheckoutWebhookEventType::PaymentCaptureDeclined => Self::PaymentIntentCaptureFailure,
CheckoutWebhookEventType::PaymentVoided => Self::PaymentIntentCancelled,
CheckoutWebhookEventType::DisputeReceived
| CheckoutWebhookEventType::DisputeEvidenceRequired => Self::DisputeOpened,
CheckoutWebhookEventType::DisputeExpired => Self::DisputeExpired,
CheckoutWebhookEventType::DisputeAccepted => Self::DisputeAccepted,
CheckoutWebhookEventType::DisputeCanceled => Self::DisputeCancelled,
CheckoutWebhookEventType::DisputeEvidenceSubmitted
| CheckoutWebhookEventType::DisputeEvidenceAcknowledgedByScheme => {
Self::DisputeChallenged
}
CheckoutWebhookEventType::DisputeWon
| CheckoutWebhookEventType::DisputeArbitrationWon => Self::DisputeWon,
CheckoutWebhookEventType::DisputeLost
| CheckoutWebhookEventType::DisputeArbitrationLost => Self::DisputeLost,
CheckoutWebhookEventType::Unknown => Self::EventNotSupported,
}
}
}
impl From<CheckoutDisputeTransactionType> for api_models::enums::DisputeStage {
fn from(code: CheckoutDisputeTransactionType) -> Self {
match code {
CheckoutDisputeTransactionType::DisputeArbitrationLost
| CheckoutDisputeTransactionType::DisputeArbitrationWon => Self::PreArbitration,
CheckoutDisputeTransactionType::DisputeReceived
| CheckoutDisputeTransactionType::DisputeExpired
| CheckoutDisputeTransactionType::DisputeAccepted
| CheckoutDisputeTransactionType::DisputeCanceled
| CheckoutDisputeTransactionType::DisputeEvidenceSubmitted
| CheckoutDisputeTransactionType::DisputeEvidenceAcknowledgedByScheme
| CheckoutDisputeTransactionType::DisputeEvidenceRequired
| CheckoutDisputeTransactionType::DisputeWon
| CheckoutDisputeTransactionType::DisputeLost => Self::Dispute,
}
}
}
#[derive(Debug, Deserialize)]
pub struct CheckoutWebhookObjectResource {
pub data: serde_json::Value,
}
pub fn construct_file_upload_request(
file_upload_router_data: UploadFileRouterData,
) -> CustomResult<reqwest::multipart::Form, errors::ConnectorError> {
let request = file_upload_router_data.request;
let mut multipart = reqwest::multipart::Form::new();
multipart = multipart.text("purpose", "dispute_evidence");
let file_data = reqwest::multipart::Part::bytes(request.file)
.file_name(format!(
"{}.{}",
request.file_key,
request
.file_type
.as_ref()
.split('/')
.next_back()
.unwrap_or_default()
))
.mime_str(request.file_type.as_ref())
.change_context(errors::ConnectorError::RequestEncodingFailed)
.attach_printable("Failure in constructing file data")?;
multipart = multipart.part("file", file_data);
Ok(multipart)
}
#[derive(Debug, Deserialize, Serialize)]
pub struct FileUploadResponse {
#[serde(rename = "id")]
pub file_id: String,
}
#[derive(Default, Debug, Serialize)]
pub struct Evidence {
pub proof_of_delivery_or_service_file: Option<String>,
pub invoice_or_receipt_file: Option<String>,
pub invoice_showing_distinct_transactions_file: Option<String>,
pub customer_communication_file: Option<String>,
pub refund_or_cancellation_policy_file: Option<String>,
pub recurring_transaction_agreement_file: Option<String>,
pub additional_evidence_file: Option<String>,
}
impl TryFrom<&webhooks::IncomingWebhookRequestDetails<'_>> for PaymentsResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> Result<Self, Self::Error> {
let details: CheckoutWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let data = details.data;
let psync_struct = Self {
id: data.payment_id.unwrap_or(data.id),
amount: Some(data.amount),
status: CheckoutPaymentStatus::try_from(details.transaction_type)?,
links: details.links,
balances: data.balances,
reference: data.reference,
response_code: data.response_code,
response_summary: data.response_summary,
action_id: data.action_id,
currency: Some(data.currency),
processed_on: data.processed_on,
approved: data.approved,
};
Ok(psync_struct)
}
}
impl TryFrom<&webhooks::IncomingWebhookRequestDetails<'_>> for RefundResponse {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> Result<Self, Self::Error> {
let details: CheckoutWebhookBody = request
.body
.parse_struct("CheckoutWebhookBody")
.change_context(errors::ConnectorError::WebhookBodyDecodingFailed)?;
let data = details.data;
let refund_struct = Self {
action_id: data
.action_id
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,
reference: data
.reference
.ok_or(errors::ConnectorError::WebhookBodyDecodingFailed)?,
};
Ok(refund_struct)
}
}
impl TryFrom<&SubmitEvidenceRouterData> for Evidence {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &SubmitEvidenceRouterData) -> Result<Self, Self::Error> {
let submit_evidence_request_data = item.request.clone();
Ok(Self {
proof_of_delivery_or_service_file: submit_evidence_request_data
.shipping_documentation_provider_file_id,
invoice_or_receipt_file: submit_evidence_request_data.receipt_provider_file_id,
invoice_showing_distinct_transactions_file: submit_evidence_request_data
.invoice_showing_distinct_transactions_provider_file_id,
customer_communication_file: submit_evidence_request_data
.customer_communication_provider_file_id,
refund_or_cancellation_policy_file: submit_evidence_request_data
.refund_policy_provider_file_id,
recurring_transaction_agreement_file: submit_evidence_request_data
.recurring_transaction_agreement_provider_file_id,
additional_evidence_file: submit_evidence_request_data
.uncategorized_file_provider_file_id,
})
}
}
impl From<String> for utils::ErrorCodeAndMessage {
fn from(error: String) -> Self {
Self {
error_code: error.clone(),
error_message: error,
}
}
}
|
crates/hyperswitch_connectors/src/connectors/checkout/transformers.rs#chunk1
|
hyperswitch_connectors
|
chunk
| 3,396
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct ThreeDsChallenge {
pub reference: String,
pub url: Url,
pub jwt: Secret<String>,
pub payload: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/worldpay/response.rs
|
hyperswitch_connectors
|
struct_definition
| 33
|
rust
|
ThreeDsChallenge
| null | null | null | null | null | null | null | null | null | null | null |
state: &'a SessionState,
connector: &'a api::ConnectorData,
customer: &'a Option<domain::Customer>,
merchant_connector_id: &'a domain::MerchantConnectorAccountTypeDetails,
) -> (bool, Option<&'a str>) {
// Check if create customer is required for the connector
match enums::PayoutConnectors::try_from(connector.connector_name) {
Ok(connector) => {
let connector_needs_customer = state
.conf
.connector_customer
.payout_connector_list
.contains(&connector);
if connector_needs_customer {
let connector_customer_details = customer
.as_ref()
.and_then(|customer| customer.get_connector_customer_id(merchant_connector_id));
let should_call_connector = connector_customer_details.is_none();
(should_call_connector, connector_customer_details)
} else {
(false, None)
}
}
_ => (false, None),
}
}
pub async fn get_gsm_record(
state: &SessionState,
error_code: Option<String>,
error_message: Option<String>,
connector_name: Option<String>,
flow: &str,
) -> Option<hyperswitch_domain_models::gsm::GatewayStatusMap> {
let connector_name = connector_name.unwrap_or_default();
let get_gsm = || async {
state.store.find_gsm_rule(
connector_name.clone(),
flow.to_string(),
"sub_flow".to_string(),
error_code.clone().unwrap_or_default(), // TODO: make changes in connector to get a mandatory code in case of success or error response
error_message.clone().unwrap_or_default(),
)
.await
.map_err(|err| {
if err.current_context().is_db_not_found() {
logger::warn!(
"GSM miss for connector - {}, flow - {}, error_code - {:?}, error_message - {:?}",
connector_name,
flow,
error_code,
error_message
);
metrics::AUTO_PAYOUT_RETRY_GSM_MISS_COUNT.add( 1, &[]);
} else {
metrics::AUTO_PAYOUT_RETRY_GSM_FETCH_FAILURE_COUNT.add( 1, &[]);
};
err.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("failed to fetch decision from gsm")
})
};
get_gsm()
.await
.inspect_err(|err| {
// warn log should suffice here because we are not propagating this error
logger::warn!(get_gsm_decision_fetch_error=?err, "error fetching gsm decision");
})
.ok()
}
pub fn is_payout_initiated(status: api_enums::PayoutStatus) -> bool {
!matches!(
status,
api_enums::PayoutStatus::RequiresCreation
| api_enums::PayoutStatus::RequiresConfirmation
| api_enums::PayoutStatus::RequiresPayoutMethodData
| api_enums::PayoutStatus::RequiresVendorAccountCreation
| api_enums::PayoutStatus::Initiated
)
}
pub(crate) fn validate_payout_status_against_not_allowed_statuses(
payout_status: api_enums::PayoutStatus,
not_allowed_statuses: &[api_enums::PayoutStatus],
action: &'static str,
) -> Result<(), errors::ApiErrorResponse> {
fp_utils::when(not_allowed_statuses.contains(&payout_status), || {
Err(errors::ApiErrorResponse::PreconditionFailed {
message: format!(
"You cannot {action} this payout because it has status {payout_status}",
),
})
})
}
pub fn is_payout_terminal_state(status: api_enums::PayoutStatus) -> bool {
!matches!(
status,
api_enums::PayoutStatus::RequiresCreation
| api_enums::PayoutStatus::RequiresConfirmation
| api_enums::PayoutStatus::RequiresPayoutMethodData
| api_enums::PayoutStatus::RequiresVendorAccountCreation
// Initiated by the underlying connector
| api_enums::PayoutStatus::Pending
| api_enums::PayoutStatus::Initiated
| api_enums::PayoutStatus::RequiresFulfillment
)
}
pub fn should_call_retrieve(status: api_enums::PayoutStatus) -> bool {
matches!(
status,
api_enums::PayoutStatus::Pending | api_enums::PayoutStatus::Initiated
)
}
pub fn is_payout_err_state(status: api_enums::PayoutStatus) -> bool {
matches!(
status,
api_enums::PayoutStatus::Cancelled
| api_enums::PayoutStatus::Failed
| api_enums::PayoutStatus::Ineligible
)
}
pub fn is_eligible_for_local_payout_cancellation(status: api_enums::PayoutStatus) -> bool {
matches!(
status,
api_enums::PayoutStatus::RequiresCreation
| api_enums::PayoutStatus::RequiresConfirmation
| api_enums::PayoutStatus::RequiresPayoutMethodData
| api_enums::PayoutStatus::RequiresVendorAccountCreation
)
}
#[cfg(feature = "olap")]
pub(super) async fn filter_by_constraints(
db: &dyn StorageInterface,
constraints: &api::PayoutListConstraints,
merchant_id: &id_type::MerchantId,
storage_scheme: storage::enums::MerchantStorageScheme,
) -> CustomResult<Vec<storage::Payouts>, errors::StorageError> {
let result = db
.filter_payouts_by_constraints(merchant_id, &constraints.clone().into(), storage_scheme)
.await?;
Ok(result)
}
#[cfg(feature = "v2")]
pub async fn update_payouts_and_payout_attempt(
_payout_data: &mut PayoutData,
_merchant_context: &domain::MerchantContext,
_req: &payouts::PayoutCreateRequest,
_state: &SessionState,
) -> CustomResult<(), errors::ApiErrorResponse> {
todo!()
}
#[cfg(feature = "v1")]
pub async fn update_payouts_and_payout_attempt(
payout_data: &mut PayoutData,
merchant_context: &domain::MerchantContext,
req: &payouts::PayoutCreateRequest,
state: &SessionState,
) -> CustomResult<(), errors::ApiErrorResponse> {
let payout_attempt = payout_data.payout_attempt.to_owned();
let status = payout_attempt.status;
let payout_id = payout_attempt.payout_id.clone();
// Verify update feasibility
if is_payout_terminal_state(status) || is_payout_initiated(status) {
return Err(report!(errors::ApiErrorResponse::InvalidRequestData {
message: format!(
"Payout {} cannot be updated for status {status}",
payout_id.get_string_repr()
),
}));
}
// Fetch customer details from request and create new or else use existing customer that was attached
let customer = get_customer_details_from_request(req);
let customer_id = if customer.customer_id.is_some()
|| customer.name.is_some()
|| customer.email.is_some()
|| customer.phone.is_some()
|| customer.phone_country_code.is_some()
{
payout_data.customer_details =
get_or_create_customer_details(state, &customer, merchant_context).await?;
payout_data
.customer_details
.as_ref()
.map(|customer| customer.customer_id.clone())
} else {
payout_data.payouts.customer_id.clone()
};
let (billing_address, address_id) = resolve_billing_address_for_payout(
state,
req.billing.as_ref(),
payout_data.payouts.address_id.as_ref(),
payout_data.payment_method.as_ref(),
merchant_context,
customer_id.as_ref(),
&payout_id,
)
.await?;
// Update payout state with resolved billing address
payout_data.billing_address = billing_address;
// Update DB with new data
let payouts = payout_data.payouts.to_owned();
let amount = MinorUnit::from(req.amount.unwrap_or(payouts.amount.into()));
let updated_payouts = storage::PayoutsUpdate::Update {
amount,
destination_currency: req
.currency
.to_owned()
.unwrap_or(payouts.destination_currency),
source_currency: req.currency.to_owned().unwrap_or(payouts.source_currency),
description: req
.description
.to_owned()
.clone()
.or(payouts.description.clone()),
recurring: req.recurring.to_owned().unwrap_or(payouts.recurring),
auto_fulfill: req.auto_fulfill.to_owned().unwrap_or(payouts.auto_fulfill),
return_url: req
.return_url
.to_owned()
.clone()
.or(payouts.return_url.clone()),
entity_type: req.entity_type.to_owned().unwrap_or(payouts.entity_type),
metadata: req.metadata.clone().or(payouts.metadata.clone()),
status: Some(status),
profile_id: Some(payout_attempt.profile_id.clone()),
confirm: req.confirm.to_owned(),
payout_type: req
.payout_type
.to_owned()
.or(payouts.payout_type.to_owned()),
address_id: address_id.clone(),
customer_id: customer_id.clone(),
};
let db = &*state.store;
payout_data.payouts = db
.update_payout(
&payouts,
updated_payouts,
&payout_attempt,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payouts")?;
let updated_business_country =
payout_attempt
.business_country
.map_or(req.business_country.to_owned(), |c| {
req.business_country
.to_owned()
.and_then(|nc| if nc != c { Some(nc) } else { None })
});
let updated_business_label =
payout_attempt
.business_label
.map_or(req.business_label.to_owned(), |l| {
req.business_label
.to_owned()
.and_then(|nl| if nl != l { Some(nl) } else { None })
});
if updated_business_country.is_some()
|| updated_business_label.is_some()
|| customer_id.is_some()
|| address_id.is_some()
{
let payout_attempt = &payout_data.payout_attempt;
let updated_payout_attempt = storage::PayoutAttemptUpdate::BusinessUpdate {
business_country: updated_business_country,
business_label: updated_business_label,
address_id,
customer_id,
};
payout_data.payout_attempt = db
.update_payout_attempt(
payout_attempt,
updated_payout_attempt,
&payout_data.payouts,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Error updating payout_attempt")?;
}
Ok(())
}
pub(super) fn get_customer_details_from_request(
request: &payouts::PayoutCreateRequest,
) -> CustomerDetails {
let customer_id = request.get_customer_id().map(ToOwned::to_owned);
let customer_name = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.name.clone())
.or(request.name.clone());
let customer_email = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.email.clone())
.or(request.email.clone());
let customer_phone = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.phone.clone())
.or(request.phone.clone());
let customer_phone_code = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.phone_country_code.clone())
.or(request.phone_country_code.clone());
let tax_registration_id = request
.customer
.as_ref()
.and_then(|customer_details| customer_details.tax_registration_id.clone());
CustomerDetails {
customer_id,
name: customer_name,
email: customer_email,
phone: customer_phone,
phone_country_code: customer_phone_code,
tax_registration_id,
}
}
pub async fn get_translated_unified_code_and_message(
state: &SessionState,
unified_code: Option<&UnifiedCode>,
unified_message: Option<&UnifiedMessage>,
locale: &str,
) -> CustomResult<Option<UnifiedMessage>, errors::ApiErrorResponse> {
Ok(unified_code
.zip(unified_message)
.async_and_then(|(code, message)| async {
payment_helpers::get_unified_translation(
state,
code.0.clone(),
message.0.clone(),
locale.to_string(),
)
.await
.map(UnifiedMessage::try_from)
})
.await
.transpose()
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "unified_message",
})?
.or_else(|| unified_message.cloned()))
}
pub async fn get_additional_payout_data(
pm_data: &api::PayoutMethodData,
db: &dyn StorageInterface,
profile_id: &id_type::ProfileId,
) -> Option<payout_additional::AdditionalPayoutMethodData> {
match pm_data {
api::PayoutMethodData::Card(card_data) => {
let card_isin = Some(card_data.card_number.get_card_isin());
let enable_extended_bin =db
.find_config_by_key_unwrap_or(
format!("{}_enable_extended_card_bin", profile_id.get_string_repr()).as_str(),
Some("false".to_string()))
.await.map_err(|err| services::logger::error!(message="Failed to fetch the config", extended_card_bin_error=?err)).ok();
let card_extended_bin = match enable_extended_bin {
Some(config) if config.config == "true" => {
Some(card_data.card_number.get_extended_card_bin())
}
_ => None,
};
let last4 = Some(card_data.card_number.get_last4());
let card_info = card_isin
.clone()
.async_and_then(|card_isin| async move {
db.get_card_info(&card_isin)
.await
.map_err(|error| services::logger::warn!(card_info_error=?error))
.ok()
})
.await
.flatten()
.map(|card_info| {
payout_additional::AdditionalPayoutMethodData::Card(Box::new(
payout_additional::CardAdditionalData {
card_issuer: card_info.card_issuer,
card_network: card_info.card_network.clone(),
bank_code: card_info.bank_code,
card_type: card_info.card_type,
card_issuing_country: card_info.card_issuing_country,
last4: last4.clone(),
card_isin: card_isin.clone(),
card_extended_bin: card_extended_bin.clone(),
card_exp_month: Some(card_data.expiry_month.clone()),
card_exp_year: Some(card_data.expiry_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
},
))
});
Some(card_info.unwrap_or_else(|| {
payout_additional::AdditionalPayoutMethodData::Card(Box::new(
payout_additional::CardAdditionalData {
card_issuer: None,
card_network: None,
bank_code: None,
card_type: None,
card_issuing_country: None,
last4,
card_isin,
card_extended_bin,
card_exp_month: Some(card_data.expiry_month.clone()),
card_exp_year: Some(card_data.expiry_year.clone()),
card_holder_name: card_data.card_holder_name.clone(),
},
))
}))
}
api::PayoutMethodData::Bank(bank_data) => {
Some(payout_additional::AdditionalPayoutMethodData::Bank(
Box::new(bank_data.to_owned().into()),
))
}
api::PayoutMethodData::Wallet(wallet_data) => {
Some(payout_additional::AdditionalPayoutMethodData::Wallet(
Box::new(wallet_data.to_owned().into()),
))
}
}
}
pub async fn resolve_billing_address_for_payout(
state: &SessionState,
req_billing: Option<&api_models::payments::Address>,
existing_address_id: Option<&String>,
payment_method: Option<&hyperswitch_domain_models::payment_methods::PaymentMethod>,
merchant_context: &domain::MerchantContext,
customer_id: Option<&id_type::CustomerId>,
payout_id: &id_type::PayoutId,
) -> RouterResult<(
Option<hyperswitch_domain_models::address::Address>,
Option<String>,
)> {
let payout_id_as_payment_id = id_type::PaymentId::try_from(std::borrow::Cow::Owned(
payout_id.get_string_repr().to_string(),
))
.change_context(errors::ApiErrorResponse::InvalidRequestData {
message: "payout_id contains invalid data for PaymentId conversion".to_string(),
})
.attach_printable("Error converting payout_id to PaymentId type")?;
match (req_billing, existing_address_id, payment_method) {
// Address in request
(Some(_), _, _) => {
let billing_address = payment_helpers::create_or_find_address_for_payment_by_request(
state,
req_billing,
None,
merchant_context.get_merchant_account().get_id(),
customer_id,
merchant_context.get_merchant_key_store(),
&payout_id_as_payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let address_id = billing_address.as_ref().map(|a| a.address_id.clone());
let hyperswitch_address = billing_address
.map(|addr| hyperswitch_domain_models::address::Address::from(&addr));
Ok((hyperswitch_address, address_id))
}
// Existing address using address_id
(None, Some(address_id), _) => {
let billing_address = payment_helpers::create_or_find_address_for_payment_by_request(
state,
None,
Some(address_id),
merchant_context.get_merchant_account().get_id(),
customer_id,
merchant_context.get_merchant_key_store(),
&payout_id_as_payment_id,
merchant_context.get_merchant_account().storage_scheme,
)
.await?;
let hyperswitch_address = billing_address
.map(|addr| hyperswitch_domain_models::address::Address::from(&addr));
Ok((hyperswitch_address, Some(address_id.clone())))
}
// Existing address in stored payment method
(None, None, Some(pm)) => {
pm.payment_method_billing_address.as_ref().map_or_else(
|| {
logger::info!("No billing address found in payment method");
Ok((None, None))
},
|encrypted_billing_address| {
logger::info!("Found encrypted billing address data in payment method");
#[cfg(feature = "v1")]
{
encrypted_billing_address
.clone()
.into_inner()
.expose()
.parse_value::<hyperswitch_domain_models::address::Address>(
"payment_method_billing_address",
)
.map(|domain_address| {
logger::info!("Successfully parsed as hyperswitch_domain_models::address::Address");
(Some(domain_address), None)
})
.map_err(|e| {
logger::error!("Failed to parse billing address into (hyperswitch_domain_models::address::Address): {:?}", e);
errors::ApiErrorResponse::InternalServerError
})
.attach_printable("Failed to parse stored billing address")
}
#[cfg(feature = "v2")]
{
// TODO: Implement v2 logic when needed
logger::warn!("v2 billing address resolution not yet implemented");
Ok((None, None))
}
},
)
}
(None, None, None) => Ok((None, None)),
}
}
|
crates/router/src/core/payouts/helpers.rs#chunk1
|
router
|
chunk
| 4,321
| null | null | null | null | null | null | null | null | null | null | null | null | null |
File: crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
Public functions: 1
Public structs: 34
use std::str::FromStr;
use common_enums::enums::CaptureMethod;
use common_utils::types::MinorUnit;
use error_stack::{report, ResultExt};
use hyperswitch_domain_models::{
payment_method_data::PaymentMethodData,
router_data::{AccessToken, ConnectorAuthType, RouterData},
router_flow_types::refunds::{Execute, RSync},
router_request_types::{PaymentsCancelData, ResponseId},
router_response_types::{PaymentsResponseData, RefundsResponseData},
types::{
PaymentsAuthorizeRouterData, PaymentsCancelRouterData, PaymentsCaptureRouterData,
RefreshTokenRouterData, RefundsRouterData,
},
};
use hyperswitch_interfaces::errors;
use masking::{PeekInterface, Secret};
use serde::{Deserialize, Serialize};
use crate::{
types::{RefundsResponseRouterData, ResponseRouterData},
utils::{
get_unimplemented_payment_method_error_message, CardData, RouterData as OtherRouterData,
},
};
pub struct JpmorganRouterData<T> {
pub amount: MinorUnit,
pub router_data: T,
}
impl<T> From<(MinorUnit, T)> for JpmorganRouterData<T> {
fn from((amount, item): (MinorUnit, T)) -> Self {
Self {
amount,
router_data: item,
}
}
}
#[derive(Debug, Clone, Serialize)]
pub struct JpmorganAuthUpdateRequest {
pub grant_type: String,
pub scope: String,
}
#[derive(Debug, Serialize, Deserialize)]
pub struct JpmorganAuthUpdateResponse {
pub access_token: Secret<String>,
pub scope: String,
pub token_type: String,
pub expires_in: i64,
}
impl TryFrom<&RefreshTokenRouterData> for JpmorganAuthUpdateRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(_item: &RefreshTokenRouterData) -> Result<Self, Self::Error> {
Ok(Self {
grant_type: String::from("client_credentials"),
scope: String::from("jpm:payments:sandbox"),
})
}
}
impl<F, T> TryFrom<ResponseRouterData<F, JpmorganAuthUpdateResponse, T, AccessToken>>
for RouterData<F, T, AccessToken>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganAuthUpdateResponse, T, AccessToken>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(AccessToken {
token: item.response.access_token,
expires: item.response.expires_in,
}),
..item.data
})
}
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentsRequest {
capture_method: CapMethod,
amount: MinorUnit,
currency: common_enums::Currency,
merchant: JpmorganMerchant,
payment_method_type: JpmorganPaymentMethodType,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCard {
account_number: Secret<String>,
expiry: Expiry,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentMethodType {
card: JpmorganCard,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Expiry {
month: Secret<i32>,
year: Secret<i32>,
}
#[derive(Serialize, Debug, Default, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganMerchantSoftware {
company_name: Secret<String>,
product_name: Secret<String>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganMerchant {
merchant_software: JpmorganMerchantSoftware,
}
fn map_capture_method(
capture_method: CaptureMethod,
) -> Result<CapMethod, error_stack::Report<errors::ConnectorError>> {
match capture_method {
CaptureMethod::Automatic => Ok(CapMethod::Now),
CaptureMethod::Manual => Ok(CapMethod::Manual),
CaptureMethod::Scheduled
| CaptureMethod::ManualMultiple
| CaptureMethod::SequentialAutomatic => {
Err(errors::ConnectorError::NotImplemented("Capture Method".to_string()).into())
}
}
}
impl TryFrom<&JpmorganRouterData<&PaymentsAuthorizeRouterData>> for JpmorganPaymentsRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &JpmorganRouterData<&PaymentsAuthorizeRouterData>,
) -> Result<Self, Self::Error> {
match item.router_data.request.payment_method_data.clone() {
PaymentMethodData::Card(req_card) => {
if item.router_data.is_three_ds() {
return Err(errors::ConnectorError::NotSupported {
message: "3DS payments".to_string(),
connector: "Jpmorgan",
}
.into());
}
let capture_method =
map_capture_method(item.router_data.request.capture_method.unwrap_or_default());
let merchant_software = JpmorganMerchantSoftware {
company_name: String::from("JPMC").into(),
product_name: String::from("Hyperswitch").into(),
};
let merchant = JpmorganMerchant { merchant_software };
let expiry: Expiry = Expiry {
month: Secret::new(
req_card
.card_exp_month
.peek()
.clone()
.parse::<i32>()
.change_context(errors::ConnectorError::RequestEncodingFailed)?,
),
year: req_card.get_expiry_year_as_4_digit_i32()?,
};
let account_number = Secret::new(req_card.card_number.to_string());
let card = JpmorganCard {
account_number,
expiry,
};
let payment_method_type = JpmorganPaymentMethodType { card };
Ok(Self {
capture_method: capture_method?,
currency: item.router_data.request.currency,
amount: item.amount,
merchant,
payment_method_type,
})
}
PaymentMethodData::CardDetailsForNetworkTransactionId(_)
| PaymentMethodData::CardRedirect(_)
| PaymentMethodData::Wallet(_)
| PaymentMethodData::PayLater(_)
| PaymentMethodData::BankRedirect(_)
| PaymentMethodData::BankDebit(_)
| PaymentMethodData::BankTransfer(_)
| PaymentMethodData::Crypto(_)
| PaymentMethodData::MandatePayment
| PaymentMethodData::Reward
| PaymentMethodData::RealTimePayment(_)
| PaymentMethodData::MobilePayment(_)
| PaymentMethodData::Upi(_)
| PaymentMethodData::Voucher(_)
| PaymentMethodData::GiftCard(_)
| PaymentMethodData::OpenBanking(_)
| PaymentMethodData::CardToken(_)
| PaymentMethodData::NetworkToken(_) => Err(errors::ConnectorError::NotImplemented(
get_unimplemented_payment_method_error_message("jpmorgan"),
)
.into()),
}
}
}
//JP Morgan uses access token only due to which we aren't reading the fields in this struct
#[derive(Debug)]
pub struct JpmorganAuthType {
pub(super) _api_key: Secret<String>,
pub(super) _key1: Secret<String>,
}
impl TryFrom<&ConnectorAuthType> for JpmorganAuthType {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(auth_type: &ConnectorAuthType) -> Result<Self, Self::Error> {
match auth_type {
ConnectorAuthType::BodyKey { api_key, key1 } => Ok(Self {
_api_key: api_key.to_owned(),
_key1: key1.to_owned(),
}),
_ => Err(errors::ConnectorError::FailedToObtainAuthType.into()),
}
}
}
#[derive(Clone, Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "UPPERCASE")]
pub enum JpmorganTransactionStatus {
Success,
Denied,
Error,
}
#[derive(Default, Debug, Serialize, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum JpmorganTransactionState {
Closed,
Authorized,
Voided,
#[default]
Pending,
Declined,
Error,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentsResponse {
transaction_id: String,
request_id: String,
transaction_state: JpmorganTransactionState,
response_status: String,
response_code: String,
response_message: String,
payment_method_type: PaymentMethodType,
capture_method: Option<CapMethod>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Merchant {
merchant_id: Option<String>,
merchant_software: JpmorganMerchantSoftware,
merchant_category_code: Option<String>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethodType {
card: Option<Card>,
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct Card {
expiry: Option<ExpiryResponse>,
card_type: Option<Secret<String>>,
card_type_name: Option<Secret<String>>,
masked_account_number: Option<Secret<String>>,
card_type_indicators: Option<CardTypeIndicators>,
network_response: Option<NetworkResponse>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct NetworkResponse {
address_verification_result: Option<Secret<String>>,
address_verification_result_code: Option<Secret<String>>,
card_verification_result_code: Option<Secret<String>>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ExpiryResponse {
month: Option<Secret<i32>>,
year: Option<Secret<i32>>,
}
#[derive(Clone, Debug, Eq, PartialEq, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct CardTypeIndicators {
issuance_country_code: Option<Secret<String>>,
is_durbin_regulated: Option<bool>,
card_product_types: Secret<Vec<String>>,
}
pub fn attempt_status_from_transaction_state(
transaction_state: JpmorganTransactionState,
) -> common_enums::AttemptStatus {
match transaction_state {
JpmorganTransactionState::Authorized => common_enums::AttemptStatus::Authorized,
JpmorganTransactionState::Closed => common_enums::AttemptStatus::Charged,
JpmorganTransactionState::Declined | JpmorganTransactionState::Error => {
common_enums::AttemptStatus::Failure
}
JpmorganTransactionState::Pending => common_enums::AttemptStatus::Pending,
JpmorganTransactionState::Voided => common_enums::AttemptStatus::Voided,
}
}
impl<F, T> TryFrom<ResponseRouterData<F, JpmorganPaymentsResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganPaymentsResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let transaction_state = match item.response.transaction_state {
JpmorganTransactionState::Closed => match item.response.capture_method {
Some(CapMethod::Now) => JpmorganTransactionState::Closed,
_ => JpmorganTransactionState::Authorized,
},
JpmorganTransactionState::Authorized => JpmorganTransactionState::Authorized,
JpmorganTransactionState::Voided => JpmorganTransactionState::Voided,
JpmorganTransactionState::Pending => JpmorganTransactionState::Pending,
JpmorganTransactionState::Declined => JpmorganTransactionState::Declined,
JpmorganTransactionState::Error => JpmorganTransactionState::Error,
};
let status = attempt_status_from_transaction_state(transaction_state);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Deserialize, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCaptureRequest {
capture_method: Option<CapMethod>,
amount: MinorUnit,
currency: Option<common_enums::Currency>,
}
#[derive(Debug, Default, Copy, Serialize, Deserialize, Clone)]
#[serde(rename_all = "UPPERCASE")]
pub enum CapMethod {
#[default]
Now,
Delayed,
Manual,
}
impl TryFrom<&JpmorganRouterData<&PaymentsCaptureRouterData>> for JpmorganCaptureRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: &JpmorganRouterData<&PaymentsCaptureRouterData>,
) -> Result<Self, Self::Error> {
let capture_method = Some(map_capture_method(
item.router_data.request.capture_method.unwrap_or_default(),
)?);
Ok(Self {
capture_method,
amount: item.amount,
currency: Some(item.router_data.request.currency),
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCaptureResponse {
pub transaction_id: String,
pub request_id: String,
pub transaction_state: JpmorganTransactionState,
pub response_status: JpmorganTransactionStatus,
pub response_code: String,
pub response_message: String,
pub payment_method_type: PaymentMethodTypeCapRes,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PaymentMethodTypeCapRes {
pub card: Option<CardCapRes>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardCapRes {
pub card_type: Option<Secret<String>>,
pub card_type_name: Option<Secret<String>>,
unmasked_account_number: Option<Secret<String>>,
}
impl<F, T> TryFrom<ResponseRouterData<F, JpmorganCaptureResponse, T, PaymentsResponseData>>
for RouterData<F, T, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganCaptureResponse, T, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = attempt_status_from_transaction_state(item.response.transaction_state);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPSyncResponse {
transaction_id: String,
transaction_state: JpmorganTransactionState,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "UPPERCASE")]
pub enum JpmorganResponseStatus {
Success,
Denied,
Error,
}
impl<F, PaymentsSyncData>
TryFrom<ResponseRouterData<F, JpmorganPSyncResponse, PaymentsSyncData, PaymentsResponseData>>
for RouterData<F, PaymentsSyncData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<F, JpmorganPSyncResponse, PaymentsSyncData, PaymentsResponseData>,
) -> Result<Self, Self::Error> {
let status = attempt_status_from_transaction_state(item.response.transaction_state);
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Default, Debug, Clone, Serialize, Deserialize, PartialEq)]
pub struct TransactionData {
payment_type: Option<Secret<String>>,
status_code: Secret<i32>,
txn_secret: Option<Secret<String>>,
tid: Option<Secret<i64>>,
test_mode: Option<Secret<i8>>,
status: Option<JpmorganTransactionStatus>,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganRefundRequest {
pub merchant: MerchantRefundReq,
pub amount: MinorUnit,
pub currency: common_enums::Currency,
}
#[derive(Default, Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct MerchantRefundReq {
pub merchant_software: JpmorganMerchantSoftware,
}
impl<F> TryFrom<&JpmorganRouterData<&RefundsRouterData<F>>> for JpmorganRefundRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: &JpmorganRouterData<&RefundsRouterData<F>>) -> Result<Self, Self::Error> {
let merchant_software = JpmorganMerchantSoftware {
company_name: String::from("JPMC").into(),
product_name: String::from("Hyperswitch").into(),
};
let merchant = MerchantRefundReq { merchant_software };
let amount = item.amount;
let currency = item.router_data.request.currency;
Ok(Self {
merchant,
amount,
currency,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganRefundResponse {
pub transaction_id: Option<String>,
pub request_id: String,
pub transaction_state: JpmorganTransactionState,
pub amount: MinorUnit,
pub currency: common_enums::Currency,
pub response_status: JpmorganResponseStatus,
pub response_code: String,
pub response_message: String,
pub transaction_reference_id: Option<String>,
pub remaining_refundable_amount: Option<i64>,
}
#[derive(Debug, Serialize, Default, Deserialize, Clone)]
pub enum RefundStatus {
Succeeded,
Failed,
#[default]
Processing,
}
impl From<RefundStatus> for common_enums::RefundStatus {
fn from(item: RefundStatus) -> Self {
match item {
RefundStatus::Succeeded => Self::Success,
RefundStatus::Failed => Self::Failure,
RefundStatus::Processing => Self::Pending,
}
}
}
impl From<(JpmorganResponseStatus, JpmorganTransactionState)> for RefundStatus {
fn from(
(response_status, transaction_state): (JpmorganResponseStatus, JpmorganTransactionState),
) -> Self {
match response_status {
JpmorganResponseStatus::Success => match transaction_state {
JpmorganTransactionState::Voided | JpmorganTransactionState::Closed => {
Self::Succeeded
}
JpmorganTransactionState::Declined | JpmorganTransactionState::Error => {
Self::Failed
}
JpmorganTransactionState::Pending | JpmorganTransactionState::Authorized => {
Self::Processing
}
},
JpmorganResponseStatus::Denied | JpmorganResponseStatus::Error => Self::Failed,
}
}
}
impl TryFrom<RefundsResponseRouterData<Execute, JpmorganRefundResponse>>
for RefundsRouterData<Execute>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<Execute, JpmorganRefundResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item
.response
.transaction_id
.clone()
.ok_or(errors::ConnectorError::ResponseHandlingFailed)?,
refund_status: RefundStatus::from((
item.response.response_status,
item.response.transaction_state,
))
.into(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganRefundSyncResponse {
transaction_id: String,
request_id: String,
transaction_state: JpmorganTransactionState,
amount: MinorUnit,
currency: common_enums::Currency,
response_status: JpmorganResponseStatus,
response_code: String,
}
impl TryFrom<RefundsResponseRouterData<RSync, JpmorganRefundSyncResponse>>
for RefundsRouterData<RSync>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: RefundsResponseRouterData<RSync, JpmorganRefundSyncResponse>,
) -> Result<Self, Self::Error> {
Ok(Self {
response: Ok(RefundsResponseData {
connector_refund_id: item.response.transaction_id.clone(),
refund_status: RefundStatus::from((
item.response.response_status,
item.response.transaction_state,
))
.into(),
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "SCREAMING_SNAKE_CASE")]
pub enum ReversalReason {
NoResponse,
LateResponse,
UnableToDeliver,
CardDeclined,
MacNotVerified,
MacSyncError,
ZekSyncError,
SystemMalfunction,
SuspectedFraud,
}
impl FromStr for ReversalReason {
type Err = error_stack::Report<errors::ConnectorError>;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_uppercase().as_str() {
"NO_RESPONSE" => Ok(Self::NoResponse),
"LATE_RESPONSE" => Ok(Self::LateResponse),
"UNABLE_TO_DELIVER" => Ok(Self::UnableToDeliver),
"CARD_DECLINED" => Ok(Self::CardDeclined),
"MAC_NOT_VERIFIED" => Ok(Self::MacNotVerified),
"MAC_SYNC_ERROR" => Ok(Self::MacSyncError),
"ZEK_SYNC_ERROR" => Ok(Self::ZekSyncError),
"SYSTEM_MALFUNCTION" => Ok(Self::SystemMalfunction),
"SUSPECTED_FRAUD" => Ok(Self::SuspectedFraud),
_ => Err(report!(errors::ConnectorError::InvalidDataFormat {
field_name: "cancellation_reason",
})),
}
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCancelRequest {
pub amount: Option<i64>,
pub is_void: Option<bool>,
pub reversal_reason: Option<ReversalReason>,
}
impl TryFrom<JpmorganRouterData<&PaymentsCancelRouterData>> for JpmorganCancelRequest {
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(item: JpmorganRouterData<&PaymentsCancelRouterData>) -> Result<Self, Self::Error> {
Ok(Self {
amount: item.router_data.request.amount,
is_void: Some(true),
reversal_reason: item
.router_data
.request
.cancellation_reason
.as_ref()
.map(|reason| ReversalReason::from_str(reason))
.transpose()?,
})
}
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganCancelResponse {
transaction_id: String,
request_id: String,
response_status: JpmorganResponseStatus,
response_code: String,
response_message: String,
payment_method_type: JpmorganPaymentMethodTypeCancelResponse,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganPaymentMethodTypeCancelResponse {
pub card: CardCancelResponse,
}
#[derive(Debug, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct CardCancelResponse {
pub card_type: Secret<String>,
pub card_type_name: Secret<String>,
}
impl<F>
TryFrom<ResponseRouterData<F, JpmorganCancelResponse, PaymentsCancelData, PaymentsResponseData>>
for RouterData<F, PaymentsCancelData, PaymentsResponseData>
{
type Error = error_stack::Report<errors::ConnectorError>;
fn try_from(
item: ResponseRouterData<
F,
JpmorganCancelResponse,
PaymentsCancelData,
PaymentsResponseData,
>,
) -> Result<Self, Self::Error> {
let status = match item.response.response_status {
JpmorganResponseStatus::Success => common_enums::AttemptStatus::Voided,
JpmorganResponseStatus::Denied | JpmorganResponseStatus::Error => {
common_enums::AttemptStatus::Failure
}
};
Ok(Self {
status,
response: Ok(PaymentsResponseData::TransactionResponse {
resource_id: ResponseId::ConnectorTransactionId(
item.response.transaction_id.clone(),
),
redirection_data: Box::new(None),
mandate_reference: Box::new(None),
connector_metadata: None,
network_txn_id: None,
connector_response_reference_id: Some(item.response.transaction_id.clone()),
incremental_authorization_allowed: None,
charges: None,
}),
..item.data
})
}
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganValidationErrors {
pub code: Option<String>,
pub message: Option<String>,
pub entity: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganErrorInformation {
pub code: Option<String>,
pub message: Option<String>,
}
#[derive(Debug, Serialize, Deserialize, PartialEq)]
#[serde(rename_all = "camelCase")]
pub struct JpmorganErrorResponse {
pub response_status: JpmorganTransactionStatus,
pub response_code: String,
pub response_message: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/jpmorgan/transformers.rs
|
hyperswitch_connectors
|
full_file
| 5,809
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct EliminationAnalyserConfig {
pub bucket_size: Option<u64>,
pub bucket_leak_interval_in_secs: Option<u64>,
}
|
crates/api_models/src/routing.rs
|
api_models
|
struct_definition
| 33
|
rust
|
EliminationAnalyserConfig
| null | null | null | null | null | null | null | null | null | null | null |
pub struct KafkaRefund<'a> {
pub refund_id: &'a id_type::GlobalRefundId,
pub merchant_reference_id: &'a id_type::RefundReferenceId,
pub payment_id: &'a id_type::GlobalPaymentId,
pub merchant_id: &'a id_type::MerchantId,
pub connector_transaction_id: &'a types::ConnectorTransactionId,
pub connector: &'a String,
pub connector_refund_id: Option<&'a types::ConnectorTransactionId>,
pub external_reference_id: Option<&'a String>,
pub refund_type: &'a storage_enums::RefundType,
pub total_amount: &'a MinorUnit,
pub currency: &'a storage_enums::Currency,
pub refund_amount: &'a MinorUnit,
pub refund_status: &'a storage_enums::RefundStatus,
pub sent_to_gateway: &'a bool,
pub refund_error_message: Option<&'a String>,
pub refund_arn: Option<&'a String>,
#[serde(default, with = "time::serde::timestamp")]
pub created_at: OffsetDateTime,
#[serde(default, with = "time::serde::timestamp")]
pub modified_at: OffsetDateTime,
pub description: Option<&'a String>,
pub attempt_id: &'a id_type::GlobalAttemptId,
pub refund_reason: Option<&'a String>,
pub refund_error_code: Option<&'a String>,
pub profile_id: Option<&'a id_type::ProfileId>,
pub organization_id: &'a id_type::OrganizationId,
pub metadata: Option<&'a pii::SecretSerdeValue>,
pub updated_by: &'a String,
pub merchant_connector_id: Option<&'a id_type::MerchantConnectorAccountId>,
pub charges: Option<&'a ChargeRefunds>,
pub connector_refund_data: Option<&'a String>,
pub connector_transaction_data: Option<&'a String>,
pub split_refunds: Option<&'a common_types::refunds::SplitRefund>,
pub unified_code: Option<&'a String>,
pub unified_message: Option<&'a String>,
pub processor_refund_data: Option<&'a String>,
pub processor_transaction_data: Option<&'a String>,
}
|
crates/router/src/services/kafka/refund.rs
|
router
|
struct_definition
| 479
|
rust
|
KafkaRefund
| null | null | null | null | null | null | null | null | null | null | null |
pub struct CustomerBankAccountResponse {
pub id: Secret<String>,
}
|
crates/hyperswitch_connectors/src/connectors/gocardless/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 15
|
rust
|
CustomerBankAccountResponse
| null | null | null | null | null | null | null | null | null | null | null |
pub fn server(state: AppState) -> Scope {
web::scope("/analytics").app_data(web::Data::new(state))
}
|
crates/router/src/analytics.rs
|
router
|
function_signature
| 28
|
rust
| null | null | null | null |
server
| null | null | null | null | null | null | null |
File: crates/router_derive/src/lib.rs
Public functions: 16
Public structs: 3
//! Utility macros for the `router` crate.
#![warn(missing_docs)]
use syn::parse_macro_input;
use crate::macros::diesel::DieselEnumMeta;
mod macros;
/// Uses the [`Debug`][Debug] implementation of a type to derive its [`Display`][Display]
/// implementation.
///
/// Causes a compilation error if the type doesn't implement the [`Debug`][Debug] trait.
///
/// [Debug]: ::core::fmt::Debug
/// [Display]: ::core::fmt::Display
///
/// # Example
///
/// ```
/// use router_derive::DebugAsDisplay;
///
/// #[derive(Debug, DebugAsDisplay)]
/// struct Point {
/// x: f32,
/// y: f32,
/// }
///
/// #[derive(Debug, DebugAsDisplay)]
/// enum Color {
/// Red,
/// Green,
/// Blue,
/// }
/// ```
#[proc_macro_derive(DebugAsDisplay)]
pub fn debug_as_display_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast = syn::parse_macro_input!(input as syn::DeriveInput);
let tokens =
macros::debug_as_display_inner(&ast).unwrap_or_else(|error| error.to_compile_error());
tokens.into()
}
/// Derives the boilerplate code required for using an enum with `diesel` and a PostgreSQL database.
/// The enum is required to implement (or derive) the [`ToString`][ToString] and the
/// [`FromStr`][FromStr] traits for this derive macro to be used.
///
/// Works in tandem with the [`diesel_enum`][diesel_enum] attribute macro to achieve the desired
/// results.
///
/// [diesel_enum]: macro@crate::diesel_enum
/// [FromStr]: ::core::str::FromStr
/// [ToString]: ::std::string::ToString
///
/// # Example
///
/// ```
/// use router_derive::diesel_enum;
///
/// // Deriving `FromStr` and `ToString` using the `strum` crate, you can also implement it
/// // yourself if required.
/// #[derive(strum::Display, strum::EnumString)]
/// #[derive(Debug)]
/// #[diesel_enum(storage_type = "db_enum")]
/// enum Color {
/// Red,
/// Green,
/// Blue,
/// }
/// ```
#[proc_macro_derive(DieselEnum, attributes(storage_type))]
pub fn diesel_enum_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast = syn::parse_macro_input!(input as syn::DeriveInput);
let tokens =
macros::diesel_enum_derive_inner(&ast).unwrap_or_else(|error| error.to_compile_error());
tokens.into()
}
/// Similar to [`DieselEnum`] but uses text when storing in the database, this is to avoid
/// making changes to the database when the enum variants are added or modified
///
/// # Example
/// [DieselEnum]: macro@crate::diesel_enum
///
/// ```
/// use router_derive::{diesel_enum};
///
/// // Deriving `FromStr` and `ToString` using the `strum` crate, you can also implement it
/// // yourself if required.
/// #[derive(strum::Display, strum::EnumString)]
/// #[derive(Debug)]
/// #[diesel_enum(storage_type = "text")]
/// enum Color {
/// Red,
/// Green,
/// Blue,
/// }
/// ```
#[proc_macro_derive(DieselEnumText)]
pub fn diesel_enum_derive_string(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let ast = syn::parse_macro_input!(input as syn::DeriveInput);
let tokens = macros::diesel_enum_text_derive_inner(&ast)
.unwrap_or_else(|error| error.to_compile_error());
tokens.into()
}
/// Derives the boilerplate code required for using an enum with `diesel` and a PostgreSQL database.
///
/// Storage Type can either be "text" or "db_enum"
/// Choosing text will store the enum as text in the database, whereas db_enum will map it to the
/// corresponding database enum
///
/// Works in tandem with the [`DieselEnum`][DieselEnum] derive macro to achieve the desired results.
/// The enum is required to implement (or derive) the [`ToString`][ToString] and the
/// [`FromStr`][FromStr] traits for the [`DieselEnum`][DieselEnum] derive macro to be used.
///
/// [DieselEnum]: crate::DieselEnum
/// [FromStr]: ::core::str::FromStr
/// [ToString]: ::std::string::ToString
///
/// # Example
///
/// ```
/// use router_derive::{diesel_enum};
///
/// // Deriving `FromStr` and `ToString` using the `strum` crate, you can also implement it
/// // yourself if required. (Required by the DieselEnum derive macro.)
/// #[derive(strum::Display, strum::EnumString)]
/// #[derive(Debug)]
/// #[diesel_enum(storage_type = "text")]
/// enum Color {
/// Red,
/// Green,
/// Blue,
/// }
/// ```
#[proc_macro_attribute]
pub fn diesel_enum(
args: proc_macro::TokenStream,
item: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
let args_parsed = parse_macro_input!(args as DieselEnumMeta);
let item = syn::parse_macro_input!(item as syn::ItemEnum);
macros::diesel::diesel_enum_attribute_macro(args_parsed, &item)
.unwrap_or_else(|error| error.to_compile_error())
.into()
}
/// A derive macro which generates the setter functions for any struct with fields
/// # Example
/// ```
/// use router_derive::Setter;
///
/// #[derive(Setter)]
/// struct Test {
/// test:u32
/// }
/// ```
/// The above Example will expand to
/// ```rust, ignore
/// impl Test {
/// fn set_test(&mut self, val: u32) -> &mut Self {
/// self.test = val;
/// self
/// }
/// }
/// ```
///
/// # Panics
///
/// Panics if a struct without named fields is provided as input to the macro
// FIXME: Remove allowed warnings, raise compile errors in a better manner instead of panicking
#[allow(clippy::panic, clippy::unwrap_used)]
#[proc_macro_derive(Setter, attributes(auth_based))]
pub fn setter(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
let ident = &input.ident;
// All the fields in the parent struct
let fields = if let syn::Data::Struct(syn::DataStruct {
fields: syn::Fields::Named(syn::FieldsNamed { ref named, .. }),
..
}) = input.data
{
named
} else {
// FIXME: Use `compile_error!()` instead
panic!("You can't use this proc-macro on structs without fields");
};
// Methods in the build struct like if the struct is
// Struct i {n: u32}
// this will be
// pub fn set_n(&mut self,n: u32)
let build_methods = fields.iter().map(|f| {
let name = f.ident.as_ref().unwrap();
let method_name = format!("set_{name}");
let method_ident = syn::Ident::new(&method_name, name.span());
let ty = &f.ty;
if check_if_auth_based_attr_is_present(f, "auth_based") {
quote::quote! {
pub fn #method_ident(&mut self, val:#ty, is_merchant_flow: bool)->&mut Self{
if is_merchant_flow {
self.#name = val;
}
self
}
}
} else {
quote::quote! {
pub fn #method_ident(&mut self, val:#ty)->&mut Self{
self.#name = val;
self
}
}
}
});
let output = quote::quote! {
#[automatically_derived]
impl #ident {
#(#build_methods)*
}
};
output.into()
}
#[inline]
fn check_if_auth_based_attr_is_present(f: &syn::Field, ident: &str) -> bool {
for i in f.attrs.iter() {
if i.path().is_ident(ident) {
return true;
}
}
false
}
/// 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()
}
/// Derives the `core::payments::Operation` trait on a type with a default base
/// implementation.
///
/// ## Usage
/// On deriving, the conversion functions to be implemented need to be specified in an helper
/// attribute `#[operation(..)]`. To derive all conversion functions, use `#[operation(all)]`. To
/// derive specific conversion functions, pass the required identifiers to the attribute.
/// `#[operation(validate_request, get_tracker)]`. Available conversions are listed below :-
///
/// - validate_request
/// - get_tracker
/// - domain
/// - update_tracker
///
/// ## Example
/// ```rust, ignore
/// use router_derive::Operation;
///
/// #[derive(Operation)]
/// #[operation(all)]
/// struct Point {
/// x: u64,
/// y: u64
/// }
///
/// // The above will expand to this
/// const _: () = {
/// use crate::core::errors::RouterResult;
/// use crate::core::payments::{GetTracker, PaymentData, UpdateTracker, ValidateRequest};
/// impl crate::core::payments::Operation for Point {
/// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> {
/// Ok(self)
/// }
/// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> {
/// Ok(self)
/// }
/// fn to_domain(&self) -> RouterResult<&dyn Domain> {
/// Ok(self)
/// }
/// fn to_update_tracker(&self) -> RouterResult<&dyn UpdateTracker<PaymentData>> {
/// Ok(self)
/// }
/// }
/// impl crate::core::payments::Operation for &Point {
/// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> {
/// Ok(*self)
/// }
/// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> {
/// Ok(*self)
/// }
/// fn to_domain(&self) -> RouterResult<&dyn Domain> {
/// Ok(*self)
/// }
/// fn to_update_tracker(&self) -> RouterResult<&dyn UpdateTracker<PaymentData>> {
/// Ok(*self)
/// }
/// }
/// };
///
/// #[derive(Operation)]
/// #[operation(validate_request, get_tracker)]
/// struct Point3 {
/// x: u64,
/// y: u64,
/// z: u64
/// }
///
/// // The above will expand to this
/// const _: () = {
/// use crate::core::errors::RouterResult;
/// use crate::core::payments::{GetTracker, PaymentData, UpdateTracker, ValidateRequest};
/// impl crate::core::payments::Operation for Point3 {
/// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> {
/// Ok(self)
/// }
/// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> {
/// Ok(self)
/// }
/// }
/// impl crate::core::payments::Operation for &Point3 {
/// fn to_validate_request(&self) -> RouterResult<&dyn ValidateRequest> {
/// Ok(*self)
/// }
/// fn to_get_tracker(&self) -> RouterResult<&dyn GetTracker<PaymentData>> {
/// Ok(*self)
/// }
/// }
/// };
///
/// ```
///
/// The `const _: () = {}` allows us to import stuff with `use` without affecting the module
/// imports, since use statements are not allowed inside of impl blocks. This technique is
/// used by `diesel`.
#[proc_macro_derive(PaymentOperation, attributes(operation))]
pub fn operation_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
macros::operation::operation_derive_inner(input)
.unwrap_or_else(|err| err.to_compile_error().into())
}
/// Generates different schemas with the ability to mark few fields as mandatory for certain schema
/// Usage
/// ```
/// use router_derive::PolymorphicSchema;
///
/// #[derive(PolymorphicSchema)]
/// #[generate_schemas(PaymentsCreateRequest, PaymentsConfirmRequest)]
/// struct PaymentsRequest {
/// #[mandatory_in(PaymentsCreateRequest = u64)]
/// amount: Option<u64>,
/// #[mandatory_in(PaymentsCreateRequest = String)]
/// currency: Option<String>,
/// payment_method: String,
/// }
/// ```
///
/// This will create two structs `PaymentsCreateRequest` and `PaymentsConfirmRequest` as follows
/// It will retain all the other attributes that are used in the original struct, and only consume
/// the #[mandatory_in] attribute to generate schemas
///
/// ```
/// #[derive(utoipa::ToSchema)]
/// struct PaymentsCreateRequest {
/// #[schema(required = true)]
/// amount: Option<u64>,
///
/// #[schema(required = true)]
/// currency: Option<String>,
///
/// payment_method: String,
/// }
///
/// #[derive(utoipa::ToSchema)]
/// struct PaymentsConfirmRequest {
/// amount: Option<u64>,
/// currency: Option<String>,
/// payment_method: String,
/// }
/// ```
#[proc_macro_derive(
PolymorphicSchema,
attributes(mandatory_in, generate_schemas, remove_in)
)]
pub fn polymorphic_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
macros::polymorphic_macro_derive_inner(input)
.unwrap_or_else(|error| error.into_compile_error())
.into()
}
/// Implements the `Validate` trait to check if the config variable is present
/// Usage
/// ```
/// use router_derive::ConfigValidate;
///
/// #[derive(ConfigValidate)]
/// struct ConnectorParams {
/// base_url: String,
/// }
///
/// enum ApplicationError {
/// InvalidConfigurationValueError(String),
/// }
///
/// #[derive(ConfigValidate)]
/// struct Connectors {
/// pub stripe: ConnectorParams,
/// pub checkout: ConnectorParams
/// }
/// ```
///
/// This will call the `validate()` function for all the fields in the struct
///
/// ```rust, ignore
/// impl Connectors {
/// fn validate(&self) -> Result<(), ApplicationError> {
/// self.stripe.validate()?;
/// self.checkout.validate()?;
/// }
/// }
/// ```
#[proc_macro_derive(ConfigValidate)]
pub fn validate_config(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
macros::misc::validate_config(input)
.unwrap_or_else(|error| error.into_compile_error())
.into()
}
/// Generates the function to get the value out of enum variant
/// Usage
/// ```
/// use router_derive::TryGetEnumVariant;
///
/// impl std::fmt::Display for RedisError {
/// fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> Result<(), std::fmt::Error> {
/// match self {
/// Self::UnknownResult => write!(f, "Unknown result")
/// }
/// }
/// }
///
/// impl std::error::Error for RedisError {}
///
/// #[derive(Debug)]
/// enum RedisError {
/// UnknownResult
/// }
///
/// #[derive(TryGetEnumVariant)]
/// #[error(RedisError::UnknownResult)]
/// enum RedisResult {
/// Set(String),
/// Get(i32)
/// }
/// ```
///
/// This will generate the function to get `String` and `i32` out of the variants
///
/// ```rust, ignore
/// impl RedisResult {
/// fn try_into_get(&self)-> Result<i32, RedisError> {
/// match self {
/// Self::Get(a) => Ok(a),
/// _=>Err(RedisError::UnknownResult)
/// }
/// }
///
/// fn try_into_set(&self)-> Result<String, RedisError> {
/// match self {
/// Self::Set(a) => Ok(a),
/// _=> Err(RedisError::UnknownResult)
/// }
/// }
/// }
/// ```
#[proc_macro_derive(TryGetEnumVariant, attributes(error))]
pub fn try_get_enum_variant(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
macros::try_get_enum::try_get_enum_variant(input)
.unwrap_or_else(|error| error.into_compile_error())
.into()
}
/// Uses the [`Serialize`] implementation of a type to derive a function implementation
/// for converting nested keys structure into a HashMap of key, value where key is in
/// the flattened form.
///
/// Example
///
/// ```
/// #[derive(Default, Serialize, FlatStruct)]
/// pub struct User {
/// name: String,
/// address: Address,
/// email: String,
/// }
///
/// #[derive(Default, Serialize)]
/// pub struct Address {
/// line1: String,
/// line2: String,
/// zip: String,
/// }
///
/// let user = User::default();
/// let flat_struct_map = user.flat_struct();
///
/// [
/// ("name", "Test"),
/// ("address.line1", "1397"),
/// ("address.line2", "Some street"),
/// ("address.zip", "941222"),
/// ("email", "[email protected]"),
/// ]
/// ```
#[proc_macro_derive(FlatStruct)]
pub fn flat_struct_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = parse_macro_input!(input as syn::DeriveInput);
let name = &input.ident;
let expanded = quote::quote! {
impl #name {
pub fn flat_struct(&self) -> std::collections::HashMap<String, String> {
use serde_json::Value;
use std::collections::HashMap;
fn flatten_value(
value: &Value,
prefix: &str,
result: &mut HashMap<String, String>
) {
match value {
Value::Object(map) => {
for (key, val) in map {
let new_key = if prefix.is_empty() {
key.to_string()
} else {
format!("{}.{}", prefix, key)
};
flatten_value(val, &new_key, result);
}
}
Value::String(s) => {
result.insert(prefix.to_string(), s.clone());
}
Value::Number(n) => {
result.insert(prefix.to_string(), n.to_string());
}
Value::Bool(b) => {
result.insert(prefix.to_string(), b.to_string());
}
_ => {}
}
}
let mut result = HashMap::new();
let value = serde_json::to_value(self).unwrap();
flatten_value(&value, "", &mut result);
result
}
}
};
proc_macro::TokenStream::from(expanded)
}
/// Generates the permissions enum and implematations for the permissions
///
/// **NOTE:** You have to make sure that all the identifiers used
/// in the macro input are present in the respective enums as well.
///
/// ## Usage
/// ```
/// use router_derive::generate_permissions;
///
/// enum Scope {
/// Read,
/// Write,
/// }
///
/// enum EntityType {
/// Profile,
/// Merchant,
/// Org,
/// }
///
/// enum Resource {
/// Payments,
/// Refunds,
/// }
///
/// generate_permissions! {
/// permissions: [
/// Payments: {
/// scopes: [Read, Write],
/// entities: [Profile, Merchant, Org]
/// },
/// Refunds: {
/// scopes: [Read],
/// entities: [Profile, Org]
/// }
/// ]
/// }
/// ```
/// This will generate the following enum.
/// ```
/// enum Permission {
/// ProfilePaymentsRead,
/// ProfilePaymentsWrite,
/// MerchantPaymentsRead,
/// MerchantPaymentsWrite,
/// OrgPaymentsRead,
/// OrgPaymentsWrite,
/// ProfileRefundsRead,
/// OrgRefundsRead,
/// ```
#[proc_macro]
pub fn generate_permissions(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
macros::generate_permissions_inner(input)
}
/// Generates the ToEncryptable trait for a type
///
/// This macro generates the temporary structs which has the fields that needs to be encrypted
///
/// fn to_encryptable: Convert the temp struct to a hashmap that can be sent over the network
/// fn from_encryptable: Convert the hashmap back to temp struct
#[proc_macro_derive(ToEncryption, attributes(encrypt))]
pub fn derive_to_encryption_attr(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
macros::derive_to_encryption(input)
.unwrap_or_else(|err| err.into_compile_error())
.into()
}
/// Derives validation functionality for structs with string-based fields that have
/// schema attributes specifying constraints like minimum and maximum lengths.
///
/// This macro generates a `validate()` method that checks if string based fields
/// meet the length requirements specified in their schema attributes.
///
/// ## Supported Types
/// - Option<T> or T: where T: String or Url
///
/// ## Supported Schema Attributes
///
/// - `min_length`: Specifies the minimum allowed character length
/// - `max_length`: Specifies the maximum allowed character length
///
/// ## Example
///
/// ```
/// use utoipa::ToSchema;
/// use router_derive::ValidateSchema;
/// use url::Url;
///
/// #[derive(Default, ToSchema, ValidateSchema)]
/// pub struct PaymentRequest {
/// #[schema(min_length = 10, max_length = 255)]
/// pub description: String,
///
/// #[schema(example = "https://example.com/return", max_length = 255)]
/// pub return_url: Option<Url>,
///
/// // Field without constraints
/// pub amount: u64,
/// }
///
/// let payment = PaymentRequest {
/// description: "Too short".to_string(),
/// return_url: Some(Url::parse("https://very-long-domain.com/callback").unwrap()),
/// amount: 1000,
/// };
///
/// let validation_result = payment.validate();
/// assert!(validation_result.is_err());
/// assert_eq!(
/// validation_result.unwrap_err(),
/// "description must be at least 10 characters long. Received 9 characters"
/// );
/// ```
///
/// ## Notes
/// - For `Option` fields, validation is only performed when the value is `Some`
/// - Fields without schema attributes or with unsupported types are ignored
/// - The validation stops on the first error encountered
/// - The generated `validate()` method returns `Ok(())` if all validations pass, or
/// `Err(String)` with an error message if any validations fail.
#[proc_macro_derive(ValidateSchema, attributes(schema))]
pub fn validate_schema(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
let input = syn::parse_macro_input!(input as syn::DeriveInput);
macros::validate_schema_derive(input)
.unwrap_or_else(|error| error.into_compile_error())
.into()
}
|
crates/router_derive/src/lib.rs
|
router_derive
|
full_file
| 6,434
| null | null | null | null | null | null | null | null | null | null | null | null | null |
pub struct BillingDetails {
country_code: Option<CountryAlpha2>,
address_lines: Option<Vec<Secret<String>>>,
family_name: Option<Secret<String>>,
given_name: Option<Secret<String>>,
postal_code: Option<Secret<String>>,
}
|
crates/hyperswitch_connectors/src/connectors/bluesnap/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 54
|
rust
|
BillingDetails
| 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. 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 = Option<String>)]
pub profile_id: Option<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(example = json!([
{
"payment_method": "wallet",
"payment_method_types": [
"upi_collect",
"upi_intent"
],
"payment_method_issuers": [
"labore magna ipsum",
"aute"
],
"payment_schemes": [
"Discover",
"Discover"
],
"accepted_currencies": {
"type": "enable_only",
"list": ["USD", "EUR"]
},
"accepted_countries": {
"type": "disable_only",
"list": ["FR", "DE","IN"]
},
"minimum_amount": 1,
"maximum_amount": 68607706,
"recurring_enabled": true,
"installment_payment_enabled": true
}
]))]
pub payment_methods_enabled: Option<Vec<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 in Test mode. By default, its value is false.
#[schema(default = false, example = false)]
pub test_mode: Option<bool>,
/// 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>>,
/// The business country to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead
#[schema(value_type = Option<CountryAlpha2>, example = "US")]
pub business_country: Option<api_enums::CountryAlpha2>,
/// The business label to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead
pub business_label: Option<String>,
/// The business sublabel to which the connector account is attached. To be deprecated soon. Use the 'profile_id' instead
#[schema(example = "chase")]
pub business_sub_label: Option<String>,
/// Unique ID of the connector
#[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = Option<String>)]
pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>,
#[schema(value_type = Option<Object>)]
pub pm_auth_config: Option<pii::SecretSerdeValue>,
#[schema(value_type = Option<ConnectorStatus>, example = "inactive")]
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>,
}
|
crates/api_models/src/admin.rs
|
api_models
|
struct_definition
| 1,086
|
rust
|
MerchantConnectorCreate
| null | null | null | null | null | null | null | null | null | null | null |
impl api::MandateSetup for Digitalvirgo {}
|
crates/hyperswitch_connectors/src/connectors/digitalvirgo.rs
|
hyperswitch_connectors
|
impl_block
| 12
|
rust
| null |
Digitalvirgo
|
api::MandateSetup for
|
impl api::MandateSetup for for Digitalvirgo
| null | null | null | null | null | null | null | null |
pub struct InespayPaymentWebhookData {
pub single_payin_id: String,
pub cod_status: InespayPSyncStatus,
pub description: String,
pub amount: MinorUnit,
pub reference: String,
pub creditor_account: Secret<String>,
pub debtor_name: Secret<String>,
pub debtor_account: Secret<String>,
pub custom_data: Option<String>,
}
|
crates/hyperswitch_connectors/src/connectors/inespay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 83
|
rust
|
InespayPaymentWebhookData
| null | null | null | null | null | null | null | null | null | null | null |
pub struct Card {
number: cards::CardNumber,
security_code: Secret<String>,
expiry_date: ExpiryDate,
}
|
crates/hyperswitch_connectors/src/connectors/authipay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 28
|
rust
|
Card
| null | null | null | null | null | null | null | null | null | null | null |
pub fn get_surcharge_keys() -> JsResult {
let keys = <SurchargeDecisionConfigs as EuclidDirFilter>::ALLOWED;
Ok(serde_wasm_bindgen::to_value(keys)?)
}
|
crates/euclid_wasm/src/lib.rs
|
euclid_wasm
|
function_signature
| 44
|
rust
| null | null | null | null |
get_surcharge_keys
| null | null | null | null | null | null | null |
File: crates/redis_interface/src/commands.rs
Public functions: 51
//! An interface to abstract the `fred` commands
//!
//! The folder provides generic functions for providing serialization
//! and deserialization while calling redis.
//! It also includes instruments to provide tracing.
use std::fmt::Debug;
use common_utils::{
errors::CustomResult,
ext_traits::{AsyncExt, ByteSliceExt, Encode, StringExt},
fp_utils,
};
use error_stack::{report, ResultExt};
use fred::{
interfaces::{HashesInterface, KeysInterface, ListInterface, SetsInterface, StreamsInterface},
prelude::{LuaInterface, RedisErrorKind},
types::{
Expiration, FromRedis, MultipleIDs, MultipleKeys, MultipleOrderedPairs, MultipleStrings,
MultipleValues, RedisMap, RedisValue, ScanType, Scanner, SetOptions, XCap, XReadResponse,
},
};
use futures::StreamExt;
use tracing::instrument;
use crate::{
errors,
types::{
DelReply, HsetnxReply, MsetnxReply, RedisEntryId, RedisKey, SaddReply, SetGetReply,
SetnxReply,
},
};
impl super::RedisConnectionPool {
pub fn add_prefix(&self, key: &str) -> String {
if self.key_prefix.is_empty() {
key.to_string()
} else {
format!("{}:{}", self.key_prefix, key)
}
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_key<V>(&self, key: &RedisKey, value: V) -> CustomResult<(), errors::RedisError>
where
V: TryInto<RedisValue> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
self.pool
.set(
key.tenant_aware_key(self),
value,
Some(Expiration::EX(self.config.default_ttl.into())),
None,
false,
)
.await
.change_context(errors::RedisError::SetFailed)
}
pub async fn set_key_without_modifying_ttl<V>(
&self,
key: &RedisKey,
value: V,
) -> CustomResult<(), errors::RedisError>
where
V: TryInto<RedisValue> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
self.pool
.set(
key.tenant_aware_key(self),
value,
Some(Expiration::KEEPTTL),
None,
false,
)
.await
.change_context(errors::RedisError::SetFailed)
}
pub async fn set_multiple_keys_if_not_exist<V>(
&self,
value: V,
) -> CustomResult<MsetnxReply, errors::RedisError>
where
V: TryInto<RedisMap> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
self.pool
.msetnx(value)
.await
.change_context(errors::RedisError::SetFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn serialize_and_set_key_if_not_exist<V>(
&self,
key: &RedisKey,
value: V,
ttl: Option<i64>,
) -> CustomResult<SetnxReply, errors::RedisError>
where
V: serde::Serialize + Debug,
{
let serialized = value
.encode_to_vec()
.change_context(errors::RedisError::JsonSerializationFailed)?;
self.set_key_if_not_exists_with_expiry(key, serialized.as_slice(), ttl)
.await
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn serialize_and_set_key<V>(
&self,
key: &RedisKey,
value: V,
) -> CustomResult<(), errors::RedisError>
where
V: serde::Serialize + Debug,
{
let serialized = value
.encode_to_vec()
.change_context(errors::RedisError::JsonSerializationFailed)?;
self.set_key(key, serialized.as_slice()).await
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn serialize_and_set_key_without_modifying_ttl<V>(
&self,
key: &RedisKey,
value: V,
) -> CustomResult<(), errors::RedisError>
where
V: serde::Serialize + Debug,
{
let serialized = value
.encode_to_vec()
.change_context(errors::RedisError::JsonSerializationFailed)?;
self.set_key_without_modifying_ttl(key, serialized.as_slice())
.await
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn serialize_and_set_key_with_expiry<V>(
&self,
key: &RedisKey,
value: V,
seconds: i64,
) -> CustomResult<(), errors::RedisError>
where
V: serde::Serialize + Debug,
{
let serialized = value
.encode_to_vec()
.change_context(errors::RedisError::JsonSerializationFailed)?;
self.pool
.set(
key.tenant_aware_key(self),
serialized.as_slice(),
Some(Expiration::EX(seconds)),
None,
false,
)
.await
.change_context(errors::RedisError::SetExFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_key<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError>
where
V: FromRedis + Unpin + Send + 'static,
{
match self
.pool
.get(key.tenant_aware_key(self))
.await
.change_context(errors::RedisError::GetFailed)
{
Ok(v) => Ok(v),
Err(_err) => {
#[cfg(not(feature = "multitenancy_fallback"))]
{
Err(_err)
}
#[cfg(feature = "multitenancy_fallback")]
{
self.pool
.get(key.tenant_unaware_key(self))
.await
.change_context(errors::RedisError::GetFailed)
}
}
}
}
#[instrument(level = "DEBUG", skip(self))]
async fn get_multiple_keys_with_mget<V>(
&self,
keys: &[RedisKey],
) -> CustomResult<Vec<Option<V>>, errors::RedisError>
where
V: FromRedis + Unpin + Send + 'static,
{
if keys.is_empty() {
return Ok(Vec::new());
}
let tenant_aware_keys: Vec<String> =
keys.iter().map(|key| key.tenant_aware_key(self)).collect();
self.pool
.mget(tenant_aware_keys)
.await
.change_context(errors::RedisError::GetFailed)
}
#[instrument(level = "DEBUG", skip(self))]
async fn get_multiple_keys_with_parallel_get<V>(
&self,
keys: &[RedisKey],
) -> CustomResult<Vec<Option<V>>, errors::RedisError>
where
V: FromRedis + Unpin + Send + 'static,
{
if keys.is_empty() {
return Ok(Vec::new());
}
let tenant_aware_keys: Vec<String> =
keys.iter().map(|key| key.tenant_aware_key(self)).collect();
let futures = tenant_aware_keys
.iter()
.map(|redis_key| self.pool.get::<Option<V>, _>(redis_key));
let results = futures::future::try_join_all(futures)
.await
.change_context(errors::RedisError::GetFailed)
.attach_printable("Failed to get keys in cluster mode")?;
Ok(results)
}
/// Helper method to encapsulate the logic for choosing between cluster and non-cluster modes
#[instrument(level = "DEBUG", skip(self))]
async fn get_keys_by_mode<V>(
&self,
keys: &[RedisKey],
) -> CustomResult<Vec<Option<V>>, errors::RedisError>
where
V: FromRedis + Unpin + Send + 'static,
{
if self.config.cluster_enabled {
// Use individual GET commands for cluster mode to avoid CROSSSLOT errors
self.get_multiple_keys_with_parallel_get(keys).await
} else {
// Use MGET for non-cluster mode for better performance
self.get_multiple_keys_with_mget(keys).await
}
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_multiple_keys<V>(
&self,
keys: &[RedisKey],
) -> CustomResult<Vec<Option<V>>, errors::RedisError>
where
V: FromRedis + Unpin + Send + 'static,
{
if keys.is_empty() {
return Ok(Vec::new());
}
match self.get_keys_by_mode(keys).await {
Ok(values) => Ok(values),
Err(_err) => {
#[cfg(not(feature = "multitenancy_fallback"))]
{
Err(_err)
}
#[cfg(feature = "multitenancy_fallback")]
{
let tenant_unaware_keys: Vec<RedisKey> = keys
.iter()
.map(|key| key.tenant_unaware_key(self).into())
.collect();
self.get_keys_by_mode(&tenant_unaware_keys).await
}
}
}
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn exists<V>(&self, key: &RedisKey) -> CustomResult<bool, errors::RedisError>
where
V: Into<MultipleKeys> + Unpin + Send + 'static,
{
match self
.pool
.exists(key.tenant_aware_key(self))
.await
.change_context(errors::RedisError::GetFailed)
{
Ok(v) => Ok(v),
Err(_err) => {
#[cfg(not(feature = "multitenancy_fallback"))]
{
Err(_err)
}
#[cfg(feature = "multitenancy_fallback")]
{
self.pool
.exists(key.tenant_unaware_key(self))
.await
.change_context(errors::RedisError::GetFailed)
}
}
}
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_and_deserialize_key<T>(
&self,
key: &RedisKey,
type_name: &'static str,
) -> CustomResult<T, errors::RedisError>
where
T: serde::de::DeserializeOwned,
{
let value_bytes = self.get_key::<Vec<u8>>(key).await?;
fp_utils::when(value_bytes.is_empty(), || Err(errors::RedisError::NotFound))?;
value_bytes
.parse_struct(type_name)
.change_context(errors::RedisError::JsonDeserializationFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_and_deserialize_multiple_keys<T>(
&self,
keys: &[RedisKey],
type_name: &'static str,
) -> CustomResult<Vec<Option<T>>, errors::RedisError>
where
T: serde::de::DeserializeOwned,
{
let value_bytes_vec = self.get_multiple_keys::<Vec<u8>>(keys).await?;
let mut results = Vec::with_capacity(value_bytes_vec.len());
for value_bytes_opt in value_bytes_vec {
match value_bytes_opt {
Some(value_bytes) => {
if value_bytes.is_empty() {
results.push(None);
} else {
let parsed = value_bytes
.parse_struct(type_name)
.change_context(errors::RedisError::JsonDeserializationFailed)?;
results.push(Some(parsed));
}
}
None => results.push(None),
}
}
Ok(results)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn delete_key(&self, key: &RedisKey) -> CustomResult<DelReply, errors::RedisError> {
match self
.pool
.del(key.tenant_aware_key(self))
.await
.change_context(errors::RedisError::DeleteFailed)
{
Ok(v) => Ok(v),
Err(_err) => {
#[cfg(not(feature = "multitenancy_fallback"))]
{
Err(_err)
}
#[cfg(feature = "multitenancy_fallback")]
{
self.pool
.del(key.tenant_unaware_key(self))
.await
.change_context(errors::RedisError::DeleteFailed)
}
}
}
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn delete_multiple_keys(
&self,
keys: &[RedisKey],
) -> CustomResult<Vec<DelReply>, errors::RedisError> {
let futures = keys.iter().map(|key| self.delete_key(key));
let del_result = futures::future::try_join_all(futures)
.await
.change_context(errors::RedisError::DeleteFailed)?;
Ok(del_result)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_key_with_expiry<V>(
&self,
key: &RedisKey,
value: V,
seconds: i64,
) -> CustomResult<(), errors::RedisError>
where
V: TryInto<RedisValue> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
self.pool
.set(
key.tenant_aware_key(self),
value,
Some(Expiration::EX(seconds)),
None,
false,
)
.await
.change_context(errors::RedisError::SetExFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_key_if_not_exists_with_expiry<V>(
&self,
key: &RedisKey,
value: V,
seconds: Option<i64>,
) -> CustomResult<SetnxReply, errors::RedisError>
where
V: TryInto<RedisValue> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
self.pool
.set(
key.tenant_aware_key(self),
value,
Some(Expiration::EX(
seconds.unwrap_or(self.config.default_ttl.into()),
)),
Some(SetOptions::NX),
false,
)
.await
.change_context(errors::RedisError::SetFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_expiry(
&self,
key: &RedisKey,
seconds: i64,
) -> CustomResult<(), errors::RedisError> {
self.pool
.expire(key.tenant_aware_key(self), seconds)
.await
.change_context(errors::RedisError::SetExpiryFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_expire_at(
&self,
key: &RedisKey,
timestamp: i64,
) -> CustomResult<(), errors::RedisError> {
self.pool
.expire_at(key.tenant_aware_key(self), timestamp)
.await
.change_context(errors::RedisError::SetExpiryFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_hash_fields<V>(
&self,
key: &RedisKey,
values: V,
ttl: Option<i64>,
) -> CustomResult<(), errors::RedisError>
where
V: TryInto<RedisMap> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
let output: Result<(), _> = self
.pool
.hset(key.tenant_aware_key(self), values)
.await
.change_context(errors::RedisError::SetHashFailed);
// setting expiry for the key
output
.async_and_then(|_| {
self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl.into()))
})
.await
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_hash_field_if_not_exist<V>(
&self,
key: &RedisKey,
field: &str,
value: V,
ttl: Option<u32>,
) -> CustomResult<HsetnxReply, errors::RedisError>
where
V: TryInto<RedisValue> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
let output: Result<HsetnxReply, _> = self
.pool
.hsetnx(key.tenant_aware_key(self), field, value)
.await
.change_context(errors::RedisError::SetHashFieldFailed);
output
.async_and_then(|inner| async {
self.set_expiry(key, ttl.unwrap_or(self.config.default_hash_ttl).into())
.await?;
Ok(inner)
})
.await
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn serialize_and_set_hash_field_if_not_exist<V>(
&self,
key: &RedisKey,
field: &str,
value: V,
ttl: Option<u32>,
) -> CustomResult<HsetnxReply, errors::RedisError>
where
V: serde::Serialize + Debug,
{
let serialized = value
.encode_to_vec()
.change_context(errors::RedisError::JsonSerializationFailed)?;
self.set_hash_field_if_not_exist(key, field, serialized.as_slice(), ttl)
.await
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn serialize_and_set_multiple_hash_field_if_not_exist<V>(
&self,
kv: &[(&RedisKey, V)],
field: &str,
ttl: Option<u32>,
) -> CustomResult<Vec<HsetnxReply>, errors::RedisError>
where
V: serde::Serialize + Debug,
{
let mut hsetnx: Vec<HsetnxReply> = Vec::with_capacity(kv.len());
for (key, val) in kv {
hsetnx.push(
self.serialize_and_set_hash_field_if_not_exist(key, field, val, ttl)
.await?,
);
}
Ok(hsetnx)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn increment_fields_in_hash<T>(
&self,
key: &RedisKey,
fields_to_increment: &[(T, i64)],
) -> CustomResult<Vec<usize>, errors::RedisError>
where
T: Debug + ToString,
{
let mut values_after_increment = Vec::with_capacity(fields_to_increment.len());
for (field, increment) in fields_to_increment.iter() {
values_after_increment.push(
self.pool
.hincrby(key.tenant_aware_key(self), field.to_string(), *increment)
.await
.change_context(errors::RedisError::IncrementHashFieldFailed)?,
)
}
Ok(values_after_increment)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn hscan(
&self,
key: &RedisKey,
pattern: &str,
count: Option<u32>,
) -> CustomResult<Vec<String>, errors::RedisError> {
Ok(self
.pool
.next()
.hscan::<&str, &str>(&key.tenant_aware_key(self), pattern, count)
.filter_map(|value| async move {
match value {
Ok(mut v) => {
let v = v.take_results()?;
let v: Vec<String> =
v.iter().filter_map(|(_, val)| val.as_string()).collect();
Some(futures::stream::iter(v))
}
Err(err) => {
tracing::error!(redis_err=?err, "Redis error while executing hscan command");
None
}
}
})
.flatten()
.collect::<Vec<_>>()
.await)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn scan(
&self,
pattern: &RedisKey,
count: Option<u32>,
scan_type: Option<ScanType>,
) -> CustomResult<Vec<String>, errors::RedisError> {
Ok(self
.pool
.next()
.scan(pattern.tenant_aware_key(self), count, scan_type)
.filter_map(|value| async move {
match value {
Ok(mut v) => {
let v = v.take_results()?;
let v: Vec<String> =
v.into_iter().filter_map(|val| val.into_string()).collect();
Some(futures::stream::iter(v))
}
Err(err) => {
tracing::error!(redis_err=?err, "Redis error while executing scan command");
None
}
}
})
.flatten()
.collect::<Vec<_>>()
.await)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn hscan_and_deserialize<T>(
&self,
key: &RedisKey,
pattern: &str,
count: Option<u32>,
) -> CustomResult<Vec<T>, errors::RedisError>
where
T: serde::de::DeserializeOwned,
{
let redis_results = self.hscan(key, pattern, count).await?;
Ok(redis_results
.iter()
.filter_map(|v| {
let r: T = v.parse_struct(std::any::type_name::<T>()).ok()?;
Some(r)
})
.collect())
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_hash_field<V>(
&self,
key: &RedisKey,
field: &str,
) -> CustomResult<V, errors::RedisError>
where
V: FromRedis + Unpin + Send + 'static,
{
match self
.pool
.hget(key.tenant_aware_key(self), field)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
{
Ok(v) => Ok(v),
Err(_err) => {
#[cfg(feature = "multitenancy_fallback")]
{
self.pool
.hget(key.tenant_unaware_key(self), field)
.await
.change_context(errors::RedisError::GetHashFieldFailed)
}
#[cfg(not(feature = "multitenancy_fallback"))]
{
Err(_err)
}
}
}
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_hash_fields<V>(&self, key: &RedisKey) -> CustomResult<V, errors::RedisError>
where
V: FromRedis + Unpin + Send + 'static,
{
match self
.pool
.hgetall(key.tenant_aware_key(self))
.await
.change_context(errors::RedisError::GetHashFieldFailed)
{
Ok(v) => Ok(v),
Err(_err) => {
#[cfg(feature = "multitenancy_fallback")]
{
self.pool
.hgetall(key.tenant_unaware_key(self))
.await
.change_context(errors::RedisError::GetHashFieldFailed)
}
#[cfg(not(feature = "multitenancy_fallback"))]
{
Err(_err)
}
}
}
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_hash_field_and_deserialize<V>(
&self,
key: &RedisKey,
field: &str,
type_name: &'static str,
) -> CustomResult<V, errors::RedisError>
where
V: serde::de::DeserializeOwned,
{
let value_bytes = self.get_hash_field::<Vec<u8>>(key, field).await?;
if value_bytes.is_empty() {
return Err(errors::RedisError::NotFound.into());
}
value_bytes
.parse_struct(type_name)
.change_context(errors::RedisError::JsonDeserializationFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn sadd<V>(
&self,
key: &RedisKey,
members: V,
) -> CustomResult<SaddReply, errors::RedisError>
where
V: TryInto<MultipleValues> + Debug + Send,
V::Error: Into<fred::error::RedisError> + Send,
{
self.pool
.sadd(key.tenant_aware_key(self), members)
.await
.change_context(errors::RedisError::SetAddMembersFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn stream_append_entry<F>(
&self,
stream: &RedisKey,
entry_id: &RedisEntryId,
fields: F,
) -> CustomResult<(), errors::RedisError>
where
F: TryInto<MultipleOrderedPairs> + Debug + Send + Sync,
F::Error: Into<fred::error::RedisError> + Send + Sync,
{
self.pool
.xadd(stream.tenant_aware_key(self), false, None, entry_id, fields)
.await
.change_context(errors::RedisError::StreamAppendFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn stream_delete_entries<Ids>(
&self,
stream: &RedisKey,
ids: Ids,
) -> CustomResult<usize, errors::RedisError>
where
Ids: Into<MultipleStrings> + Debug + Send + Sync,
{
self.pool
.xdel(stream.tenant_aware_key(self), ids)
.await
.change_context(errors::RedisError::StreamDeleteFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn stream_trim_entries<C>(
&self,
stream: &RedisKey,
xcap: C,
) -> CustomResult<usize, errors::RedisError>
where
C: TryInto<XCap> + Debug + Send + Sync,
C::Error: Into<fred::error::RedisError> + Send + Sync,
{
self.pool
.xtrim(stream.tenant_aware_key(self), xcap)
.await
.change_context(errors::RedisError::StreamTrimFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn stream_acknowledge_entries<Ids>(
&self,
stream: &RedisKey,
group: &str,
ids: Ids,
) -> CustomResult<usize, errors::RedisError>
where
Ids: Into<MultipleIDs> + Debug + Send + Sync,
{
self.pool
.xack(stream.tenant_aware_key(self), group, ids)
.await
.change_context(errors::RedisError::StreamAcknowledgeFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn stream_get_length(
&self,
stream: &RedisKey,
) -> CustomResult<usize, errors::RedisError> {
self.pool
.xlen(stream.tenant_aware_key(self))
.await
.change_context(errors::RedisError::GetLengthFailed)
}
pub fn get_keys_with_prefix<K>(&self, keys: K) -> MultipleKeys
where
K: Into<MultipleKeys> + Debug + Send + Sync,
{
let multiple_keys: MultipleKeys = keys.into();
let res = multiple_keys
.inner()
.iter()
.filter_map(|key| key.as_str().map(RedisKey::from))
.map(|k: RedisKey| k.tenant_aware_key(self))
.collect::<Vec<_>>();
MultipleKeys::from(res)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn stream_read_entries<K, Ids>(
&self,
streams: K,
ids: Ids,
read_count: Option<u64>,
) -> CustomResult<XReadResponse<String, String, String, String>, errors::RedisError>
where
K: Into<MultipleKeys> + Debug + Send + Sync,
Ids: Into<MultipleIDs> + Debug + Send + Sync,
{
let strms = self.get_keys_with_prefix(streams);
self.pool
.xread_map(
Some(read_count.unwrap_or(self.config.default_stream_read_count)),
None,
strms,
ids,
)
.await
.map_err(|err| match err.kind() {
RedisErrorKind::NotFound | RedisErrorKind::Parse => {
report!(err).change_context(errors::RedisError::StreamEmptyOrNotAvailable)
}
_ => report!(err).change_context(errors::RedisError::StreamReadFailed),
})
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn stream_read_with_options<K, Ids>(
&self,
streams: K,
ids: Ids,
count: Option<u64>,
block: Option<u64>, // timeout in milliseconds
group: Option<(&str, &str)>, // (group_name, consumer_name)
) -> CustomResult<XReadResponse<String, String, String, Option<String>>, errors::RedisError>
where
K: Into<MultipleKeys> + Debug + Send + Sync,
Ids: Into<MultipleIDs> + Debug + Send + Sync,
{
match group {
Some((group_name, consumer_name)) => {
self.pool
.xreadgroup_map(
group_name,
consumer_name,
count,
block,
false,
self.get_keys_with_prefix(streams),
ids,
)
.await
}
None => {
self.pool
.xread_map(count, block, self.get_keys_with_prefix(streams), ids)
.await
}
}
.map_err(|err| match err.kind() {
RedisErrorKind::NotFound | RedisErrorKind::Parse => {
report!(err).change_context(errors::RedisError::StreamEmptyOrNotAvailable)
}
_ => report!(err).change_context(errors::RedisError::StreamReadFailed),
})
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn append_elements_to_list<V>(
&self,
key: &RedisKey,
elements: V,
) -> CustomResult<(), errors::RedisError>
where
V: TryInto<MultipleValues> + Debug + Send,
V::Error: Into<fred::error::RedisError> + Send,
{
self.pool
.rpush(key.tenant_aware_key(self), elements)
.await
.change_context(errors::RedisError::AppendElementsToListFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_list_elements(
&self,
key: &RedisKey,
start: i64,
stop: i64,
) -> CustomResult<Vec<String>, errors::RedisError> {
self.pool
.lrange(key.tenant_aware_key(self), start, stop)
.await
.change_context(errors::RedisError::GetListElementsFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn get_list_length(&self, key: &RedisKey) -> CustomResult<usize, errors::RedisError> {
self.pool
.llen(key.tenant_aware_key(self))
.await
.change_context(errors::RedisError::GetListLengthFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn lpop_list_elements(
&self,
key: &RedisKey,
count: Option<usize>,
) -> CustomResult<Vec<String>, errors::RedisError> {
self.pool
.lpop(key.tenant_aware_key(self), count)
.await
.change_context(errors::RedisError::PopListElementsFailed)
}
// Consumer Group API
#[instrument(level = "DEBUG", skip(self))]
pub async fn consumer_group_create(
&self,
stream: &RedisKey,
group: &str,
id: &RedisEntryId,
) -> CustomResult<(), errors::RedisError> {
if matches!(
id,
RedisEntryId::AutoGeneratedID | RedisEntryId::UndeliveredEntryID
) {
// FIXME: Replace with utils::when
Err(errors::RedisError::InvalidRedisEntryId)?;
}
self.pool
.xgroup_create(stream.tenant_aware_key(self), group, id, true)
.await
.change_context(errors::RedisError::ConsumerGroupCreateFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn consumer_group_destroy(
&self,
stream: &RedisKey,
group: &str,
) -> CustomResult<usize, errors::RedisError> {
self.pool
.xgroup_destroy(stream.tenant_aware_key(self), group)
.await
.change_context(errors::RedisError::ConsumerGroupDestroyFailed)
}
// the number of pending messages that the consumer had before it was deleted
#[instrument(level = "DEBUG", skip(self))]
pub async fn consumer_group_delete_consumer(
&self,
stream: &RedisKey,
group: &str,
consumer: &str,
) -> CustomResult<usize, errors::RedisError> {
self.pool
.xgroup_delconsumer(stream.tenant_aware_key(self), group, consumer)
.await
.change_context(errors::RedisError::ConsumerGroupRemoveConsumerFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn consumer_group_set_last_id(
&self,
stream: &RedisKey,
group: &str,
id: &RedisEntryId,
) -> CustomResult<String, errors::RedisError> {
self.pool
.xgroup_setid(stream.tenant_aware_key(self), group, id)
.await
.change_context(errors::RedisError::ConsumerGroupSetIdFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn consumer_group_set_message_owner<Ids, R>(
&self,
stream: &RedisKey,
group: &str,
consumer: &str,
min_idle_time: u64,
ids: Ids,
) -> CustomResult<R, errors::RedisError>
where
Ids: Into<MultipleIDs> + Debug + Send + Sync,
R: FromRedis + Unpin + Send + 'static,
{
self.pool
.xclaim(
stream.tenant_aware_key(self),
group,
consumer,
min_idle_time,
ids,
None,
None,
None,
false,
false,
)
.await
.change_context(errors::RedisError::ConsumerGroupClaimFailed)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn evaluate_redis_script<V, T>(
&self,
lua_script: &'static str,
key: Vec<String>,
values: V,
) -> CustomResult<T, errors::RedisError>
where
V: TryInto<MultipleValues> + Debug + Send + Sync,
V::Error: Into<fred::error::RedisError> + Send + Sync,
T: serde::de::DeserializeOwned + FromRedis,
{
let val: T = self
.pool
.eval(lua_script, key, values)
.await
.change_context(errors::RedisError::IncrementHashFieldFailed)?;
Ok(val)
}
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_multiple_keys_if_not_exists_and_get_values<V>(
&self,
keys: &[(RedisKey, V)],
ttl: Option<i64>,
) -> CustomResult<Vec<SetGetReply<V>>, errors::RedisError>
where
V: TryInto<RedisValue>
+ Debug
+ FromRedis
+ ToOwned<Owned = V>
+ Send
+ Sync
+ serde::de::DeserializeOwned,
V::Error: Into<fred::error::RedisError> + Send + Sync,
{
let futures = keys.iter().map(|(key, value)| {
self.set_key_if_not_exists_and_get_value(key, (*value).to_owned(), ttl)
});
let del_result = futures::future::try_join_all(futures)
.await
.change_context(errors::RedisError::SetFailed)?;
Ok(del_result)
}
/// Sets a value in Redis if not already present, and returns the value (either existing or newly set).
/// This operation is atomic using Redis transactions.
#[instrument(level = "DEBUG", skip(self))]
pub async fn set_key_if_not_exists_and_get_value<V>(
&self,
key: &RedisKey,
value: V,
ttl: Option<i64>,
) -> CustomResult<SetGetReply<V>, errors::RedisError>
where
|
crates/redis_interface/src/commands.rs#chunk0
|
redis_interface
|
chunk
| 8,177
| null | null | null | null | null | null | null | null | null | null | null | null | null |
FiuuWebhooksResponse::FiuuWebhookRefundResponse(webhook_refund_response) => {
Ok(Box::new(fiuu::FiuuRefundSyncResponse::Webhook(
webhook_refund_response,
)))
}
}
}
fn get_mandate_details(
&self,
request: &webhooks::IncomingWebhookRequestDetails<'_>,
) -> CustomResult<
Option<hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails>,
errors::ConnectorError,
> {
parse_and_log_keys_in_url_encoded_response::<transformers::FiuuWebhooksPaymentResponse>(
request.body,
);
let webhook_payment_response: transformers::FiuuWebhooksPaymentResponse =
serde_urlencoded::from_bytes::<transformers::FiuuWebhooksPaymentResponse>(request.body)
.change_context(errors::ConnectorError::WebhookResourceObjectNotFound)?;
let mandate_reference = webhook_payment_response.extra_parameters.as_ref().and_then(|extra_p| {
let mandate_token: Result<ExtraParameters, _> = serde_json::from_str(&extra_p.clone().expose());
match mandate_token {
Ok(token) => {
token.token.as_ref().map(|token| hyperswitch_domain_models::router_flow_types::ConnectorMandateDetails {
connector_mandate_id:token.clone(),
})
}
Err(err) => {
router_env::logger::warn!(
"Failed to convert 'extraP' from fiuu webhook response to fiuu::ExtraParameters. \
Input: '{:?}', Error: {}",
extra_p,
err
);
None
}
}
});
Ok(mandate_reference)
}
}
static FIUU_SUPPORTED_PAYMENT_METHODS: LazyLock<SupportedPaymentMethods> = LazyLock::new(|| {
let supported_capture_methods = vec![
CaptureMethod::Automatic,
CaptureMethod::Manual,
CaptureMethod::SequentialAutomatic,
];
let supported_card_network = vec![
common_enums::CardNetwork::Visa,
common_enums::CardNetwork::JCB,
common_enums::CardNetwork::DinersClub,
common_enums::CardNetwork::UnionPay,
common_enums::CardNetwork::Mastercard,
common_enums::CardNetwork::Discover,
];
let mut fiuu_supported_payment_methods = SupportedPaymentMethods::new();
fiuu_supported_payment_methods.add(
PaymentMethod::RealTimePayment,
PaymentMethodType::DuitNow,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
fiuu_supported_payment_methods.add(
PaymentMethod::BankRedirect,
PaymentMethodType::OnlineBankingFpx,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
fiuu_supported_payment_methods.add(
PaymentMethod::Wallet,
PaymentMethodType::GooglePay,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
fiuu_supported_payment_methods.add(
PaymentMethod::Wallet,
PaymentMethodType::ApplePay,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::NotSupported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: None,
},
);
fiuu_supported_payment_methods.add(
PaymentMethod::Card,
PaymentMethodType::Credit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
fiuu_supported_payment_methods.add(
PaymentMethod::Card,
PaymentMethodType::Debit,
PaymentMethodDetails {
mandates: common_enums::FeatureStatus::Supported,
refunds: common_enums::FeatureStatus::Supported,
supported_capture_methods: supported_capture_methods.clone(),
specific_features: Some(
api_models::feature_matrix::PaymentMethodSpecificFeatures::Card({
api_models::feature_matrix::CardSpecificFeatures {
three_ds: common_enums::FeatureStatus::Supported,
no_three_ds: common_enums::FeatureStatus::Supported,
supported_card_networks: supported_card_network.clone(),
}
}),
),
},
);
fiuu_supported_payment_methods
});
static FIUU_CONNECTOR_INFO: ConnectorInfo = ConnectorInfo {
display_name: "Fiuu",
description:
"Fiuu, formerly known as Razer Merchant Services, is a leading online payment gateway in Southeast Asia, offering secure and seamless payment solutions for businesses of all sizes, including credit and debit cards, e-wallets, and bank transfers.",
connector_type: common_enums::HyperswitchConnectorCategory::PaymentGateway,
integration_status: common_enums::ConnectorIntegrationStatus::Live,
};
static FIUU_SUPPORTED_WEBHOOK_FLOWS: [common_enums::EventClass; 2] = [
common_enums::EventClass::Payments,
common_enums::EventClass::Refunds,
];
impl ConnectorSpecifications for Fiuu {
fn get_connector_about(&self) -> Option<&'static ConnectorInfo> {
Some(&FIUU_CONNECTOR_INFO)
}
fn get_supported_payment_methods(&self) -> Option<&'static SupportedPaymentMethods> {
Some(&*FIUU_SUPPORTED_PAYMENT_METHODS)
}
fn get_supported_webhook_flows(&self) -> Option<&'static [common_enums::EventClass]> {
Some(&FIUU_SUPPORTED_WEBHOOK_FLOWS)
}
}
|
crates/hyperswitch_connectors/src/connectors/fiuu.rs#chunk1
|
hyperswitch_connectors
|
chunk
| 1,372
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl ApiEventMetric for CurrencyConversionResponse {}
|
crates/api_models/src/currency.rs
|
api_models
|
impl_block
| 9
|
rust
| null |
CurrencyConversionResponse
|
ApiEventMetric for
|
impl ApiEventMetric for for CurrencyConversionResponse
| null | null | null | null | null | null | null | null |
pub async fn mk_basilisk_req(
jwekey: &settings::Jwekey,
jws: &str,
locker_choice: api_enums::LockerChoice,
) -> CustomResult<encryption::JweBody, errors::VaultError> {
let jws_payload: Vec<&str> = jws.split('.').collect();
let generate_jws_body = |payload: Vec<&str>| -> Option<encryption::JwsBody> {
Some(encryption::JwsBody {
header: payload.first()?.to_string(),
payload: payload.get(1)?.to_string(),
signature: payload.get(2)?.to_string(),
})
};
let jws_body = generate_jws_body(jws_payload).ok_or(errors::VaultError::SaveCardFailed)?;
let payload = jws_body
.encode_to_vec()
.change_context(errors::VaultError::SaveCardFailed)?;
let public_key = match locker_choice {
api_enums::LockerChoice::HyperswitchCardVault => {
jwekey.vault_encryption_key.peek().as_bytes()
}
};
let jwe_encrypted =
encryption::encrypt_jwe(&payload, public_key, EncryptionAlgorithm::A256GCM, None)
.await
.change_context(errors::VaultError::SaveCardFailed)
.attach_printable("Error on jwe encrypt")?;
let jwe_payload: Vec<&str> = jwe_encrypted.split('.').collect();
let generate_jwe_body = |payload: Vec<&str>| -> Option<encryption::JweBody> {
Some(encryption::JweBody {
header: payload.first()?.to_string(),
iv: payload.get(2)?.to_string(),
encrypted_payload: payload.get(3)?.to_string(),
tag: payload.get(4)?.to_string(),
encrypted_key: payload.get(1)?.to_string(),
})
};
let jwe_body = generate_jwe_body(jwe_payload).ok_or(errors::VaultError::SaveCardFailed)?;
Ok(jwe_body)
}
|
crates/router/src/core/payment_methods/transformers.rs
|
router
|
function_signature
| 442
|
rust
| null | null | null | null |
mk_basilisk_req
| null | null | null | null | null | null | null |
pub struct TokenizedBankRedirectValue2 {
pub customer_id: Option<id_type::CustomerId>,
}
|
crates/api_models/src/payment_methods.rs
|
api_models
|
struct_definition
| 22
|
rust
|
TokenizedBankRedirectValue2
| null | null | null | null | null | null | null | null | null | null | null |
pub struct AuthipayRefundRequest {
request_type: &'static str,
transaction_amount: Amount,
}
|
crates/hyperswitch_connectors/src/connectors/authipay/transformers.rs
|
hyperswitch_connectors
|
struct_definition
| 23
|
rust
|
AuthipayRefundRequest
| null | null | null | null | null | null | null | null | null | null | null |
let jwe_body = response
.unwrap_or_else(|err| err)
.response
.parse_struct::<services::JweBody>("JweBody")
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed while parsing locker response into JweBody")?;
let decrypted_payload = payment_methods::get_decrypted_response_payload(
jwekey,
jwe_body,
locker_choice,
locker.decryption_scheme.clone(),
)
.await
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Failed while decrypting locker payload response")?;
// Irrespective of locker's response status, payload is JWE + JWS decrypted. But based on locker's status,
// if Ok, deserialize the decrypted payload into given type T
// if Err, raise an error including locker error message too
if is_locker_call_succeeded {
let stored_card_resp: Result<T, error_stack::Report<errors::VaultError>> =
decrypted_payload
.parse_struct(response_type_name)
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable_lazy(|| {
format!("Failed while parsing locker response into {response_type_name}")
});
stored_card_resp
} else {
Err::<T, error_stack::Report<errors::VaultError>>((errors::VaultError::ApiError).into())
.attach_printable_lazy(|| format!("Locker error response: {decrypted_payload:?}"))
}
}
#[cfg(feature = "v1")]
pub async fn update_payment_method_metadata_and_last_used(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
db: &dyn db::StorageInterface,
pm: domain::PaymentMethod,
pm_metadata: Option<serde_json::Value>,
storage_scheme: MerchantStorageScheme,
) -> errors::CustomResult<(), errors::VaultError> {
let pm_update = payment_method::PaymentMethodUpdate::MetadataUpdateAndLastUsed {
metadata: pm_metadata,
last_used_at: common_utils::date_time::now(),
};
db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
Ok(())
}
pub async fn update_payment_method_and_last_used(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
db: &dyn db::StorageInterface,
pm: domain::PaymentMethod,
payment_method_update: Option<Encryption>,
storage_scheme: MerchantStorageScheme,
card_scheme: Option<String>,
) -> errors::CustomResult<(), errors::VaultError> {
let pm_update = payment_method::PaymentMethodUpdate::UpdatePaymentMethodDataAndLastUsed {
payment_method_data: payment_method_update,
scheme: card_scheme,
last_used_at: common_utils::date_time::now(),
};
db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
Ok(())
}
#[cfg(feature = "v2")]
pub async fn update_payment_method_connector_mandate_details(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
db: &dyn db::StorageInterface,
pm: domain::PaymentMethod,
connector_mandate_details: Option<CommonMandateReference>,
storage_scheme: MerchantStorageScheme,
) -> errors::CustomResult<(), errors::VaultError> {
let pm_update = payment_method::PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details: connector_mandate_details.map(|cmd| cmd.into()),
};
db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
Ok(())
}
#[cfg(feature = "v1")]
pub async fn update_payment_method_connector_mandate_details(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
db: &dyn db::StorageInterface,
pm: domain::PaymentMethod,
connector_mandate_details: Option<CommonMandateReference>,
storage_scheme: MerchantStorageScheme,
) -> errors::CustomResult<(), errors::VaultError> {
let connector_mandate_details_value = connector_mandate_details
.map(|common_mandate| {
common_mandate.get_mandate_details_value().map_err(|err| {
router_env::logger::error!("Failed to get get_mandate_details_value : {:?}", err);
errors::VaultError::UpdateInPaymentMethodDataTableFailed
})
})
.transpose()?;
let pm_update = payment_method::PaymentMethodUpdate::ConnectorMandateDetailsUpdate {
connector_mandate_details: connector_mandate_details_value,
};
db.update_payment_method(&(state.into()), key_store, pm, pm_update, storage_scheme)
.await
.change_context(errors::VaultError::UpdateInPaymentMethodDataTableFailed)?;
Ok(())
}
#[instrument(skip_all)]
pub async fn get_card_from_hs_locker<'a>(
state: &'a routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &'a str,
locker_choice: api_enums::LockerChoice,
) -> errors::CustomResult<Card, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = &state.conf.jwekey.get_inner();
if !locker.mock_locker {
let request = payment_methods::mk_get_card_request_hs(
jwekey,
locker,
customer_id,
merchant_id,
card_reference,
Some(locker_choice),
state.tenant.tenant_id.clone(),
state.request_id,
)
.await
.change_context(errors::VaultError::FetchCardFailed)
.attach_printable("Making get card request failed")?;
let get_card_resp = call_locker_api::<payment_methods::RetrieveCardResp>(
state,
request,
"get_card_from_locker",
Some(locker_choice),
)
.await
.change_context(errors::VaultError::FetchCardFailed)?;
let retrieve_card_resp = get_card_resp
.payload
.get_required_value("RetrieveCardRespPayload")
.change_context(errors::VaultError::FetchCardFailed)?;
retrieve_card_resp
.card
.get_required_value("Card")
.change_context(errors::VaultError::FetchCardFailed)
} else {
let (get_card_resp, _) = mock_get_card(&*state.store, card_reference).await?;
payment_methods::mk_get_card_response(get_card_resp)
.change_context(errors::VaultError::ResponseDeserializationFailed)
}
}
#[instrument(skip_all)]
pub async fn delete_card_from_hs_locker<'a>(
state: &routes::SessionState,
customer_id: &id_type::CustomerId,
merchant_id: &id_type::MerchantId,
card_reference: &'a str,
) -> errors::CustomResult<payment_methods::DeleteCardResp, errors::VaultError> {
let locker = &state.conf.locker;
let jwekey = &state.conf.jwekey.get_inner();
let request = payment_methods::mk_delete_card_request_hs(
jwekey,
locker,
customer_id,
merchant_id,
card_reference,
state.tenant.tenant_id.clone(),
state.request_id,
)
.await
.change_context(errors::VaultError::DeleteCardFailed)
.attach_printable("Making delete card request failed")?;
if !locker.mock_locker {
call_locker_api::<payment_methods::DeleteCardResp>(
state,
request,
"delete_card_from_locker",
Some(api_enums::LockerChoice::HyperswitchCardVault),
)
.await
.change_context(errors::VaultError::DeleteCardFailed)
} else {
Ok(mock_delete_card_hs(&*state.store, card_reference)
.await
.change_context(errors::VaultError::DeleteCardFailed)?)
}
}
// Need to fix this function while completing v2
#[cfg(feature = "v2")]
#[instrument(skip_all)]
pub async fn delete_card_from_hs_locker_by_global_id<'a>(
state: &routes::SessionState,
id: &str,
merchant_id: &id_type::MerchantId,
card_reference: &'a str,
) -> errors::RouterResult<payment_methods::DeleteCardResp> {
todo!()
}
///Mock api for local testing
pub async fn mock_call_to_locker_hs(
db: &dyn db::StorageInterface,
card_id: &str,
payload: &payment_methods::StoreLockerReq,
card_cvc: Option<String>,
payment_method_id: Option<String>,
customer_id: Option<&id_type::CustomerId>,
) -> errors::CustomResult<payment_methods::StoreCardResp, errors::VaultError> {
let mut locker_mock_up = storage::LockerMockUpNew {
card_id: card_id.to_string(),
external_id: uuid::Uuid::new_v4().to_string(),
card_fingerprint: uuid::Uuid::new_v4().to_string(),
card_global_fingerprint: uuid::Uuid::new_v4().to_string(),
merchant_id: id_type::MerchantId::default(),
card_number: "4111111111111111".to_string(),
card_exp_year: "2099".to_string(),
card_exp_month: "12".to_string(),
card_cvc,
payment_method_id,
customer_id: customer_id.map(ToOwned::to_owned),
name_on_card: None,
nickname: None,
enc_card_data: None,
};
locker_mock_up = match payload {
payment_methods::StoreLockerReq::LockerCard(store_card_req) => storage::LockerMockUpNew {
merchant_id: store_card_req.merchant_id.to_owned(),
card_number: store_card_req.card.card_number.peek().to_string(),
card_exp_year: store_card_req.card.card_exp_year.peek().to_string(),
card_exp_month: store_card_req.card.card_exp_month.peek().to_string(),
name_on_card: store_card_req.card.name_on_card.to_owned().expose_option(),
nickname: store_card_req.card.nick_name.to_owned(),
..locker_mock_up
},
payment_methods::StoreLockerReq::LockerGeneric(store_generic_req) => {
storage::LockerMockUpNew {
merchant_id: store_generic_req.merchant_id.to_owned(),
enc_card_data: Some(store_generic_req.enc_data.to_owned()),
..locker_mock_up
}
}
};
let response = db
.insert_locker_mock_up(locker_mock_up)
.await
.change_context(errors::VaultError::SaveCardFailed)?;
let payload = payment_methods::StoreCardRespPayload {
card_reference: response.card_id,
duplication_check: None,
};
Ok(payment_methods::StoreCardResp {
status: "Ok".to_string(),
error_code: None,
error_message: None,
payload: Some(payload),
})
}
#[instrument(skip_all)]
pub async fn mock_get_card<'a>(
db: &dyn db::StorageInterface,
card_id: &'a str,
) -> errors::CustomResult<(payment_methods::GetCardResponse, Option<String>), errors::VaultError> {
let locker_mock_up = db
.find_locker_by_card_id(card_id)
.await
.change_context(errors::VaultError::FetchCardFailed)?;
let add_card_response = payment_methods::AddCardResponse {
card_id: locker_mock_up
.payment_method_id
.unwrap_or(locker_mock_up.card_id),
external_id: locker_mock_up.external_id,
card_fingerprint: locker_mock_up.card_fingerprint.into(),
card_global_fingerprint: locker_mock_up.card_global_fingerprint.into(),
merchant_id: Some(locker_mock_up.merchant_id),
card_number: cards::CardNumber::try_from(locker_mock_up.card_number)
.change_context(errors::VaultError::ResponseDeserializationFailed)
.attach_printable("Invalid card number format from the mock locker")
.map(Some)?,
card_exp_year: Some(locker_mock_up.card_exp_year.into()),
card_exp_month: Some(locker_mock_up.card_exp_month.into()),
name_on_card: locker_mock_up.name_on_card.map(|card| card.into()),
nickname: locker_mock_up.nickname,
customer_id: locker_mock_up.customer_id,
duplicate: locker_mock_up.duplicate,
};
Ok((
payment_methods::GetCardResponse {
card: add_card_response,
},
locker_mock_up.card_cvc,
))
}
#[instrument(skip_all)]
pub async fn mock_get_payment_method<'a>(
state: &routes::SessionState,
key_store: &domain::MerchantKeyStore,
card_id: &'a str,
) -> errors::CustomResult<payment_methods::GetPaymentMethodResponse, errors::VaultError> {
let db = &*state.store;
let locker_mock_up = db
.find_locker_by_card_id(card_id)
.await
.change_context(errors::VaultError::FetchPaymentMethodFailed)?;
let dec_data = if let Some(e) = locker_mock_up.enc_card_data {
decode_and_decrypt_locker_data(state, key_store, e).await
} else {
Err(report!(errors::VaultError::FetchPaymentMethodFailed))
}?;
let payment_method_response = payment_methods::AddPaymentMethodResponse {
payment_method_id: locker_mock_up
.payment_method_id
.unwrap_or(locker_mock_up.card_id),
external_id: locker_mock_up.external_id,
merchant_id: Some(locker_mock_up.merchant_id.to_owned()),
nickname: locker_mock_up.nickname,
customer_id: locker_mock_up.customer_id,
duplicate: locker_mock_up.duplicate,
payment_method_data: dec_data,
};
Ok(payment_methods::GetPaymentMethodResponse {
payment_method: payment_method_response,
})
}
#[instrument(skip_all)]
pub async fn mock_delete_card_hs<'a>(
db: &dyn db::StorageInterface,
card_id: &'a str,
) -> errors::CustomResult<payment_methods::DeleteCardResp, errors::VaultError> {
db.delete_locker_mock_up(card_id)
.await
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(payment_methods::DeleteCardResp {
status: "Ok".to_string(),
error_code: None,
error_message: None,
})
}
#[instrument(skip_all)]
pub async fn mock_delete_card<'a>(
db: &dyn db::StorageInterface,
card_id: &'a str,
) -> errors::CustomResult<payment_methods::DeleteCardResponse, errors::VaultError> {
let locker_mock_up = db
.delete_locker_mock_up(card_id)
.await
.change_context(errors::VaultError::FetchCardFailed)?;
Ok(payment_methods::DeleteCardResponse {
card_id: Some(locker_mock_up.card_id),
external_id: Some(locker_mock_up.external_id),
card_isin: None,
status: "Ok".to_string(),
})
}
//------------------------------------------------------------------------------
pub fn get_banks(
state: &routes::SessionState,
pm_type: common_enums::enums::PaymentMethodType,
connectors: Vec<String>,
) -> Result<Vec<BankCodeResponse>, errors::ApiErrorResponse> {
let mut bank_names_hm: HashMap<String, HashSet<common_enums::enums::BankNames>> =
HashMap::new();
if matches!(
pm_type,
api_enums::PaymentMethodType::Giropay | api_enums::PaymentMethodType::Sofort
) {
Ok(vec![BankCodeResponse {
bank_name: vec![],
eligible_connectors: connectors,
}])
} else {
let mut bank_code_responses = vec![];
for connector in &connectors {
if let Some(connector_bank_names) = state.conf.bank_config.0.get(&pm_type) {
if let Some(connector_hash_set) = connector_bank_names.0.get(connector) {
bank_names_hm.insert(connector.clone(), connector_hash_set.banks.clone());
} else {
logger::error!("Could not find any configured connectors for payment_method -> {pm_type} for connector -> {connector}");
}
} else {
logger::error!("Could not find any configured banks for payment_method -> {pm_type} for connector -> {connector}");
}
}
let vector_of_hashsets = bank_names_hm
.values()
.map(|bank_names_hashset| bank_names_hashset.to_owned())
.collect::<Vec<_>>();
let mut common_bank_names = HashSet::new();
if let Some(first_element) = vector_of_hashsets.first() {
common_bank_names = vector_of_hashsets
.iter()
.skip(1)
.fold(first_element.to_owned(), |acc, hs| {
acc.intersection(hs).copied().collect()
});
}
if !common_bank_names.is_empty() {
bank_code_responses.push(BankCodeResponse {
bank_name: common_bank_names.clone().into_iter().collect(),
eligible_connectors: connectors.clone(),
});
}
for connector in connectors {
if let Some(all_bank_codes_for_connector) = bank_names_hm.get(&connector) {
let remaining_bank_codes: HashSet<_> = all_bank_codes_for_connector
.difference(&common_bank_names)
.collect();
if !remaining_bank_codes.is_empty() {
bank_code_responses.push(BankCodeResponse {
bank_name: remaining_bank_codes
.into_iter()
.map(|ele| ele.to_owned())
.collect(),
eligible_connectors: vec![connector],
})
}
} else {
logger::error!("Could not find any configured banks for payment_method -> {pm_type} for connector -> {connector}");
}
}
Ok(bank_code_responses)
}
}
fn get_val(str: String, val: &serde_json::Value) -> Option<String> {
str.split('.')
.try_fold(val, |acc, x| acc.get(x))
.and_then(|v| v.as_str())
.map(|s| s.to_string())
}
#[cfg(feature = "v1")]
pub async fn list_payment_methods(
state: routes::SessionState,
merchant_context: domain::MerchantContext,
mut req: api::PaymentMethodListRequest,
) -> errors::RouterResponse<api::PaymentMethodListResponse> {
let db = &*state.store;
let pm_config_mapping = &state.conf.pm_filters;
let key_manager_state = &(&state).into();
let payment_intent = if let Some(cs) = &req.client_secret {
if cs.starts_with("pm_") {
validate_payment_method_and_client_secret(&state, cs, db, &merchant_context).await?;
None
} else {
helpers::verify_payment_intent_time_and_client_secret(
&state,
&merchant_context,
req.client_secret.clone(),
)
.await?
}
} else {
None
};
let shipping_address = payment_intent
.as_ref()
.async_map(|pi| async {
helpers::get_address_by_id(
&state,
pi.shipping_address_id.clone(),
merchant_context.get_merchant_key_store(),
&pi.payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
})
.await
.transpose()?
.flatten();
let billing_address = payment_intent
.as_ref()
.async_map(|pi| async {
helpers::get_address_by_id(
&state,
pi.billing_address_id.clone(),
merchant_context.get_merchant_key_store(),
&pi.payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
})
.await
.transpose()?
.flatten();
let customer = payment_intent
.as_ref()
.async_and_then(|pi| async {
pi.customer_id
.as_ref()
.async_and_then(|cust| async {
db.find_customer_by_customer_id_merchant_id(
key_manager_state,
cust,
&pi.merchant_id,
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::CustomerNotFound)
.ok()
})
.await
})
.await;
let payment_attempt = payment_intent
.as_ref()
.async_map(|pi| async {
db.find_payment_attempt_by_payment_id_merchant_id_attempt_id(
&pi.payment_id,
&pi.merchant_id,
&pi.active_attempt.get_id(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)
})
.await
.transpose()?;
let setup_future_usage = payment_intent.as_ref().and_then(|pi| pi.setup_future_usage);
let is_cit_transaction = payment_attempt
.as_ref()
.map(|pa| pa.mandate_details.is_some())
.unwrap_or(false)
|| setup_future_usage
.map(|future_usage| future_usage == common_enums::FutureUsage::OffSession)
.unwrap_or(false);
let payment_type = payment_attempt.as_ref().map(|pa| {
let amount = api::Amount::from(pa.net_amount.get_order_amount());
let mandate_type = if pa.mandate_id.is_some() {
Some(api::MandateTransactionType::RecurringMandateTransaction)
} else if is_cit_transaction {
Some(api::MandateTransactionType::NewMandateTransaction)
} else {
None
};
helpers::infer_payment_type(amount, mandate_type.as_ref())
});
let all_mcas = db
.find_merchant_connector_account_by_merchant_id_and_disabled_list(
key_manager_state,
merchant_context.get_merchant_account().get_id(),
false,
merchant_context.get_merchant_key_store(),
)
.await
.to_not_found_response(errors::ApiErrorResponse::MerchantAccountNotFound)?;
let profile_id = payment_intent
.as_ref()
.and_then(|payment_intent| payment_intent.profile_id.as_ref())
.get_required_value("profile_id")
.change_context(errors::ApiErrorResponse::GenericNotFoundError {
message: "Profile id not found".to_string(),
})?;
let business_profile = db
.find_business_profile_by_profile_id(
key_manager_state,
merchant_context.get_merchant_key_store(),
profile_id,
)
.await
.to_not_found_response(errors::ApiErrorResponse::ProfileNotFound {
id: profile_id.get_string_repr().to_owned(),
})?;
// filter out payment connectors based on profile_id
let filtered_mcas = all_mcas
.clone()
.filter_based_on_profile_and_connector_type(profile_id, ConnectorType::PaymentProcessor);
logger::debug!(mca_before_filtering=?filtered_mcas);
let mut response: Vec<ResponsePaymentMethodIntermediate> = vec![];
// Key creation for storing PM_FILTER_CGRAPH
let key = {
format!(
"pm_filters_cgraph_{}_{}",
merchant_context
.get_merchant_account()
.get_id()
.get_string_repr(),
profile_id.get_string_repr()
)
};
if let Some(graph) = get_merchant_pm_filter_graph(&state, &key).await {
// Derivation of PM_FILTER_CGRAPH from MokaCache successful
for mca in &filtered_mcas {
let payment_methods = match &mca.payment_methods_enabled {
Some(pm) => pm,
None => continue,
};
filter_payment_methods(
&graph,
mca.get_id(),
payment_methods,
&mut req,
&mut response,
payment_intent.as_ref(),
payment_attempt.as_ref(),
billing_address.as_ref(),
mca.connector_name.clone(),
&state.conf,
)
.await?;
}
} else {
// No PM_FILTER_CGRAPH Cache present in MokaCache
let mut builder = cgraph::ConstraintGraphBuilder::new();
for mca in &filtered_mcas {
let domain_id = builder.make_domain(
mca.get_id().get_string_repr().to_string(),
mca.connector_name.as_str(),
);
let Ok(domain_id) = domain_id else {
logger::error!("Failed to construct domain for list payment methods");
return Err(errors::ApiErrorResponse::InternalServerError.into());
};
let payment_methods = match &mca.payment_methods_enabled {
Some(pm) => pm,
None => continue,
};
if let Err(e) = make_pm_graph(
&mut builder,
domain_id,
payment_methods,
mca.connector_name.clone(),
pm_config_mapping,
&state.conf.mandates.supported_payment_methods,
&state.conf.mandates.update_mandate_supported,
) {
logger::error!(
"Failed to construct constraint graph for list payment methods {e:?}"
);
}
}
// Refreshing our CGraph cache
let graph = refresh_pm_filters_cache(&state, &key, builder.build()).await;
for mca in &filtered_mcas {
let payment_methods = match &mca.payment_methods_enabled {
Some(pm) => pm,
None => continue,
};
filter_payment_methods(
&graph,
mca.get_id().clone(),
payment_methods,
&mut req,
&mut response,
payment_intent.as_ref(),
payment_attempt.as_ref(),
billing_address.as_ref(),
mca.connector_name.clone(),
&state.conf,
)
.await?;
}
}
logger::info!(
"The Payment Methods available after Constraint Graph filtering are {:?}",
response
);
let mut pmt_to_auth_connector: HashMap<
enums::PaymentMethod,
HashMap<enums::PaymentMethodType, String>,
> = HashMap::new();
if let Some((payment_attempt, payment_intent)) =
payment_attempt.as_ref().zip(payment_intent.as_ref())
{
let routing_enabled_pms = &router_consts::ROUTING_ENABLED_PAYMENT_METHODS;
let routing_enabled_pm_types = &router_consts::ROUTING_ENABLED_PAYMENT_METHOD_TYPES;
let mut chosen = api::SessionConnectorDatas::new(Vec::new());
for intermediate in &response {
if routing_enabled_pm_types.contains(&intermediate.payment_method_type)
|| routing_enabled_pms.contains(&intermediate.payment_method)
{
let connector_data = api::ConnectorData::get_connector_by_name(
&state.clone().conf.connectors,
&intermediate.connector,
api::GetToken::from(intermediate.payment_method_type),
None,
)
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("invalid connector name received")?;
chosen.push(api::SessionConnectorData {
payment_method_sub_type: intermediate.payment_method_type,
payment_method_type: intermediate.payment_method,
connector: connector_data,
business_sub_label: None,
});
}
}
let sfr = SessionFlowRoutingInput {
state: &state,
country: billing_address.clone().and_then(|ad| ad.country),
key_store: merchant_context.get_merchant_key_store(),
merchant_account: merchant_context.get_merchant_account(),
payment_attempt,
payment_intent,
chosen,
};
let (result, routing_approach) = routing::perform_session_flow_routing(
sfr,
&business_profile,
&enums::TransactionType::Payment,
)
.await
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("error performing session flow routing")?;
response.retain(|intermediate| {
if !routing_enabled_pm_types.contains(&intermediate.payment_method_type)
&& !routing_enabled_pms.contains(&intermediate.payment_method)
{
return true;
}
if let Some(choice) = result.get(&intermediate.payment_method_type) {
if let Some(first_routable_connector) = choice.first() {
intermediate.connector
== first_routable_connector
.connector
.connector_name
.to_string()
&& first_routable_connector
.connector
.merchant_connector_id
.as_ref()
.map(|merchant_connector_id| {
*merchant_connector_id.get_string_repr()
== intermediate.merchant_connector_id
})
.unwrap_or_default()
} else {
false
}
} else {
false
}
});
let mut routing_info: storage::PaymentRoutingInfo = payment_attempt
.straight_through_algorithm
.clone()
.map(|val| val.parse_value("PaymentRoutingInfo"))
.transpose()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Invalid PaymentRoutingInfo format found in payment attempt")?
.unwrap_or(storage::PaymentRoutingInfo {
algorithm: None,
pre_routing_results: None,
});
let mut pre_routing_results: HashMap<
api_enums::PaymentMethodType,
storage::PreRoutingConnectorChoice,
> = HashMap::new();
for (pm_type, routing_choice) in result {
let mut routable_choice_list = vec![];
for choice in routing_choice {
let routable_choice = routing_types::RoutableConnectorChoice {
choice_kind: routing_types::RoutableChoiceKind::FullStruct,
connector: choice
.connector
.connector_name
.to_string()
.parse::<api_enums::RoutableConnectors>()
.change_context(errors::ApiErrorResponse::InternalServerError)?,
merchant_connector_id: choice.connector.merchant_connector_id.clone(),
};
routable_choice_list.push(routable_choice);
}
pre_routing_results.insert(
pm_type,
storage::PreRoutingConnectorChoice::Multiple(routable_choice_list),
);
}
let redis_conn = db
.get_redis_conn()
.map_err(|redis_error| logger::error!(?redis_error))
.ok();
let mut val = Vec::new();
for (payment_method_type, routable_connector_choice) in &pre_routing_results {
let routable_connector_list = match routable_connector_choice {
storage::PreRoutingConnectorChoice::Single(routable_connector) => {
vec![routable_connector.clone()]
}
storage::PreRoutingConnectorChoice::Multiple(routable_connector_list) => {
routable_connector_list.clone()
}
};
let first_routable_connector = routable_connector_list
.first()
.ok_or(errors::ApiErrorResponse::IncorrectPaymentMethodConfiguration)?;
let matched_mca = filtered_mcas.iter().find(|m| {
first_routable_connector.merchant_connector_id.as_ref() == Some(&m.get_id())
});
if let Some(m) = matched_mca {
let pm_auth_config = m
.pm_auth_config
.as_ref()
.map(|config| {
serde_json::from_value::<PaymentMethodAuthConfig>(config.clone().expose())
.change_context(errors::StorageError::DeserializationFailed)
.attach_printable("Failed to deserialize Payment Method Auth config")
})
.transpose()
.unwrap_or_else(|error| {
logger::error!(?error);
None
});
if let Some(config) = pm_auth_config {
for inner_config in config.enabled_payment_methods.iter() {
let is_active_mca = all_mcas
.iter()
.any(|mca| mca.get_id() == inner_config.mca_id);
if inner_config.payment_method_type == *payment_method_type && is_active_mca
{
let pm = pmt_to_auth_connector
.get(&inner_config.payment_method)
.cloned();
let inner_map = if let Some(mut inner_map) = pm {
inner_map.insert(
*payment_method_type,
inner_config.connector_name.clone(),
);
inner_map
} else {
HashMap::from([(
*payment_method_type,
inner_config.connector_name.clone(),
)])
};
pmt_to_auth_connector.insert(inner_config.payment_method, inner_map);
val.push(inner_config.clone());
}
}
};
}
}
let pm_auth_key = payment_intent.payment_id.get_pm_auth_key();
let redis_expiry = state.conf.payment_method_auth.get_inner().redis_expiry;
if let Some(rc) = redis_conn {
rc.serialize_and_set_key_with_expiry(&pm_auth_key.as_str().into(), val, redis_expiry)
.await
.attach_printable("Failed to store pm auth data in redis")
.unwrap_or_else(|error| {
logger::error!(?error);
})
};
routing_info.pre_routing_results = Some(pre_routing_results);
let encoded = routing_info
.encode_to_value()
.change_context(errors::ApiErrorResponse::InternalServerError)
.attach_printable("Unable to serialize payment routing info to value")?;
let attempt_update = storage::PaymentAttemptUpdate::UpdateTrackers {
payment_token: None,
connector: None,
straight_through_algorithm: Some(encoded),
amount_capturable: None,
updated_by: merchant_context
.get_merchant_account()
.storage_scheme
.to_string(),
merchant_connector_id: None,
surcharge_amount: None,
tax_amount: None,
routing_approach,
};
state
.store
.update_payment_attempt_with_attempt_id(
payment_attempt.clone(),
attempt_update,
merchant_context.get_merchant_account().storage_scheme,
)
.await
.to_not_found_response(errors::ApiErrorResponse::PaymentNotFound)?;
}
// Check for `use_billing_as_payment_method_billing` config under business_profile
// If this is disabled, then the billing details in required fields will be empty and have to be collected by the customer
let billing_address_for_calculating_required_fields = business_profile
.use_billing_as_payment_method_billing
.unwrap_or(true)
.then_some(billing_address.as_ref())
.flatten();
let req = api_models::payments::PaymentsRequest::foreign_try_from((
payment_attempt.as_ref(),
payment_intent.as_ref(),
shipping_address.as_ref(),
billing_address_for_calculating_required_fields,
customer.as_ref(),
))?;
let req_val = serde_json::to_value(req).ok();
logger::debug!(filtered_payment_methods=?response);
let mut payment_experiences_consolidated_hm: HashMap<
api_enums::PaymentMethod,
HashMap<api_enums::PaymentMethodType, HashMap<api_enums::PaymentExperience, Vec<String>>>,
> = HashMap::new();
let mut card_networks_consolidated_hm: HashMap<
api_enums::PaymentMethod,
HashMap<api_enums::PaymentMethodType, HashMap<api_enums::CardNetwork, Vec<String>>>,
> = HashMap::new();
let mut banks_consolidated_hm: HashMap<api_enums::PaymentMethodType, Vec<String>> =
HashMap::new();
let mut bank_debits_consolidated_hm =
HashMap::<api_enums::PaymentMethodType, Vec<String>>::new();
let mut bank_transfer_consolidated_hm =
HashMap::<api_enums::PaymentMethodType, Vec<String>>::new();
// All the required fields will be stored here and later filtered out based on business profile config
let mut required_fields_hm = HashMap::<
api_enums::PaymentMethod,
HashMap<api_enums::PaymentMethodType, HashMap<String, RequiredFieldInfo>>,
>::new();
for element in response.clone() {
let payment_method = element.payment_method;
let payment_method_type = element.payment_method_type;
let connector = element.connector.clone();
let connector_variant = api_enums::Connector::from_str(connector.as_str())
.change_context(errors::ConnectorError::InvalidConnectorName)
.change_context(errors::ApiErrorResponse::InvalidDataValue {
field_name: "connector",
})
.attach_printable_lazy(|| format!("unable to parse connector name {connector:?}"))?;
state.conf.required_fields.0.get(&payment_method).map(
|required_fields_hm_for_each_payment_method_type| {
required_fields_hm_for_each_payment_method_type
.0
.get(&payment_method_type)
.map(|required_fields_hm_for_each_connector| {
required_fields_hm.entry(payment_method).or_default();
required_fields_hm_for_each_connector
.fields
.get(&connector_variant)
.map(|required_fields_final| {
let mut required_fields_hs = required_fields_final.common.clone();
if is_cit_transaction {
required_fields_hs
.extend(required_fields_final.mandate.clone());
} else {
required_fields_hs
.extend(required_fields_final.non_mandate.clone());
}
required_fields_hs = should_collect_shipping_or_billing_details_from_wallet_connector(
payment_method,
element.payment_experience.as_ref(),
&business_profile,
required_fields_hs.clone(),
);
// get the config, check the enums while adding
{
for (key, val) in &mut required_fields_hs {
let temp = req_val
|
crates/router/src/core/payment_methods/cards.rs#chunk2
|
router
|
chunk
| 8,189
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl api::Payment for Airwallex {}
|
crates/hyperswitch_connectors/src/connectors/airwallex.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Airwallex
|
api::Payment for
|
impl api::Payment for for Airwallex
| null | null | null | null | null | null | null | null |
File: crates/scheduler/src/lib.rs
pub mod configs;
pub mod consumer;
pub mod db;
pub mod env;
pub mod errors;
pub mod flow;
pub mod metrics;
pub mod producer;
pub mod scheduler;
pub mod settings;
pub mod utils;
pub use self::{consumer::types, flow::*, scheduler::*};
|
crates/scheduler/src/lib.rs
|
scheduler
|
full_file
| 67
| null | null | null | null | null | null | null | null | null | null | null | null | null |
impl<V: ValueNode> Node<V> {
pub(crate) fn new(node_type: NodeType<V>) -> Self {
Self {
node_type,
preds: Vec::new(),
succs: Vec::new(),
}
}
}
|
crates/hyperswitch_constraint_graph/src/types.rs
|
hyperswitch_constraint_graph
|
impl_block
| 52
|
rust
| null |
Node
| null |
impl Node
| null | null | null | null | null | null | null | null |
pub async fn get_profile_id_for_mandate(
state: &SessionState,
merchant_context: &domain::MerchantContext,
mandate: Mandate,
) -> CustomResult<common_utils::id_type::ProfileId, errors::ApiErrorResponse> {
let profile_id = if let Some(ref payment_id) = mandate.original_payment_id {
let pi = state
.store
.find_payment_intent_by_payment_id_merchant_id(
&state.into(),
payment_id,
merchant_context.get_merchant_account().get_id(),
merchant_context.get_merchant_key_store(),
merchant_context.get_merchant_account().storage_scheme,
)
.await
.change_context(errors::ApiErrorResponse::PaymentNotFound)?;
let profile_id =
pi.profile_id
.clone()
.ok_or(errors::ApiErrorResponse::ProfileNotFound {
id: pi
.profile_id
.map(|profile_id| profile_id.get_string_repr().to_owned())
.unwrap_or_else(|| "Profile id is Null".to_string()),
})?;
Ok(profile_id)
} else {
Err(errors::ApiErrorResponse::PaymentNotFound)
}?;
Ok(profile_id)
}
|
crates/router/src/core/mandate/helpers.rs
|
router
|
function_signature
| 250
|
rust
| null | null | null | null |
get_profile_id_for_mandate
| null | null | null | null | null | null | null |
pub struct Configs;
|
crates/router/src/routes/app.rs
|
router
|
struct_definition
| 5
|
rust
|
Configs
| null | null | null | null | null | null | null | null | null | null | null |
impl api::PaymentVoid for Chargebee {}
|
crates/hyperswitch_connectors/src/connectors/chargebee.rs
|
hyperswitch_connectors
|
impl_block
| 9
|
rust
| null |
Chargebee
|
api::PaymentVoid for
|
impl api::PaymentVoid for for Chargebee
| null | null | null | null | null | null | null | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.