repo
stringclasses
4 values
file_path
stringlengths
6
193
extension
stringclasses
23 values
content
stringlengths
0
1.73M
token_count
int64
0
724k
__index_level_0__
int64
0
10.8k
hyperswitch
crates/analytics/src/sdk_events/metrics/payment_attempts.rs
.rs
use std::collections::HashSet; use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, }, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::SdkEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct PaymentAttempts; #[async_trait::async_trait] impl<T> super::SdkEventMetric<T> for PaymentAttempts where T: AnalyticsDataSource + super::SdkEventMetricAnalytics, 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: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); let dimensions = dimensions.to_vec(); 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()?; if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; } filters.set_filter_clause(&mut query_builder).switch()?; query_builder .add_filter_clause("merchant_id", publishable_key) .switch()?; query_builder .add_bool_filter_clause("first_event", 1) .switch()?; query_builder .add_filter_clause("event_name", SdkEventNames::PaymentAttempt) .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.as_ref() { query_builder .add_group_by_clause("time_bucket") .attach_printable("Error adding granularity") .switch()?; } query_builder .execute_query::<SdkEventMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( SdkEventMetricsBucketIdentifier::new( i.payment_method.clone(), i.platform.clone(), i.browser_name.clone(), i.source.clone(), i.component.clone(), i.payment_experience.clone(), i.time_bucket.clone(), ), i, )) }) .collect::<error_stack::Result< HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
777
1,906
hyperswitch
crates/analytics/src/sdk_events/metrics/load_time.rs
.rs
use std::collections::HashSet; use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, }, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::SdkEventMetricRow; use crate::{ query::{Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct LoadTime; #[async_trait::async_trait] impl<T> super::SdkEventMetric<T> for LoadTime where T: AnalyticsDataSource + super::SdkEventMetricAnalytics, 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: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); let dimensions = dimensions.to_vec(); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Percentile { field: "latency", alias: Some("count"), percentile: Some(&50), }) .switch()?; if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; } filters.set_filter_clause(&mut query_builder).switch()?; query_builder .add_filter_clause("merchant_id", publishable_key) .switch()?; query_builder .add_bool_filter_clause("first_event", 1) .switch()?; query_builder .add_filter_clause("event_name", SdkEventNames::AppRendered) .switch()?; query_builder .add_custom_filter_clause("latency", 0, FilterTypes::Gt) .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.as_ref() { query_builder .add_group_by_clause("time_bucket") .attach_printable("Error adding granularity") .switch()?; } query_builder .execute_query::<SdkEventMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( SdkEventMetricsBucketIdentifier::new( i.payment_method.clone(), i.platform.clone(), i.browser_name.clone(), i.source.clone(), i.component.clone(), i.payment_experience.clone(), i.time_bucket.clone(), ), i, )) }) .collect::<error_stack::Result< HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
820
1,907
hyperswitch
crates/analytics/src/sdk_events/metrics/payment_methods_call_count.rs
.rs
use std::collections::HashSet; use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, }, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::SdkEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct PaymentMethodsCallCount; #[async_trait::async_trait] impl<T> super::SdkEventMetric<T> for PaymentMethodsCallCount where T: AnalyticsDataSource + super::SdkEventMetricAnalytics, 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: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); let dimensions = dimensions.to_vec(); 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()?; if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; } filters.set_filter_clause(&mut query_builder).switch()?; query_builder .add_filter_clause("merchant_id", publishable_key) .switch()?; query_builder .add_bool_filter_clause("first_event", 1) .switch()?; query_builder .add_filter_clause("event_name", SdkEventNames::PaymentMethodsCall) .switch()?; query_builder .add_filter_clause("log_type", "INFO") .switch()?; query_builder .add_filter_clause("category", "API") .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.as_ref() { query_builder .add_group_by_clause("time_bucket") .attach_printable("Error adding granularity") .switch()?; } query_builder .execute_query::<SdkEventMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( SdkEventMetricsBucketIdentifier::new( i.payment_method.clone(), i.platform.clone(), i.browser_name.clone(), i.source.clone(), i.component.clone(), i.payment_experience.clone(), i.time_bucket.clone(), ), i, )) }) .collect::<error_stack::Result< HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
823
1,908
hyperswitch
crates/analytics/src/sdk_events/metrics/payment_data_filled_count.rs
.rs
use std::collections::HashSet; use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, }, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::SdkEventMetricRow; use crate::{ query::{Aggregate, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct PaymentDataFilledCount; #[async_trait::async_trait] impl<T> super::SdkEventMetric<T> for PaymentDataFilledCount where T: AnalyticsDataSource + super::SdkEventMetricAnalytics, 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: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); let dimensions = dimensions.to_vec(); 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()?; if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; } filters.set_filter_clause(&mut query_builder).switch()?; query_builder .add_filter_clause("merchant_id", publishable_key) .switch()?; query_builder .add_bool_filter_clause("first_event", 1) .switch()?; query_builder .add_filter_clause("event_name", SdkEventNames::PaymentDataFilled) .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.as_ref() { query_builder .add_group_by_clause("time_bucket") .attach_printable("Error adding granularity") .switch()?; } query_builder .execute_query::<SdkEventMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( SdkEventMetricsBucketIdentifier::new( i.payment_method.clone(), i.platform.clone(), i.browser_name.clone(), i.source.clone(), i.component.clone(), i.payment_experience.clone(), i.time_bucket.clone(), ), i, )) }) .collect::<error_stack::Result< HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
782
1,909
hyperswitch
crates/analytics/src/sdk_events/metrics/average_payment_time.rs
.rs
use std::collections::HashSet; use api_models::analytics::{ sdk_events::{ SdkEventDimensions, SdkEventFilters, SdkEventMetricsBucketIdentifier, SdkEventNames, }, Granularity, TimeRange, }; use common_utils::errors::ReportSwitchExt; use error_stack::ResultExt; use time::PrimitiveDateTime; use super::SdkEventMetricRow; use crate::{ query::{Aggregate, FilterTypes, GroupByClause, QueryBuilder, QueryFilter, ToSql, Window}, types::{AnalyticsCollection, AnalyticsDataSource, MetricsError, MetricsResult}, }; #[derive(Default)] pub(super) struct AveragePaymentTime; #[async_trait::async_trait] impl<T> super::SdkEventMetric<T> for AveragePaymentTime where T: AnalyticsDataSource + super::SdkEventMetricAnalytics, 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: &[SdkEventDimensions], publishable_key: &str, filters: &SdkEventFilters, granularity: Option<Granularity>, time_range: &TimeRange, pool: &T, ) -> MetricsResult<HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>> { let mut query_builder: QueryBuilder<T> = QueryBuilder::new(AnalyticsCollection::SdkEventsAnalytics); let dimensions = dimensions.to_vec(); for dim in dimensions.iter() { query_builder.add_select_column(dim).switch()?; } query_builder .add_select_column(Aggregate::Percentile { field: "latency", alias: Some("count"), percentile: Some(&50), }) .switch()?; if let Some(granularity) = granularity { query_builder .add_granularity_in_mins(granularity) .switch()?; } filters.set_filter_clause(&mut query_builder).switch()?; query_builder .add_filter_clause("merchant_id", publishable_key) .switch()?; query_builder .add_bool_filter_clause("first_event", 1) .switch()?; query_builder .add_filter_clause("event_name", SdkEventNames::PaymentAttempt) .switch()?; query_builder .add_custom_filter_clause("latency", 0, FilterTypes::Gt) .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.as_ref() { query_builder .add_group_by_clause("time_bucket") .attach_printable("Error adding granularity") .switch()?; } query_builder .execute_query::<SdkEventMetricRow, _>(pool) .await .change_context(MetricsError::QueryBuildingError)? .change_context(MetricsError::QueryExecutionFailure)? .into_iter() .map(|i| { Ok(( SdkEventMetricsBucketIdentifier::new( i.payment_method.clone(), i.platform.clone(), i.browser_name.clone(), i.source.clone(), i.component.clone(), i.payment_experience.clone(), i.time_bucket.clone(), ), i, )) }) .collect::<error_stack::Result< HashSet<(SdkEventMetricsBucketIdentifier, SdkEventMetricRow)>, crate::query::PostProcessingError, >>() .change_context(MetricsError::PostProcessingFailure) } }
821
1,910
hyperswitch
crates/analytics/src/metrics/request.rs
.rs
use std::time; #[inline] pub async fn record_operation_time<F, R, T>( future: F, metric: &once_cell::sync::Lazy<router_env::opentelemetry::metrics::Histogram<f64>>, metric_name: &T, source: &crate::AnalyticsProvider, ) -> R where F: futures::Future<Output = R>, T: ToString, { let (result, time) = time_future(future).await; let attributes = router_env::metric_attributes!( ("metric_name", metric_name.to_string()), ("source", source.to_string()), ); let value = time.as_secs_f64(); metric.record(value, attributes); router_env::logger::debug!("Attributes: {:?}, Time: {}", attributes, value); result } #[inline] pub async fn time_future<F, R>(future: F) -> (R, time::Duration) where F: futures::Future<Output = R>, { let start = time::Instant::now(); let result = future.await; let time_spent = start.elapsed(); (result, time_spent) }
249
1,911
hyperswitch
crates/euclid_macros/Cargo.toml
.toml
[package] name = "euclid_macros" description = "Macros for Euclid DSL" version = "0.1.0" edition.workspace = true rust-version.workspace = true license.workspace = true [lib] proc-macro = true [dependencies] proc-macro2 = "1.0.79" quote = "1.0.35" rustc-hash = "1.1.0" strum = { version = "0.26", features = ["derive"] } syn = "2.0.57" [lints] workspace = true
127
1,912
hyperswitch
crates/euclid_macros/src/lib.rs
.rs
mod inner; use proc_macro::TokenStream; #[proc_macro_derive(EnumNums)] pub fn enum_nums(ts: TokenStream) -> TokenStream { inner::enum_nums_inner(ts) } #[proc_macro] pub fn knowledge(ts: TokenStream) -> TokenStream { match inner::knowledge_inner(ts.into()) { Ok(ts) => ts.into(), Err(e) => e.into_compile_error().into(), } }
90
1,913
hyperswitch
crates/euclid_macros/src/inner.rs
.rs
mod enum_nums; mod knowledge; pub(crate) use enum_nums::enum_nums_inner; pub(crate) use knowledge::knowledge_inner;
27
1,914
hyperswitch
crates/euclid_macros/src/inner/knowledge.rs
.rs
use std::{ fmt::{Display, Formatter}, hash::Hash, rc::Rc, }; use proc_macro2::{Span, TokenStream}; use quote::{format_ident, quote}; use rustc_hash::{FxHashMap, FxHashSet}; use syn::{parse::Parse, Token}; mod strength { syn::custom_punctuation!(Normal, ->); syn::custom_punctuation!(Strong, ->>); } mod kw { syn::custom_keyword!(any); syn::custom_keyword!(not); } #[derive(Clone, PartialEq, Eq, Hash)] enum Comparison { LessThan, Equal, GreaterThan, GreaterThanEqual, LessThanEqual, } impl Display for Comparison { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { let symbol = match self { Self::LessThan => "< ", Self::Equal => return Ok(()), Self::GreaterThanEqual => ">= ", Self::LessThanEqual => "<= ", Self::GreaterThan => "> ", }; write!(f, "{}", symbol) } } impl Parse for Comparison { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { if input.peek(Token![>]) { input.parse::<Token![>]>()?; Ok(Self::GreaterThan) } else if input.peek(Token![<]) { input.parse::<Token![<]>()?; Ok(Self::LessThan) } else if input.peek(Token!(<=)) { input.parse::<Token![<=]>()?; Ok(Self::LessThanEqual) } else if input.peek(Token!(>=)) { input.parse::<Token![>=]>()?; Ok(Self::GreaterThanEqual) } else { Ok(Self::Equal) } } } #[derive(Clone, PartialEq, Eq, Hash)] enum ValueType { Any, EnumVariant(String), Number { number: i64, comparison: Comparison }, } impl ValueType { fn to_string(&self, key: &str) -> String { match self { Self::Any => format!("{key}(any)"), Self::EnumVariant(s) => format!("{key}({s})"), Self::Number { number, comparison } => { format!("{}({}{})", key, comparison, number) } } } } impl Parse for ValueType { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(syn::Ident) { let ident: syn::Ident = input.parse()?; Ok(Self::EnumVariant(ident.to_string())) } else if lookahead.peek(Token![>]) || lookahead.peek(Token![<]) || lookahead.peek(syn::LitInt) { let comparison: Comparison = input.parse()?; let number: syn::LitInt = input.parse()?; let num_val = number.base10_parse::<i64>()?; Ok(Self::Number { number: num_val, comparison, }) } else { Err(lookahead.error()) } } } #[derive(Clone, PartialEq, Eq, Hash)] struct Atom { key: String, value: ValueType, } impl Display for Atom { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { write!(f, "{}", self.value.to_string(&self.key)) } } impl Parse for Atom { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let maybe_any: syn::Ident = input.parse()?; if maybe_any == "any" { let actual_key: syn::Ident = input.parse()?; Ok(Self { key: actual_key.to_string(), value: ValueType::Any, }) } else { let content; syn::parenthesized!(content in input); let value: ValueType = content.parse()?; Ok(Self { key: maybe_any.to_string(), value, }) } } } #[derive(Clone, PartialEq, Eq, Hash, strum::Display)] enum Strength { Normal, Strong, } impl Parse for Strength { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(strength::Strong) { input.parse::<strength::Strong>()?; Ok(Self::Strong) } else if lookahead.peek(strength::Normal) { input.parse::<strength::Normal>()?; Ok(Self::Normal) } else { Err(lookahead.error()) } } } #[derive(Clone, PartialEq, Eq, Hash, strum::Display)] enum Relation { Positive, Negative, } enum AtomType { Value { relation: Relation, atom: Rc<Atom>, }, InAggregator { key: String, values: Vec<String>, relation: Relation, }, } fn parse_atom_type_inner( input: syn::parse::ParseStream<'_>, key: syn::Ident, relation: Relation, ) -> syn::Result<AtomType> { let result = if input.peek(Token![in]) { input.parse::<Token![in]>()?; let bracketed; syn::bracketed!(bracketed in input); let mut values = Vec::<String>::new(); let first: syn::Ident = bracketed.parse()?; values.push(first.to_string()); while !bracketed.is_empty() { bracketed.parse::<Token![,]>()?; let next: syn::Ident = bracketed.parse()?; values.push(next.to_string()); } AtomType::InAggregator { key: key.to_string(), values, relation, } } else if input.peek(kw::any) { input.parse::<kw::any>()?; AtomType::Value { relation, atom: Rc::new(Atom { key: key.to_string(), value: ValueType::Any, }), } } else { let value: ValueType = input.parse()?; AtomType::Value { relation, atom: Rc::new(Atom { key: key.to_string(), value, }), } }; Ok(result) } impl Parse for AtomType { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let key: syn::Ident = input.parse()?; let content; syn::parenthesized!(content in input); let relation = if content.peek(kw::not) { content.parse::<kw::not>()?; Relation::Negative } else { Relation::Positive }; let result = parse_atom_type_inner(&content, key, relation)?; if !content.is_empty() { Err(content.error("Unexpected input received after atom value")) } else { Ok(result) } } } fn parse_rhs_atom(input: syn::parse::ParseStream<'_>) -> syn::Result<Atom> { let key: syn::Ident = input.parse()?; let content; syn::parenthesized!(content in input); let lookahead = content.lookahead1(); let value_type = if lookahead.peek(kw::any) { content.parse::<kw::any>()?; ValueType::Any } else if lookahead.peek(syn::Ident) { let variant = content.parse::<syn::Ident>()?; ValueType::EnumVariant(variant.to_string()) } else { return Err(lookahead.error()); }; if !content.is_empty() { Err(content.error("Unexpected input received after atom value")) } else { Ok(Atom { key: key.to_string(), value: value_type, }) } } struct Rule { lhs: Vec<AtomType>, strength: Strength, rhs: Rc<Atom>, } impl Parse for Rule { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let first_atom: AtomType = input.parse()?; let mut lhs: Vec<AtomType> = vec![first_atom]; while input.peek(Token![&]) { input.parse::<Token![&]>()?; let and_atom: AtomType = input.parse()?; lhs.push(and_atom); } let strength: Strength = input.parse()?; let rhs: Rc<Atom> = Rc::new(parse_rhs_atom(input)?); input.parse::<Token![;]>()?; Ok(Self { lhs, strength, rhs }) } } #[derive(Clone)] enum Scope { Crate, Extern, } impl Parse for Scope { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let lookahead = input.lookahead1(); if lookahead.peek(Token![crate]) { input.parse::<Token![crate]>()?; Ok(Self::Crate) } else if lookahead.peek(Token![extern]) { input.parse::<Token![extern]>()?; Ok(Self::Extern) } else { Err(lookahead.error()) } } } impl Display for Scope { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { Self::Crate => write!(f, "crate"), Self::Extern => write!(f, "euclid"), } } } #[derive(Clone)] struct Program { rules: Vec<Rc<Rule>>, } impl Parse for Program { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { let mut rules: Vec<Rc<Rule>> = Vec::new(); while !input.is_empty() { rules.push(Rc::new(input.parse::<Rule>()?)); } Ok(Self { rules }) } } struct GenContext { next_idx: usize, next_node_idx: usize, idx2atom: FxHashMap<usize, Rc<Atom>>, atom2idx: FxHashMap<Rc<Atom>, usize>, edges: FxHashMap<usize, FxHashSet<usize>>, compiled_atoms: FxHashMap<Rc<Atom>, proc_macro2::Ident>, } impl GenContext { fn new() -> Self { Self { next_idx: 1, next_node_idx: 1, idx2atom: FxHashMap::default(), atom2idx: FxHashMap::default(), edges: FxHashMap::default(), compiled_atoms: FxHashMap::default(), } } fn register_node(&mut self, atom: Rc<Atom>) -> usize { if let Some(idx) = self.atom2idx.get(&atom) { *idx } else { let this_idx = self.next_idx; self.next_idx += 1; self.idx2atom.insert(this_idx, Rc::clone(&atom)); self.atom2idx.insert(atom, this_idx); this_idx } } fn register_edge(&mut self, from: usize, to: usize) -> Result<(), String> { let node_children = self.edges.entry(from).or_default(); if node_children.contains(&to) { Err("Duplicate edge detected".to_string()) } else { node_children.insert(to); self.edges.entry(to).or_default(); Ok(()) } } fn register_rule(&mut self, rule: &Rule) -> Result<(), String> { let to_idx = self.register_node(Rc::clone(&rule.rhs)); for atom_type in &rule.lhs { if let AtomType::Value { atom, .. } = atom_type { let from_idx = self.register_node(Rc::clone(atom)); self.register_edge(from_idx, to_idx)?; } } Ok(()) } fn cycle_dfs( &self, node_id: usize, explored: &mut FxHashSet<usize>, visited: &mut FxHashSet<usize>, order: &mut Vec<usize>, ) -> Result<Option<Vec<usize>>, String> { if explored.contains(&node_id) { let position = order .iter() .position(|v| *v == node_id) .ok_or_else(|| "Error deciding cycle order".to_string())?; let cycle_order = order .get(position..) .ok_or_else(|| "Error getting cycle order".to_string())? .to_vec(); Ok(Some(cycle_order)) } else if visited.contains(&node_id) { Ok(None) } else { visited.insert(node_id); explored.insert(node_id); order.push(node_id); let dests = self .edges .get(&node_id) .ok_or_else(|| "Error getting edges of node".to_string())?; for dest in dests.iter().copied() { if let Some(cycle) = self.cycle_dfs(dest, explored, visited, order)? { return Ok(Some(cycle)); } } order.pop(); Ok(None) } } fn detect_graph_cycles(&self) -> Result<(), String> { let start_nodes = self.edges.keys().copied().collect::<Vec<usize>>(); let mut total_visited = FxHashSet::<usize>::default(); for node_id in start_nodes.iter().copied() { let mut explored = FxHashSet::<usize>::default(); let mut order = Vec::<usize>::new(); match self.cycle_dfs(node_id, &mut explored, &mut total_visited, &mut order)? { None => {} Some(order) => { let mut display_strings = Vec::<String>::with_capacity(order.len() + 1); for cycle_node_id in order { let node = self.idx2atom.get(&cycle_node_id).ok_or_else(|| { "Failed to find node during cycle display creation".to_string() })?; display_strings.push(node.to_string()); } let first = display_strings .first() .cloned() .ok_or("Unable to fill cycle display array")?; display_strings.push(first); return Err(format!("Found cycle: {}", display_strings.join(" -> "))); } } } Ok(()) } fn next_node_ident(&mut self) -> (proc_macro2::Ident, usize) { let this_idx = self.next_node_idx; self.next_node_idx += 1; (format_ident!("_node_{this_idx}"), this_idx) } fn compile_atom( &mut self, atom: &Rc<Atom>, tokens: &mut TokenStream, ) -> Result<proc_macro2::Ident, String> { let maybe_ident = self.compiled_atoms.get(atom); if let Some(ident) = maybe_ident { Ok(ident.clone()) } else { let (identifier, _) = self.next_node_ident(); let key = format_ident!("{}", &atom.key); let the_value = match &atom.value { ValueType::Any => quote! { cgraph::NodeValue::Key(DirKey::new(DirKeyKind::#key,None)) }, ValueType::EnumVariant(variant) => { let variant = format_ident!("{}", variant); quote! { cgraph::NodeValue::Value(DirValue::#key(#key::#variant)) } } ValueType::Number { number, comparison } => { let comp_type = match comparison { Comparison::Equal => quote! { None }, Comparison::LessThan => quote! { Some(NumValueRefinement::LessThan) }, Comparison::GreaterThan => quote! { Some(NumValueRefinement::GreaterThan) }, Comparison::GreaterThanEqual => quote! { Some(NumValueRefinement::GreaterThanEqual) }, Comparison::LessThanEqual => quote! { Some(NumValueRefinement::LessThanEqual) }, }; quote! { cgraph::NodeValue::Value(DirValue::#key(NumValue { number: #number, refinement: #comp_type, })) } } }; let compiled = quote! { let #identifier = graph.make_value_node(#the_value, None, None::<()>); }; tokens.extend(compiled); self.compiled_atoms .insert(Rc::clone(atom), identifier.clone()); Ok(identifier) } } fn compile_atom_type( &mut self, atom_type: &AtomType, tokens: &mut TokenStream, ) -> Result<(proc_macro2::Ident, Relation), String> { match atom_type { AtomType::Value { relation, atom } => { let node_ident = self.compile_atom(atom, tokens)?; Ok((node_ident, relation.clone())) } AtomType::InAggregator { key, values, relation, } => { let key_ident = format_ident!("{key}"); let mut values_tokens: Vec<TokenStream> = Vec::new(); for value in values { let value_ident = format_ident!("{value}"); values_tokens.push(quote! { DirValue::#key_ident(#key_ident::#value_ident) }); } let (node_ident, _) = self.next_node_ident(); let node_code = quote! { let #node_ident = graph.make_in_aggregator( Vec::from_iter([#(#values_tokens),*]), None, None::<()>, ).expect("Failed to make In aggregator"); }; tokens.extend(node_code); Ok((node_ident, relation.clone())) } } } fn compile_rule(&mut self, rule: &Rule, tokens: &mut TokenStream) -> Result<(), String> { let rhs_ident = self.compile_atom(&rule.rhs, tokens)?; let mut node_details: Vec<(proc_macro2::Ident, Relation)> = Vec::with_capacity(rule.lhs.len()); for lhs_atom_type in &rule.lhs { let details = self.compile_atom_type(lhs_atom_type, tokens)?; node_details.push(details); } if node_details.len() <= 1 { let strength = format_ident!("{}", rule.strength.to_string()); for (from_node, relation) in &node_details { let relation = format_ident!("{}", relation.to_string()); tokens.extend(quote! { graph.make_edge(#from_node, #rhs_ident, cgraph::Strength::#strength, cgraph::Relation::#relation, None::<cgraph::DomainId>) .expect("Failed to make edge"); }); } } else { let mut all_agg_nodes: Vec<TokenStream> = Vec::with_capacity(node_details.len()); for (from_node, relation) in &node_details { let relation = format_ident!("{}", relation.to_string()); all_agg_nodes.push( quote! { (#from_node, cgraph::Relation::#relation, cgraph::Strength::Strong) }, ); } let strength = format_ident!("{}", rule.strength.to_string()); let (agg_node_ident, _) = self.next_node_ident(); tokens.extend(quote! { let #agg_node_ident = graph.make_all_aggregator(&[#(#all_agg_nodes),*], None, None::<()>, None) .expect("Failed to make all aggregator node"); graph.make_edge(#agg_node_ident, #rhs_ident, cgraph::Strength::#strength, cgraph::Relation::Positive, None::<cgraph::DomainId>) .expect("Failed to create all aggregator edge"); }); } Ok(()) } fn compile(&mut self, program: Program) -> Result<TokenStream, String> { let mut tokens = TokenStream::new(); for rule in &program.rules { self.compile_rule(rule, &mut tokens)?; } let compiled = quote! {{ use euclid_graph_prelude::*; let mut graph = cgraph::ConstraintGraphBuilder::new(); #tokens graph.build() }}; Ok(compiled) } } pub(crate) fn knowledge_inner(ts: TokenStream) -> syn::Result<TokenStream> { let program = syn::parse::<Program>(ts.into())?; let mut gen_context = GenContext::new(); for rule in &program.rules { gen_context .register_rule(rule) .map_err(|msg| syn::Error::new(Span::call_site(), msg))?; } gen_context .detect_graph_cycles() .map_err(|msg| syn::Error::new(Span::call_site(), msg))?; gen_context .compile(program) .map_err(|msg| syn::Error::new(Span::call_site(), msg)) }
4,420
1,915
hyperswitch
crates/euclid_macros/src/inner/enum_nums.rs
.rs
use proc_macro::TokenStream; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::quote; fn error() -> TokenStream2 { syn::Error::new( Span::call_site(), "'EnumNums' can only be derived on enums with unit variants".to_string(), ) .to_compile_error() } pub(crate) fn enum_nums_inner(ts: TokenStream) -> TokenStream { let derive_input = syn::parse_macro_input!(ts as syn::DeriveInput); let enum_obj = match derive_input.data { syn::Data::Enum(e) => e, _ => return error().into(), }; let enum_name = derive_input.ident; let mut match_arms = Vec::<TokenStream2>::with_capacity(enum_obj.variants.len()); for (i, variant) in enum_obj.variants.iter().enumerate() { match variant.fields { syn::Fields::Unit => {} _ => return error().into(), } let var_ident = &variant.ident; match_arms.push(quote! { Self::#var_ident => #i }); } let impl_block = quote! { impl #enum_name { pub fn to_num(&self) -> usize { match self { #(#match_arms),* } } } }; impl_block.into() }
291
1,916
hyperswitch
crates/scheduler/Cargo.toml
.toml
[package] name = "scheduler" version = "0.1.0" edition.workspace = true rust-version.workspace = true license.workspace = true [features] default = ["kv_store", "olap"] olap = ["storage_impl/olap", "hyperswitch_domain_models/olap"] kv_store = [] email = ["external_services/email"] v1 = ["diesel_models/v1", "hyperswitch_domain_models/v1", "storage_impl/v1", "common_utils/v1", "common_types/v1"] v2 = ["diesel_models/v2", "hyperswitch_domain_models/v2", "storage_impl/v2", "common_utils/v2", "common_types/v2"] [dependencies] # Third party crates async-trait = "0.1.79" error-stack = "0.4.1" futures = "0.3.30" num_cpus = "1.16.0" once_cell = "1.19.0" rand = "0.8.5" serde = "1.0.197" serde_json = "1.0.115" strum = { version = "0.26.2", features = ["derive"] } thiserror = "1.0.58" time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } tokio = { version = "1.37.0", features = ["macros", "rt-multi-thread"] } uuid = { version = "1.8.0", features = ["v4"] } # First party crates common_utils = { version = "0.1.0", path = "../common_utils", features = ["signals", "async_ext"] } common_types = { version = "0.1.0", path = "../common_types" } diesel_models = { version = "0.1.0", path = "../diesel_models", features = ["kv_store"], default-features = false } external_services = { version = "0.1.0", path = "../external_services" } hyperswitch_domain_models = { version = "0.1.0", path = "../hyperswitch_domain_models", default-features = false } redis_interface = { version = "0.1.0", path = "../redis_interface" } router_env = { version = "0.1.0", path = "../router_env", features = ["log_extra_implicit_fields", "log_custom_entries_to_extra"] } storage_impl = { version = "0.1.0", path = "../storage_impl", default-features = false } [lints] workspace = true
576
1,917
hyperswitch
crates/scheduler/src/metrics.rs
.rs
use router_env::{counter_metric, global_meter, histogram_metric_f64}; global_meter!(PT_METER, "PROCESS_TRACKER"); histogram_metric_f64!(CONSUMER_OPS, PT_METER); counter_metric!(PAYMENT_COUNT, PT_METER); // No. of payments created counter_metric!(TASKS_PICKED_COUNT, PT_METER); // Tasks picked by counter_metric!(BATCHES_CREATED, PT_METER); // Batches added to stream counter_metric!(BATCHES_CONSUMED, PT_METER); // Batches consumed by consumer counter_metric!(TASK_CONSUMED, PT_METER); // Tasks consumed by consumer counter_metric!(TASK_PROCESSED, PT_METER); // Tasks completed processing counter_metric!(TASK_FINISHED, PT_METER); // Tasks finished counter_metric!(TASK_RETRIED, PT_METER); // Tasks added for retries
188
1,918
hyperswitch
crates/scheduler/src/db.rs
.rs
pub mod process_tracker; pub mod queue;
9
1,919
hyperswitch
crates/scheduler/src/consumer.rs
.rs
// TODO: Figure out what to log use std::{ sync::{self, atomic}, time as std_time, }; pub mod types; pub mod workflows; use common_utils::{errors::CustomResult, id_type, signals::get_allowed_signals}; use diesel_models::enums; pub use diesel_models::{self, process_tracker as storage}; use error_stack::ResultExt; use futures::future; use redis_interface::{RedisConnectionPool, RedisEntryId}; use router_env::{ instrument, tracing::{self, Instrument}, }; use time::PrimitiveDateTime; use tokio::sync::mpsc; use uuid::Uuid; use super::env::logger; pub use super::workflows::ProcessTrackerWorkflow; use crate::{ configs::settings::SchedulerSettings, db::process_tracker::ProcessTrackerInterface, errors, metrics, utils as pt_utils, SchedulerAppState, SchedulerInterface, SchedulerSessionState, }; // Valid consumer business statuses pub fn valid_business_statuses() -> Vec<&'static str> { vec![storage::business_status::PENDING] } #[instrument(skip_all)] pub async fn start_consumer<T: SchedulerAppState + 'static, U: SchedulerSessionState + 'static, F>( state: &T, settings: sync::Arc<SchedulerSettings>, workflow_selector: impl workflows::ProcessTrackerWorkflows<U> + 'static + Copy + std::fmt::Debug, (tx, mut rx): (mpsc::Sender<()>, mpsc::Receiver<()>), app_state_to_session_state: F, ) -> CustomResult<(), errors::ProcessTrackerError> where F: Fn(&T, &id_type::TenantId) -> CustomResult<U, errors::ProcessTrackerError>, { use std::time::Duration; use rand::distributions::{Distribution, Uniform}; let mut rng = rand::thread_rng(); // TODO: this can be removed once rand-0.9 is released // reference - https://github.com/rust-random/rand/issues/1326#issuecomment-1635331942 #[allow(unknown_lints)] #[allow(clippy::unnecessary_fallible_conversions)] let timeout = Uniform::try_from(0..=settings.loop_interval) .change_context(errors::ProcessTrackerError::ConfigurationError)?; tokio::time::sleep(Duration::from_millis(timeout.sample(&mut rng))).await; let mut interval = tokio::time::interval(Duration::from_millis(settings.loop_interval)); let mut shutdown_interval = tokio::time::interval(Duration::from_millis(settings.graceful_shutdown_interval)); let consumer_operation_counter = sync::Arc::new(atomic::AtomicU64::new(0)); let signal = get_allowed_signals() .map_err(|error| { logger::error!(?error, "Signal Handler Error"); errors::ProcessTrackerError::ConfigurationError }) .attach_printable("Failed while creating a signals handler")?; let handle = signal.handle(); let task_handle = tokio::spawn(common_utils::signals::signal_handler(signal, tx).in_current_span()); 'consumer: loop { match rx.try_recv() { Err(mpsc::error::TryRecvError::Empty) => { interval.tick().await; // A guard from env to disable the consumer if settings.consumer.disabled { continue; } consumer_operation_counter.fetch_add(1, atomic::Ordering::SeqCst); let start_time = std_time::Instant::now(); let tenants = state.get_tenants(); for tenant in tenants { let session_state = app_state_to_session_state(state, &tenant)?; pt_utils::consumer_operation_handler( session_state.clone(), settings.clone(), |error| { logger::error!(?error, "Failed to perform consumer operation"); }, workflow_selector, ) .await; } let end_time = std_time::Instant::now(); let duration = end_time.saturating_duration_since(start_time).as_secs_f64(); logger::debug!("Time taken to execute consumer_operation: {}s", duration); let current_count = consumer_operation_counter.fetch_sub(1, atomic::Ordering::SeqCst); logger::info!("Current tasks being executed: {}", current_count); } Ok(()) | Err(mpsc::error::TryRecvError::Disconnected) => { logger::debug!("Awaiting shutdown!"); rx.close(); loop { shutdown_interval.tick().await; let active_tasks = consumer_operation_counter.load(atomic::Ordering::Acquire); logger::info!("Active tasks: {active_tasks}"); match active_tasks { 0 => { logger::info!("Terminating consumer"); break 'consumer; } _ => continue, } } } } } handle.close(); task_handle .await .change_context(errors::ProcessTrackerError::UnexpectedFlow)?; Ok(()) } #[instrument(skip_all)] pub async fn consumer_operations<T: SchedulerSessionState + 'static>( state: &T, settings: &SchedulerSettings, workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + Copy + std::fmt::Debug, ) -> CustomResult<(), errors::ProcessTrackerError> { let stream_name = settings.stream.clone(); let group_name = settings.consumer.consumer_group.clone(); let consumer_name = format!("consumer_{}", Uuid::new_v4()); let _group_created = &mut state .get_db() .consumer_group_create(&stream_name, &group_name, &RedisEntryId::AfterLastID) .await; let mut tasks = state .get_db() .as_scheduler() .fetch_consumer_tasks(&stream_name, &group_name, &consumer_name) .await?; if !tasks.is_empty() { logger::info!("{} picked {} tasks", consumer_name, tasks.len()); } let mut handler = vec![]; for task in tasks.iter_mut() { let pickup_time = common_utils::date_time::now(); pt_utils::add_histogram_metrics(&pickup_time, task, &stream_name); metrics::TASK_CONSUMED.add(1, &[]); handler.push(tokio::task::spawn(start_workflow( state.clone(), task.clone(), pickup_time, workflow_selector, ))) } future::join_all(handler).await; Ok(()) } #[instrument(skip(db, redis_conn))] pub async fn fetch_consumer_tasks( db: &dyn ProcessTrackerInterface, redis_conn: &RedisConnectionPool, stream_name: &str, group_name: &str, consumer_name: &str, ) -> CustomResult<Vec<storage::ProcessTracker>, errors::ProcessTrackerError> { let batches = pt_utils::get_batches(redis_conn, stream_name, group_name, consumer_name).await?; // Returning early to avoid execution of database queries when `batches` is empty if batches.is_empty() { return Ok(Vec::new()); } let mut tasks = batches.into_iter().fold(Vec::new(), |mut acc, batch| { acc.extend_from_slice( batch .trackers .into_iter() .filter(|task| task.is_valid_business_status(&valid_business_statuses())) .collect::<Vec<_>>() .as_slice(), ); acc }); let task_ids = tasks .iter() .map(|task| task.id.to_owned()) .collect::<Vec<_>>(); db.process_tracker_update_process_status_by_ids( task_ids, storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::ProcessStarted, business_status: None, }, ) .await .change_context(errors::ProcessTrackerError::ProcessFetchingFailed)?; tasks .iter_mut() .for_each(|x| x.status = enums::ProcessTrackerStatus::ProcessStarted); Ok(tasks) } // Accept flow_options if required #[instrument(skip(state), fields(workflow_id))] pub async fn start_workflow<T>( state: T, process: storage::ProcessTracker, _pickup_time: PrimitiveDateTime, workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + std::fmt::Debug, ) -> CustomResult<(), errors::ProcessTrackerError> where T: SchedulerSessionState, { tracing::Span::current().record("workflow_id", Uuid::new_v4().to_string()); logger::info!(pt.name=?process.name, pt.id=%process.id); let res = workflow_selector .trigger_workflow(&state.clone(), process.clone()) .await .inspect_err(|error| { logger::error!(?error, "Failed to trigger workflow"); }); metrics::TASK_PROCESSED.add(1, &[]); res } #[instrument(skip_all)] pub async fn consumer_error_handler( state: &(dyn SchedulerInterface + 'static), process: storage::ProcessTracker, error: errors::ProcessTrackerError, ) -> CustomResult<(), errors::ProcessTrackerError> { logger::error!(pt.name=?process.name, pt.id=%process.id, ?error, "Failed to execute workflow"); state .process_tracker_update_process_status_by_ids( vec![process.id], storage::ProcessTrackerUpdate::StatusUpdate { status: enums::ProcessTrackerStatus::Finish, business_status: Some(String::from(storage::business_status::GLOBAL_ERROR)), }, ) .await .change_context(errors::ProcessTrackerError::ProcessUpdateFailed)?; Ok(()) } pub async fn create_task( db: &dyn ProcessTrackerInterface, process_tracker_entry: storage::ProcessTrackerNew, ) -> CustomResult<(), storage_impl::errors::StorageError> { db.insert_process(process_tracker_entry).await?; Ok(()) }
2,114
1,920
hyperswitch
crates/scheduler/src/producer.rs
.rs
use std::sync::Arc; use common_utils::{errors::CustomResult, id_type}; use diesel_models::enums::ProcessTrackerStatus; use error_stack::{report, ResultExt}; use router_env::{ instrument, tracing::{self, Instrument}, }; use time::Duration; use tokio::sync::mpsc; use super::{ env::logger::{self, debug, error, warn}, metrics, }; use crate::{ configs::settings::SchedulerSettings, errors, flow::SchedulerFlow, scheduler::SchedulerInterface, utils::*, SchedulerAppState, SchedulerSessionState, }; #[instrument(skip_all)] pub async fn start_producer<T, U, F>( state: &T, scheduler_settings: Arc<SchedulerSettings>, (tx, mut rx): (mpsc::Sender<()>, mpsc::Receiver<()>), app_state_to_session_state: F, ) -> CustomResult<(), errors::ProcessTrackerError> where F: Fn(&T, &id_type::TenantId) -> CustomResult<U, errors::ProcessTrackerError>, T: SchedulerAppState, U: SchedulerSessionState, { use std::time::Duration; use rand::distributions::{Distribution, Uniform}; let mut rng = rand::thread_rng(); // TODO: this can be removed once rand-0.9 is released // reference - https://github.com/rust-random/rand/issues/1326#issuecomment-1635331942 #[allow(unknown_lints)] #[allow(clippy::unnecessary_fallible_conversions)] let timeout = Uniform::try_from(0..=scheduler_settings.loop_interval) .change_context(errors::ProcessTrackerError::ConfigurationError)?; tokio::time::sleep(Duration::from_millis(timeout.sample(&mut rng))).await; let mut interval = tokio::time::interval(Duration::from_millis(scheduler_settings.loop_interval)); let mut shutdown_interval = tokio::time::interval(Duration::from_millis( scheduler_settings.graceful_shutdown_interval, )); let signal = common_utils::signals::get_allowed_signals() .map_err(|error| { logger::error!("Signal Handler Error: {:?}", error); errors::ProcessTrackerError::ConfigurationError }) .attach_printable("Failed while creating a signals handler")?; let handle = signal.handle(); let task_handle = tokio::spawn(common_utils::signals::signal_handler(signal, tx).in_current_span()); loop { match rx.try_recv() { Err(mpsc::error::TryRecvError::Empty) => { interval.tick().await; let tenants = state.get_tenants(); for tenant in tenants { let session_state = app_state_to_session_state(state, &tenant)?; match run_producer_flow(&session_state, &scheduler_settings).await { Ok(_) => (), Err(error) => { // Intentionally not propagating error to caller. // Any errors that occur in the producer flow must be handled here only, as // this is the topmost level function which is concerned with the producer flow. error!(?error); } } } } Ok(()) | Err(mpsc::error::TryRecvError::Disconnected) => { logger::debug!("Awaiting shutdown!"); rx.close(); shutdown_interval.tick().await; logger::info!("Terminating producer"); break; } } } handle.close(); task_handle .await .change_context(errors::ProcessTrackerError::UnexpectedFlow)?; Ok(()) } #[instrument(skip_all)] pub async fn run_producer_flow<T>( state: &T, settings: &SchedulerSettings, ) -> CustomResult<(), errors::ProcessTrackerError> where T: SchedulerSessionState, { lock_acquire_release::<_, _, _>(state.get_db().as_scheduler(), settings, move || async { let tasks = fetch_producer_tasks(state.get_db().as_scheduler(), settings).await?; debug!("Producer count of tasks {}", tasks.len()); // [#268]: Allow task based segregation of tasks divide_and_append_tasks( state.get_db().as_scheduler(), SchedulerFlow::Producer, tasks, settings, ) .await?; Ok(()) }) .await?; Ok(()) } #[instrument(skip_all)] pub async fn fetch_producer_tasks( db: &dyn SchedulerInterface, conf: &SchedulerSettings, ) -> CustomResult<Vec<storage::ProcessTracker>, errors::ProcessTrackerError> { let upper = conf.producer.upper_fetch_limit; let lower = conf.producer.lower_fetch_limit; let now = common_utils::date_time::now(); // Add these to validations let time_upper_limit = now.checked_add(Duration::seconds(upper)).ok_or_else(|| { report!(errors::ProcessTrackerError::ConfigurationError) .attach_printable("Error obtaining upper limit to fetch producer tasks") })?; let time_lower_limit = now.checked_sub(Duration::seconds(lower)).ok_or_else(|| { report!(errors::ProcessTrackerError::ConfigurationError) .attach_printable("Error obtaining lower limit to fetch producer tasks") })?; let mut new_tasks = db .find_processes_by_time_status( time_lower_limit, time_upper_limit, ProcessTrackerStatus::New, None, ) .await .change_context(errors::ProcessTrackerError::ProcessFetchingFailed)?; let mut pending_tasks = db .find_processes_by_time_status( time_lower_limit, time_upper_limit, ProcessTrackerStatus::Pending, None, ) .await .change_context(errors::ProcessTrackerError::ProcessFetchingFailed)?; if new_tasks.is_empty() { warn!("No new tasks found for producer to schedule"); } if pending_tasks.is_empty() { warn!("No pending tasks found for producer to schedule"); } new_tasks.append(&mut pending_tasks); // Safety: Assuming we won't deal with more than `u64::MAX` tasks at once #[allow(clippy::as_conversions)] metrics::TASKS_PICKED_COUNT.add(new_tasks.len() as u64, &[]); Ok(new_tasks) }
1,334
1,921
hyperswitch
crates/scheduler/src/settings.rs
.rs
use common_utils::ext_traits::ConfigExt; use serde::Deserialize; use storage_impl::errors::ApplicationError; pub use crate::configs::settings::SchedulerSettings; #[derive(Debug, Clone, Deserialize)] pub struct ProducerSettings { pub upper_fetch_limit: i64, pub lower_fetch_limit: i64, pub lock_key: String, pub lock_ttl: i64, pub batch_size: usize, } #[derive(Debug, Clone, Deserialize)] pub struct ConsumerSettings { pub disabled: bool, pub consumer_group: String, } #[cfg(feature = "kv_store")] #[derive(Debug, Clone, Deserialize)] pub struct DrainerSettings { pub stream_name: String, pub num_partitions: u8, pub max_read_count: u64, pub shutdown_interval: u32, // in milliseconds pub loop_interval: u32, // in milliseconds } impl ProducerSettings { pub fn validate(&self) -> Result<(), ApplicationError> { common_utils::fp_utils::when(self.lock_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "producer lock key must not be empty".into(), )) }) } } #[cfg(feature = "kv_store")] impl DrainerSettings { pub fn validate(&self) -> Result<(), ApplicationError> { common_utils::fp_utils::when(self.stream_name.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "drainer stream name must not be empty".into(), )) }) } } impl Default for ProducerSettings { fn default() -> Self { Self { upper_fetch_limit: 0, lower_fetch_limit: 1800, lock_key: "PRODUCER_LOCKING_KEY".into(), lock_ttl: 160, batch_size: 200, } } } impl Default for ConsumerSettings { fn default() -> Self { Self { disabled: false, consumer_group: "SCHEDULER_GROUP".into(), } } } #[cfg(feature = "kv_store")] impl Default for DrainerSettings { fn default() -> Self { Self { stream_name: "DRAINER_STREAM".into(), num_partitions: 64, max_read_count: 100, shutdown_interval: 1000, loop_interval: 500, } } }
524
1,922
hyperswitch
crates/scheduler/src/scheduler.rs
.rs
use std::sync::Arc; use common_utils::{errors::CustomResult, id_type}; #[cfg(feature = "kv_store")] use storage_impl::kv_router_store::KVRouterStore; use storage_impl::mock_db::MockDb; #[cfg(not(feature = "kv_store"))] use storage_impl::RouterStore; use tokio::sync::mpsc; use super::env::logger::error; pub use crate::{ configs::settings::SchedulerSettings, consumer::{self, workflows}, db::{process_tracker::ProcessTrackerInterface, queue::QueueInterface}, errors, flow::SchedulerFlow, producer, }; #[cfg(not(feature = "olap"))] type StoreType = storage_impl::database::store::Store; #[cfg(feature = "olap")] type StoreType = storage_impl::database::store::ReplicaStore; #[cfg(not(feature = "kv_store"))] pub type Store = RouterStore<StoreType>; #[cfg(feature = "kv_store")] pub type Store = KVRouterStore<StoreType>; pub trait AsSchedulerInterface { fn as_scheduler(&self) -> &dyn SchedulerInterface; } impl<T: SchedulerInterface> AsSchedulerInterface for T { fn as_scheduler(&self) -> &dyn SchedulerInterface { self } } #[async_trait::async_trait] pub trait SchedulerInterface: ProcessTrackerInterface + QueueInterface + AsSchedulerInterface { } #[async_trait::async_trait] impl SchedulerInterface for Store {} #[async_trait::async_trait] impl SchedulerInterface for MockDb {} #[async_trait::async_trait] pub trait SchedulerAppState: Send + Sync + Clone { fn get_tenants(&self) -> Vec<id_type::TenantId>; } #[async_trait::async_trait] pub trait SchedulerSessionState: Send + Sync + Clone { fn get_db(&self) -> Box<dyn SchedulerInterface>; } pub async fn start_process_tracker< T: SchedulerAppState + 'static, U: SchedulerSessionState + 'static, F, >( state: &T, scheduler_flow: SchedulerFlow, scheduler_settings: Arc<SchedulerSettings>, channel: (mpsc::Sender<()>, mpsc::Receiver<()>), runner_from_task: impl workflows::ProcessTrackerWorkflows<U> + 'static + Copy + std::fmt::Debug, app_state_to_session_state: F, ) -> CustomResult<(), errors::ProcessTrackerError> where F: Fn(&T, &id_type::TenantId) -> CustomResult<U, errors::ProcessTrackerError>, { match scheduler_flow { SchedulerFlow::Producer => { producer::start_producer( state, scheduler_settings, channel, app_state_to_session_state, ) .await? } SchedulerFlow::Consumer => { consumer::start_consumer( state, scheduler_settings, runner_from_task, channel, app_state_to_session_state, ) .await? } SchedulerFlow::Cleaner => { error!("This flow has not been implemented yet!"); } } Ok(()) }
646
1,923
hyperswitch
crates/scheduler/src/utils.rs
.rs
use std::sync; use common_utils::errors::CustomResult; use diesel_models::enums::{self, ProcessTrackerStatus}; pub use diesel_models::process_tracker as storage; use error_stack::{report, ResultExt}; use redis_interface::{RedisConnectionPool, RedisEntryId}; use router_env::{instrument, tracing}; use uuid::Uuid; use super::{ consumer::{self, types::process_data, workflows}, env::logger, }; use crate::{ configs::settings::SchedulerSettings, consumer::types::ProcessTrackerBatch, errors, flow::SchedulerFlow, metrics, SchedulerInterface, SchedulerSessionState, }; pub async fn divide_and_append_tasks<T>( state: &T, flow: SchedulerFlow, tasks: Vec<storage::ProcessTracker>, settings: &SchedulerSettings, ) -> CustomResult<(), errors::ProcessTrackerError> where T: SchedulerInterface + Send + Sync + ?Sized, { let batches = divide(tasks, settings); // Safety: Assuming we won't deal with more than `u64::MAX` batches at once #[allow(clippy::as_conversions)] metrics::BATCHES_CREATED.add(batches.len() as u64, &[]); // Metrics for batch in batches { let result = update_status_and_append(state, flow, batch).await; match result { Ok(_) => (), Err(error) => logger::error!(?error), } } Ok(()) } pub async fn update_status_and_append<T>( state: &T, flow: SchedulerFlow, pt_batch: ProcessTrackerBatch, ) -> CustomResult<(), errors::ProcessTrackerError> where T: SchedulerInterface + Send + Sync + ?Sized, { let process_ids: Vec<String> = pt_batch .trackers .iter() .map(|process| process.id.to_owned()) .collect(); match flow { SchedulerFlow::Producer => state .process_tracker_update_process_status_by_ids( process_ids, storage::ProcessTrackerUpdate::StatusUpdate { status: ProcessTrackerStatus::Processing, business_status: None, }, ) .await .map_or_else( |error| { logger::error!(?error, "Error while updating process status"); Err(error.change_context(errors::ProcessTrackerError::ProcessUpdateFailed)) }, |count| { logger::debug!("Updated status of {count} processes"); Ok(()) }, ), SchedulerFlow::Cleaner => { let res = state .reinitialize_limbo_processes(process_ids, common_utils::date_time::now()) .await; match res { Ok(count) => { logger::debug!("Reinitialized {count} processes"); Ok(()) } Err(error) => { logger::error!(?error, "Error while reinitializing processes"); Err(error.change_context(errors::ProcessTrackerError::ProcessUpdateFailed)) } } } _ => { let error = format!("Unexpected scheduler flow {flow:?}"); logger::error!(%error); Err(report!(errors::ProcessTrackerError::UnexpectedFlow).attach_printable(error)) } }?; let field_value_pairs = pt_batch.to_redis_field_value_pairs()?; match state .stream_append_entry( &pt_batch.stream_name, &RedisEntryId::AutoGeneratedID, field_value_pairs, ) .await .change_context(errors::ProcessTrackerError::BatchInsertionFailed) { Ok(x) => Ok(x), Err(mut err) => { let update_res = state .process_tracker_update_process_status_by_ids( pt_batch .trackers .iter() .map(|process| process.id.clone()) .collect(), storage::ProcessTrackerUpdate::StatusUpdate { status: ProcessTrackerStatus::Processing, business_status: None, }, ) .await .map_or_else( |error| { logger::error!(?error, "Error while updating process status"); Err(error.change_context(errors::ProcessTrackerError::ProcessUpdateFailed)) }, |count| { logger::debug!("Updated status of {count} processes"); Ok(()) }, ); match update_res { Ok(_) => (), Err(inner_err) => { err.extend_one(inner_err); } }; Err(err) } } } pub fn divide( tasks: Vec<storage::ProcessTracker>, conf: &SchedulerSettings, ) -> Vec<ProcessTrackerBatch> { let now = common_utils::date_time::now(); let batch_size = conf.producer.batch_size; divide_into_batches(batch_size, tasks, now, conf) } pub fn divide_into_batches( batch_size: usize, tasks: Vec<storage::ProcessTracker>, batch_creation_time: time::PrimitiveDateTime, conf: &SchedulerSettings, ) -> Vec<ProcessTrackerBatch> { let batch_id = Uuid::new_v4().to_string(); tasks .chunks(batch_size) .fold(Vec::new(), |mut batches, item| { let batch = ProcessTrackerBatch { id: batch_id.clone(), group_name: conf.consumer.consumer_group.clone(), stream_name: conf.stream.clone(), connection_name: String::new(), created_time: batch_creation_time, rule: String::new(), // is it required? trackers: item.to_vec(), }; batches.push(batch); batches }) } pub async fn get_batches( conn: &RedisConnectionPool, stream_name: &str, group_name: &str, consumer_name: &str, ) -> CustomResult<Vec<ProcessTrackerBatch>, errors::ProcessTrackerError> { let response = match conn .stream_read_with_options( stream_name, RedisEntryId::UndeliveredEntryID, // Update logic for collecting to Vec and flattening, if count > 1 is provided Some(1), None, Some((group_name, consumer_name)), ) .await { Ok(response) => response, Err(error) => { if let redis_interface::errors::RedisError::StreamEmptyOrNotAvailable = error.current_context() { logger::debug!("No batches processed as stream is empty"); return Ok(Vec::new()); } else { return Err(error.change_context(errors::ProcessTrackerError::BatchNotFound)); } } }; metrics::BATCHES_CONSUMED.add(1, &[]); let (batches, entry_ids): (Vec<Vec<ProcessTrackerBatch>>, Vec<Vec<String>>) = response.into_values().map(|entries| { entries.into_iter().try_fold( (Vec::new(), Vec::new()), |(mut batches, mut entry_ids), entry| { // Redis entry ID entry_ids.push(entry.0); // Value HashMap batches.push(ProcessTrackerBatch::from_redis_stream_entry(entry.1)?); Ok((batches, entry_ids)) }, ) }).collect::<CustomResult<Vec<(Vec<ProcessTrackerBatch>, Vec<String>)>, errors::ProcessTrackerError>>()? .into_iter() .unzip(); // Flattening the Vec's since the count provided above is 1. This needs to be updated if a // count greater than 1 is provided. let batches = batches.into_iter().flatten().collect::<Vec<_>>(); let entry_ids = entry_ids.into_iter().flatten().collect::<Vec<_>>(); conn.stream_acknowledge_entries(&stream_name.into(), group_name, entry_ids.clone()) .await .map_err(|error| { logger::error!(?error, "Error acknowledging batch in stream"); error.change_context(errors::ProcessTrackerError::BatchUpdateFailed) })?; conn.stream_delete_entries(&stream_name.into(), entry_ids.clone()) .await .map_err(|error| { logger::error!(?error, "Error deleting batch from stream"); error.change_context(errors::ProcessTrackerError::BatchDeleteFailed) })?; Ok(batches) } pub fn get_process_tracker_id<'a>( runner: storage::ProcessTrackerRunner, task_name: &'a str, txn_id: &'a str, merchant_id: &'a common_utils::id_type::MerchantId, ) -> String { format!( "{runner}_{task_name}_{txn_id}_{}", merchant_id.get_string_repr() ) } pub fn get_time_from_delta(delta: Option<i32>) -> Option<time::PrimitiveDateTime> { delta.map(|t| common_utils::date_time::now().saturating_add(time::Duration::seconds(t.into()))) } #[instrument(skip_all)] pub async fn consumer_operation_handler<E, T>( state: T, settings: sync::Arc<SchedulerSettings>, error_handler_fun: E, workflow_selector: impl workflows::ProcessTrackerWorkflows<T> + 'static + Copy + std::fmt::Debug, ) where // Error handler function E: FnOnce(error_stack::Report<errors::ProcessTrackerError>), T: SchedulerSessionState + Send + Sync + 'static, { match consumer::consumer_operations(&state, &settings, workflow_selector).await { Ok(_) => (), Err(err) => error_handler_fun(err), } } pub fn add_histogram_metrics( pickup_time: &time::PrimitiveDateTime, task: &mut storage::ProcessTracker, stream_name: &str, ) { #[warn(clippy::option_map_unit_fn)] if let Some((schedule_time, runner)) = task.schedule_time.as_ref().zip(task.runner.as_ref()) { let pickup_schedule_delta = (*pickup_time - *schedule_time).as_seconds_f64(); logger::info!("Time delta for scheduled tasks: {pickup_schedule_delta} seconds"); let runner_name = runner.clone(); metrics::CONSUMER_OPS.record( pickup_schedule_delta, router_env::metric_attributes!((stream_name.to_owned(), runner_name)), ); }; } pub fn get_schedule_time( mapping: process_data::ConnectorPTMapping, merchant_id: &common_utils::id_type::MerchantId, retry_count: i32, ) -> Option<i32> { let mapping = match mapping.custom_merchant_mapping.get(merchant_id) { Some(map) => map.clone(), None => mapping.default_mapping, }; // For first try, get the `start_after` time if retry_count == 0 { Some(mapping.start_after) } else { get_delay(retry_count, &mapping.frequencies) } } pub fn get_pm_schedule_time( mapping: process_data::PaymentMethodsPTMapping, pm: enums::PaymentMethod, retry_count: i32, ) -> Option<i32> { let mapping = match mapping.custom_pm_mapping.get(&pm) { Some(map) => map.clone(), None => mapping.default_mapping, }; if retry_count == 0 { Some(mapping.start_after) } else { get_delay(retry_count, &mapping.frequencies) } } pub fn get_outgoing_webhook_retry_schedule_time( mapping: process_data::OutgoingWebhookRetryProcessTrackerMapping, merchant_id: &common_utils::id_type::MerchantId, retry_count: i32, ) -> Option<i32> { let retry_mapping = match mapping.custom_merchant_mapping.get(merchant_id) { Some(map) => map.clone(), None => mapping.default_mapping, }; // For first try, get the `start_after` time if retry_count == 0 { Some(retry_mapping.start_after) } else { get_delay(retry_count, &retry_mapping.frequencies) } } pub fn get_pcr_payments_retry_schedule_time( mapping: process_data::RevenueRecoveryPaymentProcessTrackerMapping, merchant_id: &common_utils::id_type::MerchantId, retry_count: i32, ) -> Option<i32> { let mapping = match mapping.custom_merchant_mapping.get(merchant_id) { Some(map) => map.clone(), None => mapping.default_mapping, }; // TODO: check if the current scheduled time is not more than the configured timerange // For first try, get the `start_after` time if retry_count == 0 { Some(mapping.start_after) } else { get_delay(retry_count, &mapping.frequencies) } } /// Get the delay based on the retry count pub fn get_delay<'a>( retry_count: i32, frequencies: impl IntoIterator<Item = &'a (i32, i32)>, ) -> Option<i32> { // Preferably, fix this by using unsigned ints if retry_count <= 0 { return None; } let mut cumulative_count = 0; for &(frequency, count) in frequencies.into_iter() { cumulative_count += count; if cumulative_count >= retry_count { return Some(frequency); } } None } pub(crate) async fn lock_acquire_release<T, F, Fut>( state: &T, settings: &SchedulerSettings, callback: F, ) -> CustomResult<(), errors::ProcessTrackerError> where F: Fn() -> Fut, T: SchedulerInterface + Send + Sync + ?Sized, Fut: futures::Future<Output = CustomResult<(), errors::ProcessTrackerError>>, { let tag = "PRODUCER_LOCK"; let lock_key = &settings.producer.lock_key; let lock_val = "LOCKED"; let ttl = settings.producer.lock_ttl; if state .acquire_pt_lock(tag, lock_key, lock_val, ttl) .await .change_context(errors::ProcessTrackerError::ERedisError( errors::RedisError::RedisConnectionError.into(), ))? { let result = callback().await; state .release_pt_lock(tag, lock_key) .await .map_err(errors::ProcessTrackerError::ERedisError)?; result } else { Ok(()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_get_delay() { let frequency_count = vec![(300, 10), (600, 5), (1800, 3), (3600, 2)]; let retry_counts_and_expected_delays = [ (-4, None), (-2, None), (0, None), (4, Some(300)), (7, Some(300)), (10, Some(300)), (12, Some(600)), (16, Some(1800)), (18, Some(1800)), (20, Some(3600)), (24, None), (30, None), ]; for (retry_count, expected_delay) in retry_counts_and_expected_delays { let delay = get_delay(retry_count, &frequency_count); assert_eq!( delay, expected_delay, "Delay and expected delay differ for `retry_count` = {retry_count}" ); } } }
3,302
1,924
hyperswitch
crates/scheduler/src/env.rs
.rs
#[doc(inline)] pub use router_env::*;
10
1,925
hyperswitch
crates/scheduler/src/lib.rs
.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::*};
58
1,926
hyperswitch
crates/scheduler/src/flow.rs
.rs
#[derive(Copy, Clone, Debug, strum::Display, strum::EnumString)] #[strum(serialize_all = "snake_case")] pub enum SchedulerFlow { Producer, Consumer, Cleaner, }
46
1,927
hyperswitch
crates/scheduler/src/errors.rs
.rs
pub use common_utils::errors::{ParsingError, ValidationError}; #[cfg(feature = "email")] use external_services::email::EmailError; use hyperswitch_domain_models::errors::api_error_response::ApiErrorResponse; pub use redis_interface::errors::RedisError; pub use storage_impl::errors::ApplicationError; use storage_impl::errors::{RecoveryError, StorageError}; use crate::env::logger::{self, error}; #[derive(Debug, thiserror::Error)] pub enum ProcessTrackerError { #[error("An unexpected flow was specified")] UnexpectedFlow, #[error("Failed to serialize object")] SerializationFailed, #[error("Failed to deserialize object")] DeserializationFailed, #[error("Missing required field")] MissingRequiredField, #[error("Failed to insert process batch into stream")] BatchInsertionFailed, #[error("Failed to insert process into stream")] ProcessInsertionFailed, #[error("The process batch with the specified details was not found")] BatchNotFound, #[error("Failed to update process batch in stream")] BatchUpdateFailed, #[error("Failed to delete process batch from stream")] BatchDeleteFailed, #[error("An error occurred when trying to read process tracker configuration")] ConfigurationError, #[error("Failed to update process in database")] ProcessUpdateFailed, #[error("Failed to fetch processes from database")] ProcessFetchingFailed, #[error("Failed while fetching: {resource_name}")] ResourceFetchingFailed { resource_name: String }, #[error("Failed while executing: {flow}")] FlowExecutionError { flow: &'static str }, #[error("Not Implemented")] NotImplemented, #[error("Job not found")] JobNotFound, #[error("Received Error ApiResponseError")] EApiErrorResponse, #[error("Received Error ClientError")] EClientError, #[error("Received RecoveryError: {0:?}")] ERecoveryError(error_stack::Report<RecoveryError>), #[error("Received Error StorageError: {0:?}")] EStorageError(error_stack::Report<StorageError>), #[error("Received Error RedisError: {0:?}")] ERedisError(error_stack::Report<RedisError>), #[error("Received Error ParsingError: {0:?}")] EParsingError(error_stack::Report<ParsingError>), #[error("Validation Error Received: {0:?}")] EValidationError(error_stack::Report<ValidationError>), #[cfg(feature = "email")] #[error("Received Error EmailError: {0:?}")] EEmailError(error_stack::Report<EmailError>), #[error("Type Conversion error")] TypeConversionError, #[error("Tenant not found")] TenantNotFound, } #[macro_export] macro_rules! error_to_process_tracker_error { ($($path: ident)::+ < $st: ident >, $($path2:ident)::* ($($inner_path2:ident)::+ <$st2:ident>) ) => { impl From<$($path)::+ <$st>> for ProcessTrackerError { fn from(err: $($path)::+ <$st> ) -> Self { $($path2)::*(err) } } }; ($($path: ident)::+ <$($inner_path:ident)::+>, $($path2:ident)::* ($($inner_path2:ident)::+ <$st2:ident>) ) => { impl<'a> From< $($path)::+ <$($inner_path)::+> > for ProcessTrackerError { fn from(err: $($path)::+ <$($inner_path)::+> ) -> Self { $($path2)::*(err) } } }; } pub trait PTError: Send + Sync + 'static { fn to_pt_error(&self) -> ProcessTrackerError; } impl<T: PTError> From<T> for ProcessTrackerError { fn from(value: T) -> Self { value.to_pt_error() } } impl PTError for ApiErrorResponse { fn to_pt_error(&self) -> ProcessTrackerError { ProcessTrackerError::EApiErrorResponse } } impl<T: PTError + std::fmt::Debug + std::fmt::Display> From<error_stack::Report<T>> for ProcessTrackerError { fn from(error: error_stack::Report<T>) -> Self { logger::error!(?error); error.current_context().to_pt_error() } } error_to_process_tracker_error!( error_stack::Report<StorageError>, ProcessTrackerError::EStorageError(error_stack::Report<StorageError>) ); error_to_process_tracker_error!( error_stack::Report<RedisError>, ProcessTrackerError::ERedisError(error_stack::Report<RedisError>) ); error_to_process_tracker_error!( error_stack::Report<ParsingError>, ProcessTrackerError::EParsingError(error_stack::Report<ParsingError>) ); error_to_process_tracker_error!( error_stack::Report<ValidationError>, ProcessTrackerError::EValidationError(error_stack::Report<ValidationError>) ); #[cfg(feature = "email")] error_to_process_tracker_error!( error_stack::Report<EmailError>, ProcessTrackerError::EEmailError(error_stack::Report<EmailError>) ); error_to_process_tracker_error!( error_stack::Report<RecoveryError>, ProcessTrackerError::ERecoveryError(error_stack::Report<RecoveryError>) );
1,135
1,928
hyperswitch
crates/scheduler/src/configs.rs
.rs
pub mod defaults; pub mod settings; pub mod validations;
12
1,929
hyperswitch
crates/scheduler/src/db/process_tracker.rs
.rs
use common_utils::errors::CustomResult; pub use diesel_models as storage; use diesel_models::enums as storage_enums; use error_stack::{report, ResultExt}; use storage_impl::{connection, errors, mock_db::MockDb}; use time::PrimitiveDateTime; use crate::{metrics, scheduler::Store}; #[async_trait::async_trait] pub trait ProcessTrackerInterface: Send + Sync + 'static { async fn reinitialize_limbo_processes( &self, ids: Vec<String>, schedule_time: PrimitiveDateTime, ) -> CustomResult<usize, errors::StorageError>; async fn find_process_by_id( &self, id: &str, ) -> CustomResult<Option<storage::ProcessTracker>, errors::StorageError>; async fn update_process( &self, this: storage::ProcessTracker, process: storage::ProcessTrackerUpdate, ) -> CustomResult<storage::ProcessTracker, errors::StorageError>; async fn process_tracker_update_process_status_by_ids( &self, task_ids: Vec<String>, task_update: storage::ProcessTrackerUpdate, ) -> CustomResult<usize, errors::StorageError>; async fn insert_process( &self, new: storage::ProcessTrackerNew, ) -> CustomResult<storage::ProcessTracker, errors::StorageError>; async fn reset_process( &self, this: storage::ProcessTracker, schedule_time: PrimitiveDateTime, ) -> CustomResult<(), errors::StorageError>; async fn retry_process( &self, this: storage::ProcessTracker, schedule_time: PrimitiveDateTime, ) -> CustomResult<(), errors::StorageError>; async fn finish_process_with_business_status( &self, this: storage::ProcessTracker, business_status: &'static str, ) -> CustomResult<(), errors::StorageError>; async fn find_processes_by_time_status( &self, time_lower_limit: PrimitiveDateTime, time_upper_limit: PrimitiveDateTime, status: storage_enums::ProcessTrackerStatus, limit: Option<i64>, ) -> CustomResult<Vec<storage::ProcessTracker>, errors::StorageError>; } #[async_trait::async_trait] impl ProcessTrackerInterface for Store { async fn find_process_by_id( &self, id: &str, ) -> CustomResult<Option<storage::ProcessTracker>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::ProcessTracker::find_process_by_id(&conn, id) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn reinitialize_limbo_processes( &self, ids: Vec<String>, schedule_time: PrimitiveDateTime, ) -> CustomResult<usize, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::ProcessTracker::reinitialize_limbo_processes(&conn, ids, schedule_time) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn find_processes_by_time_status( &self, time_lower_limit: PrimitiveDateTime, time_upper_limit: PrimitiveDateTime, status: storage_enums::ProcessTrackerStatus, limit: Option<i64>, ) -> CustomResult<Vec<storage::ProcessTracker>, errors::StorageError> { let conn = connection::pg_connection_read(self).await?; storage::ProcessTracker::find_processes_by_time_status( &conn, time_lower_limit, time_upper_limit, status, limit, common_types::consts::API_VERSION, ) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn insert_process( &self, new: storage::ProcessTrackerNew, ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; new.insert_process(&conn) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn update_process( &self, this: storage::ProcessTracker, process: storage::ProcessTrackerUpdate, ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; this.update(&conn, process) .await .map_err(|error| report!(errors::StorageError::from(error))) } async fn reset_process( &self, this: storage::ProcessTracker, schedule_time: PrimitiveDateTime, ) -> CustomResult<(), errors::StorageError> { self.update_process( this, storage::ProcessTrackerUpdate::StatusRetryUpdate { status: storage_enums::ProcessTrackerStatus::New, retry_count: 0, schedule_time, }, ) .await?; Ok(()) } async fn retry_process( &self, this: storage::ProcessTracker, schedule_time: PrimitiveDateTime, ) -> CustomResult<(), errors::StorageError> { metrics::TASK_RETRIED.add(1, &[]); let retry_count = this.retry_count + 1; self.update_process( this, storage::ProcessTrackerUpdate::StatusRetryUpdate { status: storage_enums::ProcessTrackerStatus::Pending, retry_count, schedule_time, }, ) .await?; Ok(()) } async fn finish_process_with_business_status( &self, this: storage::ProcessTracker, business_status: &'static str, ) -> CustomResult<(), errors::StorageError> { self.update_process( this, storage::ProcessTrackerUpdate::StatusUpdate { status: storage_enums::ProcessTrackerStatus::Finish, business_status: Some(String::from(business_status)), }, ) .await .attach_printable("Failed to update business status of process")?; metrics::TASK_FINISHED.add(1, &[]); Ok(()) } async fn process_tracker_update_process_status_by_ids( &self, task_ids: Vec<String>, task_update: storage::ProcessTrackerUpdate, ) -> CustomResult<usize, errors::StorageError> { let conn = connection::pg_connection_write(self).await?; storage::ProcessTracker::update_process_status_by_ids(&conn, task_ids, task_update) .await .map_err(|error| report!(errors::StorageError::from(error))) } } #[async_trait::async_trait] impl ProcessTrackerInterface for MockDb { async fn find_process_by_id( &self, id: &str, ) -> CustomResult<Option<storage::ProcessTracker>, errors::StorageError> { let optional = self .processes .lock() .await .iter() .find(|process| process.id == id) .cloned(); Ok(optional) } async fn reinitialize_limbo_processes( &self, _ids: Vec<String>, _schedule_time: PrimitiveDateTime, ) -> CustomResult<usize, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn find_processes_by_time_status( &self, _time_lower_limit: PrimitiveDateTime, _time_upper_limit: PrimitiveDateTime, _status: storage_enums::ProcessTrackerStatus, _limit: Option<i64>, ) -> CustomResult<Vec<storage::ProcessTracker>, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn insert_process( &self, new: storage::ProcessTrackerNew, ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { let mut processes = self.processes.lock().await; let process = storage::ProcessTracker { id: new.id, name: new.name, tag: new.tag, runner: new.runner, retry_count: new.retry_count, schedule_time: new.schedule_time, rule: new.rule, tracking_data: new.tracking_data, business_status: new.business_status, status: new.status, event: new.event, created_at: new.created_at, updated_at: new.updated_at, version: new.version, }; processes.push(process.clone()); Ok(process) } async fn update_process( &self, _this: storage::ProcessTracker, _process: storage::ProcessTrackerUpdate, ) -> CustomResult<storage::ProcessTracker, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn reset_process( &self, _this: storage::ProcessTracker, _schedule_time: PrimitiveDateTime, ) -> CustomResult<(), errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn retry_process( &self, _this: storage::ProcessTracker, _schedule_time: PrimitiveDateTime, ) -> CustomResult<(), errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn finish_process_with_business_status( &self, _this: storage::ProcessTracker, _business_status: &'static str, ) -> CustomResult<(), errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } async fn process_tracker_update_process_status_by_ids( &self, _task_ids: Vec<String>, _task_update: storage::ProcessTrackerUpdate, ) -> CustomResult<usize, errors::StorageError> { // [#172]: Implement function for `MockDb` Err(errors::StorageError::MockDbError)? } }
2,177
1,930
hyperswitch
crates/scheduler/src/db/queue.rs
.rs
use common_utils::errors::CustomResult; use diesel_models::process_tracker as storage; use redis_interface::{errors::RedisError, RedisEntryId, SetnxReply}; use router_env::logger; use storage_impl::{mock_db::MockDb, redis::kv_store::RedisConnInterface}; use crate::{errors::ProcessTrackerError, scheduler::Store}; #[async_trait::async_trait] pub trait QueueInterface { async fn fetch_consumer_tasks( &self, stream_name: &str, group_name: &str, consumer_name: &str, ) -> CustomResult<Vec<storage::ProcessTracker>, ProcessTrackerError>; async fn consumer_group_create( &self, stream: &str, group: &str, id: &RedisEntryId, ) -> CustomResult<(), RedisError>; async fn acquire_pt_lock( &self, tag: &str, lock_key: &str, lock_val: &str, ttl: i64, ) -> CustomResult<bool, RedisError>; async fn release_pt_lock(&self, tag: &str, lock_key: &str) -> CustomResult<bool, RedisError>; async fn stream_append_entry( &self, stream: &str, entry_id: &RedisEntryId, fields: Vec<(&str, String)>, ) -> CustomResult<(), RedisError>; async fn get_key(&self, key: &str) -> CustomResult<Vec<u8>, RedisError>; } #[async_trait::async_trait] impl QueueInterface for Store { async fn fetch_consumer_tasks( &self, stream_name: &str, group_name: &str, consumer_name: &str, ) -> CustomResult<Vec<storage::ProcessTracker>, ProcessTrackerError> { crate::consumer::fetch_consumer_tasks( self, &self .get_redis_conn() .map_err(ProcessTrackerError::ERedisError)? .clone(), stream_name, group_name, consumer_name, ) .await } async fn consumer_group_create( &self, stream: &str, group: &str, id: &RedisEntryId, ) -> CustomResult<(), RedisError> { self.get_redis_conn()? .consumer_group_create(&stream.into(), group, id) .await } async fn acquire_pt_lock( &self, tag: &str, lock_key: &str, lock_val: &str, ttl: i64, ) -> CustomResult<bool, RedisError> { let conn = self.get_redis_conn()?.clone(); let is_lock_acquired = conn .set_key_if_not_exists_with_expiry(&lock_key.into(), lock_val, None) .await; Ok(match is_lock_acquired { Ok(SetnxReply::KeySet) => match conn.set_expiry(&lock_key.into(), ttl).await { Ok(()) => true, #[allow(unused_must_use)] Err(error) => { logger::error!(?error); conn.delete_key(&lock_key.into()).await; false } }, Ok(SetnxReply::KeyNotSet) => { logger::error!(%tag, "Lock not acquired, previous fetch still in progress"); false } Err(error) => { logger::error!(?error, %tag, "Error while locking"); false } }) } async fn release_pt_lock(&self, tag: &str, lock_key: &str) -> CustomResult<bool, RedisError> { let is_lock_released = self.get_redis_conn()?.delete_key(&lock_key.into()).await; Ok(match is_lock_released { Ok(_del_reply) => true, Err(error) => { logger::error!(?error, %tag, "Error while releasing lock"); false } }) } async fn stream_append_entry( &self, stream: &str, entry_id: &RedisEntryId, fields: Vec<(&str, String)>, ) -> CustomResult<(), RedisError> { self.get_redis_conn()? .stream_append_entry(&stream.into(), entry_id, fields) .await } async fn get_key(&self, key: &str) -> CustomResult<Vec<u8>, RedisError> { self.get_redis_conn()?.get_key::<Vec<u8>>(&key.into()).await } } #[async_trait::async_trait] impl QueueInterface for MockDb { async fn fetch_consumer_tasks( &self, _stream_name: &str, _group_name: &str, _consumer_name: &str, ) -> CustomResult<Vec<storage::ProcessTracker>, ProcessTrackerError> { // [#172]: Implement function for `MockDb` Err(ProcessTrackerError::ResourceFetchingFailed { resource_name: "consumer_tasks".to_string(), })? } async fn consumer_group_create( &self, _stream: &str, _group: &str, _id: &RedisEntryId, ) -> CustomResult<(), RedisError> { // [#172]: Implement function for `MockDb` Err(RedisError::ConsumerGroupCreateFailed)? } async fn acquire_pt_lock( &self, _tag: &str, _lock_key: &str, _lock_val: &str, _ttl: i64, ) -> CustomResult<bool, RedisError> { // [#172]: Implement function for `MockDb` Ok(false) } async fn release_pt_lock(&self, _tag: &str, _lock_key: &str) -> CustomResult<bool, RedisError> { // [#172]: Implement function for `MockDb` Ok(false) } async fn stream_append_entry( &self, _stream: &str, _entry_id: &RedisEntryId, _fields: Vec<(&str, String)>, ) -> CustomResult<(), RedisError> { // [#172]: Implement function for `MockDb` Err(RedisError::StreamAppendFailed)? } async fn get_key(&self, _key: &str) -> CustomResult<Vec<u8>, RedisError> { Err(RedisError::RedisConnectionError.into()) } }
1,379
1,931
hyperswitch
crates/scheduler/src/configs/settings.rs
.rs
pub use router_env::config::{Log, LogConsole, LogFile, LogTelemetry}; use serde::Deserialize; #[derive(Debug, Clone, Deserialize)] #[serde(default)] pub struct SchedulerSettings { pub stream: String, pub producer: ProducerSettings, pub consumer: ConsumerSettings, pub loop_interval: u64, pub graceful_shutdown_interval: u64, pub server: Server, } #[derive(Debug, Deserialize, Clone)] #[serde(default)] pub struct Server { pub port: u16, pub workers: usize, pub host: String, } #[derive(Debug, Clone, Deserialize)] #[serde(default)] pub struct ProducerSettings { pub upper_fetch_limit: i64, pub lower_fetch_limit: i64, pub lock_key: String, pub lock_ttl: i64, pub batch_size: usize, } #[derive(Debug, Clone, Deserialize)] #[serde(default)] pub struct ConsumerSettings { pub disabled: bool, pub consumer_group: String, }
216
1,932
hyperswitch
crates/scheduler/src/configs/validations.rs
.rs
use common_utils::ext_traits::ConfigExt; use storage_impl::errors::ApplicationError; impl super::settings::SchedulerSettings { pub fn validate(&self) -> Result<(), ApplicationError> { use common_utils::fp_utils::when; when(self.stream.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "scheduler stream must not be empty".into(), )) })?; when(self.consumer.consumer_group.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "scheduler consumer group must not be empty".into(), )) })?; self.producer.validate()?; self.server.validate()?; Ok(()) } } impl super::settings::ProducerSettings { pub fn validate(&self) -> Result<(), ApplicationError> { common_utils::fp_utils::when(self.lock_key.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "producer lock key must not be empty".into(), )) }) } } impl super::settings::Server { pub fn validate(&self) -> Result<(), ApplicationError> { common_utils::fp_utils::when(self.host.is_default_or_empty(), || { Err(ApplicationError::InvalidConfigurationValueError( "server host must not be empty".into(), )) }) } }
282
1,933
hyperswitch
crates/scheduler/src/configs/defaults.rs
.rs
impl Default for super::settings::SchedulerSettings { fn default() -> Self { Self { stream: "SCHEDULER_STREAM".into(), producer: super::settings::ProducerSettings::default(), consumer: super::settings::ConsumerSettings::default(), graceful_shutdown_interval: 60000, loop_interval: 5000, server: super::settings::Server::default(), } } } impl Default for super::settings::ProducerSettings { fn default() -> Self { Self { upper_fetch_limit: 0, lower_fetch_limit: 1800, lock_key: "PRODUCER_LOCKING_KEY".into(), lock_ttl: 160, batch_size: 200, } } } impl Default for super::settings::ConsumerSettings { fn default() -> Self { Self { disabled: false, consumer_group: "SCHEDULER_GROUP".into(), } } } impl Default for super::settings::Server { fn default() -> Self { Self { port: 8080, workers: num_cpus::get_physical(), host: "localhost".into(), } } }
262
1,934
hyperswitch
crates/scheduler/src/consumer/workflows.rs
.rs
use async_trait::async_trait; use common_utils::errors::CustomResult; pub use diesel_models::process_tracker as storage; use diesel_models::process_tracker::business_status; use router_env::logger; use crate::{errors, SchedulerSessionState}; pub type WorkflowSelectorFn = fn(&storage::ProcessTracker) -> Result<(), errors::ProcessTrackerError>; #[async_trait] pub trait ProcessTrackerWorkflows<T>: Send + Sync { // The core execution of the workflow async fn trigger_workflow<'a>( &'a self, _state: &'a T, _process: storage::ProcessTracker, ) -> CustomResult<(), errors::ProcessTrackerError> { Err(errors::ProcessTrackerError::NotImplemented)? } async fn execute_workflow<'a>( &'a self, operation: Box<dyn ProcessTrackerWorkflow<T>>, state: &'a T, process: storage::ProcessTracker, ) -> CustomResult<(), errors::ProcessTrackerError> where T: SchedulerSessionState, { let app_state = &state.clone(); let output = operation.execute_workflow(app_state, process.clone()).await; match output { Ok(_) => operation.success_handler(app_state, process).await, Err(error) => match operation .error_handler(app_state, process.clone(), error) .await { Ok(_) => (), Err(error) => { logger::error!( ?error, "Failed to handle process tracker workflow execution error" ); let status = app_state .get_db() .as_scheduler() .finish_process_with_business_status( process, business_status::GLOBAL_FAILURE, ) .await; if let Err(error) = status { logger::error!(?error, "Failed to update process business status"); } } }, }; Ok(()) } } #[async_trait] pub trait ProcessTrackerWorkflow<T>: Send + Sync { /// The core execution of the workflow async fn execute_workflow<'a>( &'a self, _state: &'a T, _process: storage::ProcessTracker, ) -> Result<(), errors::ProcessTrackerError> { Err(errors::ProcessTrackerError::NotImplemented)? } /// Callback function after successful execution of the `execute_workflow` async fn success_handler<'a>(&'a self, _state: &'a T, _process: storage::ProcessTracker) {} /// Callback function after error received from `execute_workflow` async fn error_handler<'a>( &'a self, _state: &'a T, _process: storage::ProcessTracker, _error: errors::ProcessTrackerError, ) -> CustomResult<(), errors::ProcessTrackerError> { Err(errors::ProcessTrackerError::NotImplemented)? } }
597
1,935
hyperswitch
crates/scheduler/src/consumer/types.rs
.rs
pub mod batch; pub mod process_data; pub use self::batch::ProcessTrackerBatch;
19
1,936
hyperswitch
crates/scheduler/src/consumer/types/process_data.rs
.rs
use std::collections::HashMap; use diesel_models::enums; use serde::{Deserialize, Serialize}; #[derive(Serialize, Deserialize, Clone, Debug)] pub struct RetryMapping { pub start_after: i32, pub frequencies: Vec<(i32, i32)>, // (frequency, count) } #[derive(Serialize, Deserialize)] pub struct ConnectorPTMapping { pub default_mapping: RetryMapping, pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>, pub max_retries_count: i32, } impl Default for ConnectorPTMapping { fn default() -> Self { Self { custom_merchant_mapping: HashMap::new(), default_mapping: RetryMapping { start_after: 60, frequencies: vec![(300, 5)], }, max_retries_count: 5, } } } #[derive(Serialize, Deserialize)] pub struct PaymentMethodsPTMapping { pub default_mapping: RetryMapping, pub custom_pm_mapping: HashMap<enums::PaymentMethod, RetryMapping>, pub max_retries_count: i32, } impl Default for PaymentMethodsPTMapping { fn default() -> Self { Self { custom_pm_mapping: HashMap::new(), default_mapping: RetryMapping { start_after: 900, frequencies: vec![(300, 5)], }, max_retries_count: 5, } } } /// Configuration for outgoing webhook retries. #[derive(Debug, Serialize, Deserialize)] pub struct OutgoingWebhookRetryProcessTrackerMapping { /// Default (fallback) retry configuration used when no merchant-specific retry configuration /// exists. pub default_mapping: RetryMapping, /// Merchant-specific retry configuration. pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>, } impl Default for OutgoingWebhookRetryProcessTrackerMapping { fn default() -> Self { Self { default_mapping: RetryMapping { // 1st attempt happens after 1 minute start_after: 60, frequencies: vec![ // 2nd and 3rd attempts happen at intervals of 5 minutes each (60 * 5, 2), // 4th, 5th, 6th, 7th and 8th attempts happen at intervals of 10 minutes each (60 * 10, 5), // 9th, 10th, 11th, 12th and 13th attempts happen at intervals of 1 hour each (60 * 60, 5), // 14th, 15th and 16th attempts happen at intervals of 6 hours each (60 * 60 * 6, 3), ], }, custom_merchant_mapping: HashMap::new(), } } } /// Configuration for outgoing webhook retries. #[derive(Debug, Serialize, Deserialize)] pub struct RevenueRecoveryPaymentProcessTrackerMapping { /// Default (fallback) retry configuration used when no merchant-specific retry configuration /// exists. pub default_mapping: RetryMapping, /// Merchant-specific retry configuration. pub custom_merchant_mapping: HashMap<common_utils::id_type::MerchantId, RetryMapping>, } impl Default for RevenueRecoveryPaymentProcessTrackerMapping { fn default() -> Self { Self { default_mapping: RetryMapping { // 1st attempt happens after 1 minute of it being start_after: 60, frequencies: vec![ // 2nd and 3rd attempts happen at intervals of 3 hours each (60 * 60 * 3, 2), // 4th, 5th, 6th attempts happen at intervals of 6 hours each (60 * 60 * 6, 3), // 7th, 8th, 9th attempts happen at intervals of 9 hour each (60 * 60 * 9, 3), // 10th, 11th and 12th attempts happen at intervals of 12 hours each (60 * 60 * 12, 3), // 13th, 14th and 15th attempts happen at intervals of 18 hours each (60 * 60 * 18, 3), ], }, custom_merchant_mapping: HashMap::new(), } } }
985
1,937
hyperswitch
crates/scheduler/src/consumer/types/batch.rs
.rs
use std::collections::HashMap; use common_utils::{errors::CustomResult, ext_traits::OptionExt}; use diesel_models::process_tracker::ProcessTracker; use error_stack::ResultExt; use time::PrimitiveDateTime; use crate::errors; #[derive(Debug, Clone)] pub struct ProcessTrackerBatch { pub id: String, pub group_name: String, pub stream_name: String, pub connection_name: String, pub created_time: PrimitiveDateTime, pub rule: String, // is it required? pub trackers: Vec<ProcessTracker>, /* FIXME: Add sized also here, list */ } impl ProcessTrackerBatch { pub fn to_redis_field_value_pairs( &self, ) -> CustomResult<Vec<(&str, String)>, errors::ProcessTrackerError> { Ok(vec![ ("id", self.id.to_string()), ("group_name", self.group_name.to_string()), ("stream_name", self.stream_name.to_string()), ("connection_name", self.connection_name.to_string()), ( "created_time", self.created_time.assume_utc().unix_timestamp().to_string(), ), ("rule", self.rule.to_string()), ( "trackers", serde_json::to_string(&self.trackers) .change_context(errors::ProcessTrackerError::SerializationFailed) .attach_printable_lazy(|| { format!("Unable to stringify trackers: {:?}", self.trackers) })?, ), ]) } pub fn from_redis_stream_entry( entry: HashMap<String, Option<String>>, ) -> CustomResult<Self, errors::ProcessTrackerError> { let mut entry = entry; let id = entry .remove("id") .flatten() .get_required_value("id") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let group_name = entry .remove("group_name") .flatten() .get_required_value("group_name") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let stream_name = entry .remove("stream_name") .flatten() .get_required_value("stream_name") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let connection_name = entry .remove("connection_name") .flatten() .get_required_value("connection_name") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let created_time = entry .remove("created_time") .flatten() .get_required_value("created_time") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; //make it parser error let created_time = { let offset_date_time = time::OffsetDateTime::from_unix_timestamp( created_time .as_str() .parse::<i64>() .change_context(errors::ParsingError::UnknownError) .change_context(errors::ProcessTrackerError::DeserializationFailed)?, ) .attach_printable_lazy(|| format!("Unable to parse time {}", &created_time)) .change_context(errors::ProcessTrackerError::MissingRequiredField)?; PrimitiveDateTime::new(offset_date_time.date(), offset_date_time.time()) }; let rule = entry .remove("rule") .flatten() .get_required_value("rule") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let trackers = entry .remove("trackers") .flatten() .get_required_value("trackers") .change_context(errors::ProcessTrackerError::MissingRequiredField)?; let trackers = serde_json::from_str::<Vec<ProcessTracker>>(trackers.as_str()) .change_context(errors::ParsingError::UnknownError) .attach_printable_lazy(|| { format!("Unable to parse trackers from JSON string: {trackers:?}") }) .change_context(errors::ProcessTrackerError::DeserializationFailed) .attach_printable("Error parsing ProcessTracker from redis stream entry")?; Ok(Self { id, group_name, stream_name, connection_name, created_time, rule, trackers, }) } }
870
1,938
hyperswitch
crates/api_models/Cargo.toml
.toml
[package] name = "api_models" description = "Request/response models for the `router` crate" version = "0.1.0" edition.workspace = true rust-version.workspace = true readme = "README.md" license.workspace = true [features] errors = ["dep:actix-web", "dep:reqwest"] dummy_connector = ["euclid/dummy_connector", "common_enums/dummy_connector"] detailed_errors = [] payouts = ["common_enums/payouts"] frm = [] olap = [] openapi = ["common_enums/openapi", "olap", "recon", "dummy_connector", "olap"] recon = [] v1 = ["common_utils/v1"] v2 = ["common_types/v2", "common_utils/v2", "customer_v2"] customer_v2 = ["common_utils/customer_v2"] payment_methods_v2 = ["common_utils/payment_methods_v2"] dynamic_routing = [] control_center_theme = ["dep:actix-web", "dep:actix-multipart"] revenue_recovery = [] [dependencies] actix-multipart = { version = "0.6.1", optional = true } actix-web = { version = "4.5.1", optional = true } error-stack = "0.4.1" indexmap = "2.3.0" mime = "0.3.17" reqwest = { version = "0.11.27", optional = true } serde = { version = "1.0.197", features = ["derive"] } serde_json = "1.0.115" strum = { version = "0.26", features = ["derive"] } time = { version = "0.3.35", features = ["serde", "serde-well-known", "std"] } url = { version = "2.5.0", features = ["serde"] } utoipa = { version = "4.2.0", features = ["preserve_order", "preserve_path_order"] } rustc-hash = "1.1.0" nutype = { version = "0.4.2", features = ["serde"] } # First party crates cards = { version = "0.1.0", path = "../cards" } common_enums = { version = "0.1.0", path = "../common_enums" } common_types = { version = "0.1.0", path = "../common_types" } common_utils = { version = "0.1.0", path = "../common_utils" } euclid = { version = "0.1.0", path = "../euclid" } masking = { version = "0.1.0", path = "../masking", default-features = false, features = ["alloc", "serde"] } router_derive = { version = "0.1.0", path = "../router_derive" } [lints] workspace = true
633
1,939
hyperswitch
crates/api_models/README.md
.md
# API Models Request/response models for the `router` crate.
14
1,940
hyperswitch
crates/api_models/src/apple_pay_certificates_migration.rs
.rs
#[derive(Debug, Clone, serde::Serialize)] pub struct ApplePayCertificatesMigrationResponse { pub migration_successful: Vec<common_utils::id_type::MerchantId>, pub migration_failed: Vec<common_utils::id_type::MerchantId>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct ApplePayCertificatesMigrationRequest { pub merchant_ids: Vec<common_utils::id_type::MerchantId>, } impl common_utils::events::ApiEventMetric for ApplePayCertificatesMigrationRequest {}
110
1,941
hyperswitch
crates/api_models/src/organization.rs
.rs
use common_utils::{id_type, pii}; use utoipa::ToSchema; pub struct OrganizationNew { pub org_id: id_type::OrganizationId, pub org_name: Option<String>, } impl OrganizationNew { pub fn new(org_name: Option<String>) -> Self { Self { org_id: id_type::OrganizationId::default(), org_name, } } } #[derive(Clone, Debug, serde::Serialize)] pub struct OrganizationId { pub organization_id: id_type::OrganizationId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OrganizationCreateRequest { /// Name of the organization pub organization_name: String, /// Details about the organization #[schema(value_type = Option<Object>)] pub organization_details: Option<pii::SecretSerdeValue>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OrganizationUpdateRequest { /// Name of the organization pub organization_name: Option<String>, /// Details about the organization #[schema(value_type = Option<Object>)] pub organization_details: Option<pii::SecretSerdeValue>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct OrganizationResponse { /// The unique identifier for the Organization #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub organization_id: id_type::OrganizationId, /// Name of the Organization pub organization_name: Option<String>, /// Details about the organization #[schema(value_type = Option<Object>)] pub organization_details: Option<pii::SecretSerdeValue>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: time::PrimitiveDateTime, pub created_at: time::PrimitiveDateTime, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct OrganizationResponse { /// The unique identifier for the Organization #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub id: id_type::OrganizationId, /// Name of the Organization pub organization_name: Option<String>, /// Details about the organization #[schema(value_type = Option<Object>)] pub organization_details: Option<pii::SecretSerdeValue>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, pub modified_at: time::PrimitiveDateTime, pub created_at: time::PrimitiveDateTime, }
733
1,942
hyperswitch
crates/api_models/src/external_service_auth.rs
.rs
use common_utils::{id_type, pii}; use masking::Secret; #[derive(Debug, serde::Serialize)] pub struct ExternalTokenResponse { pub token: Secret<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct ExternalVerifyTokenRequest { pub token: Secret<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct ExternalSignoutTokenRequest { pub token: Secret<String>, } #[derive(serde::Serialize, Debug)] #[serde(untagged)] pub enum ExternalVerifyTokenResponse { Hypersense { user_id: String, merchant_id: id_type::MerchantId, name: Secret<String>, email: pii::Email, }, } impl ExternalVerifyTokenResponse { pub fn get_user_id(&self) -> &str { match self { Self::Hypersense { user_id, .. } => user_id, } } }
195
1,943
hyperswitch
crates/api_models/src/enums.rs
.rs
use std::str::FromStr; pub use common_enums::*; use utoipa::ToSchema; pub use super::connector_enums::Connector; #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, )] /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingAlgorithm { RoundRobin, MaxConversion, MinCost, Custom, } #[cfg(feature = "payouts")] #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PayoutConnectors { Adyen, Adyenplatform, Cybersource, Ebanx, Nomupay, Payone, Paypal, Stripe, Wise, } #[cfg(feature = "v2")] /// Whether active attempt is to be set/unset #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum UpdateActiveAttempt { /// Request to set the active attempt id #[schema(value_type = Option<String>)] Set(common_utils::id_type::GlobalAttemptId), /// To unset the active attempt id Unset, } #[cfg(feature = "payouts")] impl From<PayoutConnectors> for RoutableConnectors { fn from(value: PayoutConnectors) -> Self { match value { PayoutConnectors::Adyen => Self::Adyen, PayoutConnectors::Adyenplatform => Self::Adyenplatform, PayoutConnectors::Cybersource => Self::Cybersource, PayoutConnectors::Ebanx => Self::Ebanx, PayoutConnectors::Nomupay => Self::Nomupay, PayoutConnectors::Payone => Self::Payone, PayoutConnectors::Paypal => Self::Paypal, PayoutConnectors::Stripe => Self::Stripe, PayoutConnectors::Wise => Self::Wise, } } } #[cfg(feature = "payouts")] impl From<PayoutConnectors> for Connector { fn from(value: PayoutConnectors) -> Self { match value { PayoutConnectors::Adyen => Self::Adyen, PayoutConnectors::Adyenplatform => Self::Adyenplatform, PayoutConnectors::Cybersource => Self::Cybersource, PayoutConnectors::Ebanx => Self::Ebanx, PayoutConnectors::Nomupay => Self::Nomupay, PayoutConnectors::Payone => Self::Payone, PayoutConnectors::Paypal => Self::Paypal, PayoutConnectors::Stripe => Self::Stripe, PayoutConnectors::Wise => Self::Wise, } } } #[cfg(feature = "payouts")] impl TryFrom<Connector> for PayoutConnectors { type Error = String; fn try_from(value: Connector) -> Result<Self, Self::Error> { match value { Connector::Adyen => Ok(Self::Adyen), Connector::Adyenplatform => Ok(Self::Adyenplatform), Connector::Cybersource => Ok(Self::Cybersource), Connector::Ebanx => Ok(Self::Ebanx), Connector::Nomupay => Ok(Self::Nomupay), Connector::Payone => Ok(Self::Payone), Connector::Paypal => Ok(Self::Paypal), Connector::Stripe => Ok(Self::Stripe), Connector::Wise => Ok(Self::Wise), _ => Err(format!("Invalid payout connector {}", value)), } } } #[cfg(feature = "frm")] #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmConnectors { /// Signifyd Risk Manager. Official docs: https://docs.signifyd.com/ Signifyd, Riskified, } #[derive( Clone, Copy, Debug, Eq, Hash, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum TaxConnectors { Taxjar, } #[derive(Clone, Debug, serde::Serialize, strum::EnumString)] #[serde(rename_all = "snake_case")] pub enum BillingConnectors { Chargebee, } #[derive( Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FrmAction { CancelTxn, AutoRefund, ManualReview, } #[derive( Clone, Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FrmPreferredFlowTypes { Pre, Post, } #[derive(Debug, Eq, PartialEq, Clone, serde::Serialize, serde::Deserialize)] pub struct UnresolvedResponseReason { pub code: String, /// A message to merchant to give hint on next action he/she should do to resolve pub message: String, } /// Possible field type of required fields in payment_method_data #[derive( Clone, Debug, Eq, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FieldType { UserCardNumber, UserCardExpiryMonth, UserCardExpiryYear, UserCardCvc, UserCardNetwork, UserFullName, UserEmailAddress, UserPhoneNumber, UserPhoneNumberCountryCode, //phone number's country code UserCountry { options: Vec<String> }, //for country inside payment method data ex- bank redirect UserCurrency { options: Vec<String> }, UserCryptoCurrencyNetwork, //for crypto network associated with the cryptopcurrency UserBillingName, UserAddressLine1, UserAddressLine2, UserAddressCity, UserAddressPincode, UserAddressState, UserAddressCountry { options: Vec<String> }, UserShippingName, UserShippingAddressLine1, UserShippingAddressLine2, UserShippingAddressCity, UserShippingAddressPincode, UserShippingAddressState, UserShippingAddressCountry { options: Vec<String> }, UserSocialSecurityNumber, UserBlikCode, UserBank, UserBankAccountNumber, Text, DropDown { options: Vec<String> }, UserDateOfBirth, UserVpaId, LanguagePreference { options: Vec<String> }, UserPixKey, UserCpf, UserCnpj, UserIban, UserBsbNumber, UserBankSortCode, UserBankRoutingNumber, UserMsisdn, UserClientIdentifier, OrderDetailsProductName, } impl FieldType { pub fn get_billing_variants() -> Vec<Self> { vec![ Self::UserBillingName, Self::UserAddressLine1, Self::UserAddressLine2, Self::UserAddressCity, Self::UserAddressPincode, Self::UserAddressState, Self::UserAddressCountry { options: vec![] }, ] } pub fn get_shipping_variants() -> Vec<Self> { vec![ Self::UserShippingName, Self::UserShippingAddressLine1, Self::UserShippingAddressLine2, Self::UserShippingAddressCity, Self::UserShippingAddressPincode, Self::UserShippingAddressState, Self::UserShippingAddressCountry { options: vec![] }, ] } } /// This implementatiobn is to ignore the inner value of UserAddressCountry enum while comparing impl PartialEq for FieldType { fn eq(&self, other: &Self) -> bool { match (self, other) { (Self::UserCardNumber, Self::UserCardNumber) => true, (Self::UserCardExpiryMonth, Self::UserCardExpiryMonth) => true, (Self::UserCardExpiryYear, Self::UserCardExpiryYear) => true, (Self::UserCardCvc, Self::UserCardCvc) => true, (Self::UserFullName, Self::UserFullName) => true, (Self::UserEmailAddress, Self::UserEmailAddress) => true, (Self::UserPhoneNumber, Self::UserPhoneNumber) => true, (Self::UserPhoneNumberCountryCode, Self::UserPhoneNumberCountryCode) => true, ( Self::UserCountry { options: options_self, }, Self::UserCountry { options: options_other, }, ) => options_self.eq(options_other), ( Self::UserCurrency { options: options_self, }, Self::UserCurrency { options: options_other, }, ) => options_self.eq(options_other), (Self::UserCryptoCurrencyNetwork, Self::UserCryptoCurrencyNetwork) => true, (Self::UserBillingName, Self::UserBillingName) => true, (Self::UserAddressLine1, Self::UserAddressLine1) => true, (Self::UserAddressLine2, Self::UserAddressLine2) => true, (Self::UserAddressCity, Self::UserAddressCity) => true, (Self::UserAddressPincode, Self::UserAddressPincode) => true, (Self::UserAddressState, Self::UserAddressState) => true, (Self::UserAddressCountry { .. }, Self::UserAddressCountry { .. }) => true, (Self::UserShippingName, Self::UserShippingName) => true, (Self::UserShippingAddressLine1, Self::UserShippingAddressLine1) => true, (Self::UserShippingAddressLine2, Self::UserShippingAddressLine2) => true, (Self::UserShippingAddressCity, Self::UserShippingAddressCity) => true, (Self::UserShippingAddressPincode, Self::UserShippingAddressPincode) => true, (Self::UserShippingAddressState, Self::UserShippingAddressState) => true, (Self::UserShippingAddressCountry { .. }, Self::UserShippingAddressCountry { .. }) => { true } (Self::UserBlikCode, Self::UserBlikCode) => true, (Self::UserBank, Self::UserBank) => true, (Self::Text, Self::Text) => true, ( Self::DropDown { options: options_self, }, Self::DropDown { options: options_other, }, ) => options_self.eq(options_other), (Self::UserDateOfBirth, Self::UserDateOfBirth) => true, (Self::UserVpaId, Self::UserVpaId) => true, (Self::UserPixKey, Self::UserPixKey) => true, (Self::UserCpf, Self::UserCpf) => true, (Self::UserCnpj, Self::UserCnpj) => true, (Self::LanguagePreference { .. }, Self::LanguagePreference { .. }) => true, (Self::UserMsisdn, Self::UserMsisdn) => true, (Self::UserClientIdentifier, Self::UserClientIdentifier) => true, (Self::OrderDetailsProductName, Self::OrderDetailsProductName) => true, _unused => false, } } } #[cfg(test)] mod test { use super::*; #[test] fn test_partialeq_for_field_type() { let user_address_country_is_us = FieldType::UserAddressCountry { options: vec!["US".to_string()], }; let user_address_country_is_all = FieldType::UserAddressCountry { options: vec!["ALL".to_string()], }; assert!(user_address_country_is_us.eq(&user_address_country_is_all)) } } /// Denotes the retry action #[derive( Debug, serde::Deserialize, serde::Serialize, strum::Display, strum::EnumString, Clone, PartialEq, Eq, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RetryAction { /// Payment can be retried from the client side until the payment is successful or payment expires or the attempts(configured by the merchant) for payment are exhausted ManualRetry, /// Denotes that the payment is requeued Requeue, } #[derive(Clone, Copy)] pub enum LockerChoice { HyperswitchCardVault, } #[derive( Clone, Copy, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum PmAuthConnectors { Plaid, } pub fn convert_pm_auth_connector(connector_name: &str) -> Option<PmAuthConnectors> { PmAuthConnectors::from_str(connector_name).ok() } pub fn convert_authentication_connector(connector_name: &str) -> Option<AuthenticationConnectors> { AuthenticationConnectors::from_str(connector_name).ok() } pub fn convert_tax_connector(connector_name: &str) -> Option<TaxConnectors> { TaxConnectors::from_str(connector_name).ok() } pub fn convert_billing_connector(connector_name: &str) -> Option<BillingConnectors> { BillingConnectors::from_str(connector_name).ok() } #[cfg(feature = "frm")] pub fn convert_frm_connector(connector_name: &str) -> Option<FrmConnectors> { FrmConnectors::from_str(connector_name).ok() } #[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, serde::Serialize, Hash)] pub enum ReconPermissionScope { #[serde(rename = "R")] Read = 0, #[serde(rename = "RW")] Write = 1, } impl From<PermissionScope> for ReconPermissionScope { fn from(scope: PermissionScope) -> Self { match scope { PermissionScope::Read => Self::Read, PermissionScope::Write => Self::Write, } } }
3,285
1,944
hyperswitch
crates/api_models/src/disputes.rs
.rs
use std::collections::HashMap; use common_utils::types::TimeRange; use masking::{Deserialize, Serialize}; use serde::de::Error; use time::PrimitiveDateTime; use utoipa::ToSchema; use super::enums::{Currency, DisputeStage, DisputeStatus}; use crate::{admin::MerchantConnectorInfo, files}; #[derive(Clone, Debug, Serialize, ToSchema, Eq, PartialEq)] pub struct DisputeResponse { /// The identifier for dispute pub dispute_id: String, /// The identifier for payment_intent #[schema(value_type = String)] pub payment_id: common_utils::id_type::PaymentId, /// The identifier for payment_attempt pub attempt_id: String, /// The dispute amount pub amount: String, /// The three-letter ISO currency code #[schema(value_type = Currency)] pub currency: Currency, /// Stage of the dispute pub dispute_stage: DisputeStage, /// Status of the dispute pub dispute_status: DisputeStatus, /// connector to which dispute is associated with pub connector: String, /// Status of the dispute sent by connector pub connector_status: String, /// Dispute id sent by connector pub connector_dispute_id: String, /// Reason of dispute sent by connector pub connector_reason: Option<String>, /// Reason code of dispute sent by connector pub connector_reason_code: Option<String>, /// Evidence deadline of dispute sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub challenge_required_by: Option<PrimitiveDateTime>, /// Dispute created time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_created_at: Option<PrimitiveDateTime>, /// Dispute updated time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_updated_at: Option<PrimitiveDateTime>, /// Time at which dispute is received #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// The `profile_id` associated with the dispute #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// The `merchant_connector_id` of the connector / processor through which the dispute was processed #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Clone, Debug, Serialize, ToSchema, Eq, PartialEq)] pub struct DisputeResponsePaymentsRetrieve { /// The identifier for dispute pub dispute_id: String, /// Stage of the dispute pub dispute_stage: DisputeStage, /// Status of the dispute pub dispute_status: DisputeStatus, /// Status of the dispute sent by connector pub connector_status: String, /// Dispute id sent by connector pub connector_dispute_id: String, /// Reason of dispute sent by connector pub connector_reason: Option<String>, /// Reason code of dispute sent by connector pub connector_reason_code: Option<String>, /// Evidence deadline of dispute sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub challenge_required_by: Option<PrimitiveDateTime>, /// Dispute created time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_created_at: Option<PrimitiveDateTime>, /// Dispute updated time sent by connector #[serde(with = "common_utils::custom_serde::iso8601::option")] pub connector_updated_at: Option<PrimitiveDateTime>, /// Time at which dispute is received #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, } #[derive(Debug, Serialize, Deserialize, strum::Display, Clone)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum EvidenceType { CancellationPolicy, CustomerCommunication, CustomerSignature, Receipt, RefundPolicy, ServiceDocumentation, ShippingDocumentation, InvoiceShowingDistinctTransactions, RecurringTransactionAgreement, UncategorizedFile, } #[derive(Clone, Debug, Serialize, ToSchema)] pub struct DisputeEvidenceBlock { /// Evidence type pub evidence_type: EvidenceType, /// File metadata pub file_metadata_response: files::FileMetadataResponse, } #[derive(Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct DisputeListGetConstraints { /// The identifier for dispute pub dispute_id: Option<String>, /// The payment_id against which dispute is raised pub payment_id: Option<common_utils::id_type::PaymentId>, /// Limit on the number of objects to return pub limit: Option<u32>, /// The starting point within a list of object pub offset: Option<u32>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// The comma separated list of status of the disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub dispute_status: Option<Vec<DisputeStatus>>, /// The comma separated list of stages of the disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub dispute_stage: Option<Vec<DisputeStage>>, /// Reason for the dispute pub reason: Option<String>, /// The comma separated list of connectors linked to disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub connector: Option<Vec<String>>, /// The comma separated list of currencies of the disputes #[serde(default, deserialize_with = "parse_comma_separated")] pub currency: Option<Vec<Currency>>, /// The merchant connector id to filter the disputes list pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<TimeRange>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct DisputeListFilters { /// The map of available connector filters, where the key is the connector name and the value is a list of MerchantConnectorInfo instances pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<Currency>, /// The list of available dispute status filters pub dispute_status: Vec<DisputeStatus>, /// The list of available dispute stage filters pub dispute_stage: Vec<DisputeStage>, } #[derive(Default, Clone, Debug, Serialize, Deserialize, ToSchema)] pub struct SubmitEvidenceRequest { ///Dispute Id pub dispute_id: String, /// Logs showing the usage of service by customer pub access_activity_log: Option<String>, /// Billing address of the customer pub billing_address: Option<String>, /// File Id of cancellation policy pub cancellation_policy: Option<String>, /// Details of showing cancellation policy to customer before purchase pub cancellation_policy_disclosure: Option<String>, /// Details telling why customer's subscription was not cancelled pub cancellation_rebuttal: Option<String>, /// File Id of customer communication pub customer_communication: Option<String>, /// Customer email address pub customer_email_address: Option<String>, /// Customer name pub customer_name: Option<String>, /// IP address of the customer pub customer_purchase_ip: Option<String>, /// Fild Id of customer signature pub customer_signature: Option<String>, /// Product Description pub product_description: Option<String>, /// File Id of receipt pub receipt: Option<String>, /// File Id of refund policy pub refund_policy: Option<String>, /// Details of showing refund policy to customer before purchase pub refund_policy_disclosure: Option<String>, /// Details why customer is not entitled to refund pub refund_refusal_explanation: Option<String>, /// Customer service date pub service_date: Option<String>, /// File Id service documentation pub service_documentation: Option<String>, /// Shipping address of the customer pub shipping_address: Option<String>, /// Delivery service that shipped the product pub shipping_carrier: Option<String>, /// Shipping date pub shipping_date: Option<String>, /// File Id shipping documentation pub shipping_documentation: Option<String>, /// Tracking number of shipped product pub shipping_tracking_number: Option<String>, /// File Id showing two distinct transactions when customer claims a payment was charged twice pub invoice_showing_distinct_transactions: Option<String>, /// File Id of recurring transaction agreement pub recurring_transaction_agreement: Option<String>, /// Any additional supporting file pub uncategorized_file: Option<String>, /// Any additional evidence statements pub uncategorized_text: Option<String>, } #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] pub struct DeleteEvidenceRequest { /// Id of the dispute pub dispute_id: String, /// Evidence Type to be deleted pub evidence_type: EvidenceType, } #[derive(Clone, Debug, serde::Serialize)] pub struct DisputesAggregateResponse { /// Different status of disputes with their count pub status_with_count: HashMap<DisputeStatus, i64>, } fn parse_comma_separated<'de, D, T>(v: D) -> Result<Option<Vec<T>>, D::Error> where D: serde::Deserializer<'de>, T: std::str::FromStr, <T as std::str::FromStr>::Err: std::fmt::Debug + std::fmt::Display + std::error::Error, { let output = Option::<&str>::deserialize(v)?; output .map(|s| { s.split(",") .map(|x| x.parse::<T>().map_err(D::Error::custom)) .collect::<Result<_, _>>() }) .transpose() }
2,234
1,945
hyperswitch
crates/api_models/src/connector_onboarding.rs
.rs
use common_utils::id_type; use super::{admin, enums}; #[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] pub struct ActionUrlRequest { pub connector: enums::Connector, pub connector_id: id_type::MerchantConnectorAccountId, pub return_url: String, } #[derive(serde::Serialize, Debug, Clone)] #[serde(rename_all = "lowercase")] pub enum ActionUrlResponse { PayPal(PayPalActionUrlResponse), } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] pub struct OnboardingSyncRequest { pub profile_id: id_type::ProfileId, pub connector_id: id_type::MerchantConnectorAccountId, pub connector: enums::Connector, } #[derive(serde::Serialize, Debug, Clone)] pub struct PayPalActionUrlResponse { pub action_url: String, } #[derive(serde::Serialize, Debug, Clone)] #[serde(rename_all = "lowercase")] pub enum OnboardingStatus { PayPal(PayPalOnboardingStatus), } #[derive(serde::Serialize, Debug, Clone)] #[serde(rename_all = "snake_case")] pub enum PayPalOnboardingStatus { AccountNotFound, PaymentsNotReceivable, PpcpCustomDenied, MorePermissionsNeeded, EmailNotVerified, Success(PayPalOnboardingDone), ConnectorIntegrated(Box<admin::MerchantConnectorResponse>), } #[derive(serde::Serialize, Debug, Clone)] pub struct PayPalOnboardingDone { pub payer_id: id_type::MerchantId, } #[derive(serde::Serialize, Debug, Clone)] pub struct PayPalIntegrationDone { pub connector_id: String, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone)] pub struct ResetTrackingIdRequest { pub connector_id: id_type::MerchantConnectorAccountId, pub connector: enums::Connector, }
390
1,946
hyperswitch
crates/api_models/src/api_keys.rs
.rs
use common_utils::custom_serde; use masking::StrongSecret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; /// The request body for creating an API Key. #[derive(Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct CreateApiKeyRequest { /// A unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: String, /// A description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// An expiration date for the API Key. Although we allow keys to never expire, we recommend /// rotating your keys once every 6 months. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: ApiKeyExpiration, } /// The response body for creating an API Key. #[derive(Debug, Serialize, ToSchema)] pub struct CreateApiKeyResponse { /// The identifier for the API Key. #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: String, /// The description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// The plaintext API Key used for server-side API access. Ensure you store the API Key /// securely as you will not be able to see it again. #[schema(value_type = String, max_length = 128)] pub api_key: StrongSecret<String>, /// The time at which the API Key was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The expiration date for the API Key. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: ApiKeyExpiration, /* /// The date and time indicating when the API Key was last used. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_used: Option<PrimitiveDateTime>, */ } /// The response body for retrieving an API Key. #[derive(Debug, Serialize, ToSchema)] pub struct RetrieveApiKeyResponse { /// The identifier for the API Key. #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: String, /// The description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// The first few characters of the plaintext API Key to help you identify it. #[schema(value_type = String, max_length = 64)] pub prefix: StrongSecret<String>, /// The time at which the API Key was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The expiration date for the API Key. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: ApiKeyExpiration, /* /// The date and time indicating when the API Key was last used. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub last_used: Option<PrimitiveDateTime>, */ } /// The request body for updating an API Key. #[derive(Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct UpdateApiKeyRequest { /// A unique name for the API Key to help you identify it. #[schema(max_length = 64, example = "Sandbox integration key")] pub name: Option<String>, /// A description to provide more context about the API Key. #[schema( max_length = 256, example = "Key used by our developers to integrate with the sandbox environment" )] pub description: Option<String>, /// An expiration date for the API Key. Although we allow keys to never expire, we recommend /// rotating your keys once every 6 months. #[schema(example = "2022-09-10T10:11:12Z")] pub expiration: Option<ApiKeyExpiration>, #[serde(skip_deserializing)] #[schema(value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, #[serde(skip_deserializing)] #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, } /// The response body for revoking an API Key. #[derive(Debug, Serialize, ToSchema)] pub struct RevokeApiKeyResponse { /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The identifier for the API Key. #[schema(max_length = 64, example = "5hEEqkgJUyuxgSKGArHA4mWSnX", value_type = String)] pub key_id: common_utils::id_type::ApiKeyId, /// Indicates whether the API key was revoked or not. #[schema(example = "true")] pub revoked: bool, } /// The constraints that are applicable when listing API Keys associated with a merchant account. #[derive(Clone, Debug, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct ListApiKeyConstraints { /// The maximum number of API Keys to include in the response. pub limit: Option<i64>, /// The number of API Keys to skip when retrieving the list of API keys. pub skip: Option<i64>, } /// The expiration date and time for an API Key. #[derive(Debug, Serialize, Deserialize, PartialEq)] #[serde(untagged)] pub enum ApiKeyExpiration { /// The API Key does not expire. #[serde(with = "never")] Never, /// The API Key expires at the specified date and time. #[serde(with = "custom_serde::iso8601")] DateTime(PrimitiveDateTime), } impl From<ApiKeyExpiration> for Option<PrimitiveDateTime> { fn from(expiration: ApiKeyExpiration) -> Self { match expiration { ApiKeyExpiration::Never => None, ApiKeyExpiration::DateTime(date_time) => Some(date_time), } } } impl From<Option<PrimitiveDateTime>> for ApiKeyExpiration { fn from(date_time: Option<PrimitiveDateTime>) -> Self { date_time.map_or(Self::Never, Self::DateTime) } } // This implementation is required as otherwise, `serde` would serialize and deserialize // `ApiKeyExpiration::Never` as `null`, which is not preferable. // Reference: https://github.com/serde-rs/serde/issues/1560#issuecomment-506915291 mod never { const NEVER: &str = "never"; pub fn serialize<S>(serializer: S) -> Result<S::Ok, S::Error> where S: serde::Serializer, { serializer.serialize_str(NEVER) } pub fn deserialize<'de, D>(deserializer: D) -> Result<(), D::Error> where D: serde::Deserializer<'de>, { struct NeverVisitor; impl serde::de::Visitor<'_> for NeverVisitor { type Value = (); fn expecting(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(f, r#""{NEVER}""#) } fn visit_str<E: serde::de::Error>(self, value: &str) -> Result<Self::Value, E> { if value == NEVER { Ok(()) } else { Err(E::invalid_value(serde::de::Unexpected::Str(value), &self)) } } } deserializer.deserialize_str(NeverVisitor) } } impl<'a> ToSchema<'a> for ApiKeyExpiration { fn schema() -> ( &'a str, utoipa::openapi::RefOr<utoipa::openapi::schema::Schema>, ) { use utoipa::openapi::{KnownFormat, ObjectBuilder, OneOfBuilder, SchemaFormat, SchemaType}; ( "ApiKeyExpiration", OneOfBuilder::new() .item( ObjectBuilder::new() .schema_type(SchemaType::String) .enum_values(Some(["never"])), ) .item( ObjectBuilder::new() .schema_type(SchemaType::String) .format(Some(SchemaFormat::KnownFormat(KnownFormat::DateTime))), ) .into(), ) } } #[cfg(test)] mod api_key_expiration_tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_serialization() { assert_eq!( serde_json::to_string(&ApiKeyExpiration::Never).unwrap(), r#""never""# ); let date = time::Date::from_calendar_date(2022, time::Month::September, 10).unwrap(); let time = time::Time::from_hms(11, 12, 13).unwrap(); assert_eq!( serde_json::to_string(&ApiKeyExpiration::DateTime(PrimitiveDateTime::new( date, time ))) .unwrap(), r#""2022-09-10T11:12:13.000Z""# ); } #[test] fn test_deserialization() { assert_eq!( serde_json::from_str::<ApiKeyExpiration>(r#""never""#).unwrap(), ApiKeyExpiration::Never ); let date = time::Date::from_calendar_date(2022, time::Month::September, 10).unwrap(); let time = time::Time::from_hms(11, 12, 13).unwrap(); assert_eq!( serde_json::from_str::<ApiKeyExpiration>(r#""2022-09-10T11:12:13.000Z""#).unwrap(), ApiKeyExpiration::DateTime(PrimitiveDateTime::new(date, time)) ); } #[test] fn test_null() { let result = serde_json::from_str::<ApiKeyExpiration>("null"); assert!(result.is_err()); let result = serde_json::from_str::<Option<ApiKeyExpiration>>("null").unwrap(); assert_eq!(result, None); } }
2,766
1,947
hyperswitch
crates/api_models/src/relay.rs
.rs
use common_utils::types::MinorUnit; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::enums as api_enums; #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayRequest { /// The identifier that is associated to a resource at the connector reference to which the relay request is being made #[schema(example = "7256228702616471803954")] pub connector_resource_id: String, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub connector_id: common_utils::id_type::MerchantConnectorAccountId, /// The type of relay request #[serde(rename = "type")] #[schema(value_type = RelayType)] pub relay_type: api_enums::RelayType, /// The data that is associated with the relay request pub data: Option<RelayData>, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(rename_all = "snake_case")] pub enum RelayData { /// The data that is associated with a refund relay request Refund(RelayRefundRequestData), } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayRefundRequestData { /// The amount that is being refunded #[schema(value_type = i64 , example = 6540)] pub amount: MinorUnit, /// The currency in which the amount is being refunded #[schema(value_type = Currency)] pub currency: api_enums::Currency, /// The reason for the refund #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayResponse { /// The unique identifier for the Relay #[schema(example = "relay_mbabizu24mvu3mela5njyhpit4", value_type = String)] pub id: common_utils::id_type::RelayId, /// The status of the relay request #[schema(value_type = RelayStatus)] pub status: api_enums::RelayStatus, /// The identifier that is associated to a resource at the connector reference to which the relay request is being made #[schema(example = "pi_3MKEivSFNglxLpam0ZaL98q9")] pub connector_resource_id: String, /// The error details if the relay request failed pub error: Option<RelayError>, /// The identifier that is associated to a resource at the connector to which the relay request is being made #[schema(example = "re_3QY4TnEOqOywnAIx1Mm1p7GQ")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub connector_id: common_utils::id_type::MerchantConnectorAccountId, /// The business profile that is associated with this relay request. #[schema(example = "pro_abcdefghijklmnopqrstuvwxyz", value_type = String)] pub profile_id: common_utils::id_type::ProfileId, /// The type of relay request #[serde(rename = "type")] #[schema(value_type = RelayType)] pub relay_type: api_enums::RelayType, /// The data that is associated with the relay request pub data: Option<RelayData>, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayError { /// The error code pub code: String, /// The error message pub message: String, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayRetrieveRequest { /// The unique identifier for the Relay #[serde(default)] pub force_sync: bool, /// The unique identifier for the Relay pub id: common_utils::id_type::RelayId, } #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RelayRetrieveBody { /// The unique identifier for the Relay #[serde(default)] pub force_sync: bool, } impl common_utils::events::ApiEventMetric for RelayRequest {} impl common_utils::events::ApiEventMetric for RelayResponse {} impl common_utils::events::ApiEventMetric for RelayRetrieveRequest {} impl common_utils::events::ApiEventMetric for RelayRetrieveBody {}
1,019
1,948
hyperswitch
crates/api_models/src/currency.rs
.rs
use common_utils::{events::ApiEventMetric, types::MinorUnit}; /// QueryParams to be send to convert the amount -> from_currency -> to_currency #[derive(Debug, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct CurrencyConversionParams { pub amount: MinorUnit, pub to_currency: String, pub from_currency: String, } /// Response to be send for convert currency route #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct CurrencyConversionResponse { pub converted_amount: String, pub currency: String, } impl ApiEventMetric for CurrencyConversionResponse {} impl ApiEventMetric for CurrencyConversionParams {}
146
1,949
hyperswitch
crates/api_models/src/user.rs
.rs
use std::fmt::Debug; use common_enums::{EntityType, TokenPurpose}; use common_utils::{crypto::OptionalEncryptableName, id_type, pii}; use masking::Secret; use crate::user_role::UserStatus; pub mod dashboard_metadata; #[cfg(feature = "dummy_connector")] pub mod sample_data; #[cfg(feature = "control_center_theme")] pub mod theme; #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] pub struct SignUpWithMerchantIdRequest { pub name: Secret<String>, pub email: pii::Email, pub password: Secret<String>, pub company_name: String, } pub type SignUpWithMerchantIdResponse = AuthorizeResponse; #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] pub struct SignUpRequest { pub email: pii::Email, pub password: Secret<String>, } pub type SignInRequest = SignUpRequest; #[derive(serde::Deserialize, Debug, Clone, serde::Serialize)] pub struct ConnectAccountRequest { pub email: pii::Email, } pub type ConnectAccountResponse = AuthorizeResponse; #[derive(serde::Serialize, Debug, Clone)] pub struct AuthorizeResponse { pub is_email_sent: bool, //this field is added for audit/debug reasons #[serde(skip_serializing)] pub user_id: String, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct ChangePasswordRequest { pub new_password: Secret<String>, pub old_password: Secret<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct ForgotPasswordRequest { pub email: pii::Email, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct ResetPasswordRequest { pub token: Secret<String>, pub password: Secret<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct RotatePasswordRequest { pub password: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct InviteUserRequest { pub email: pii::Email, pub name: Secret<String>, pub role_id: String, } #[derive(Debug, serde::Serialize)] pub struct InviteMultipleUserResponse { pub email: pii::Email, pub is_email_sent: bool, #[serde(skip_serializing_if = "Option::is_none")] pub password: Option<Secret<String>>, #[serde(skip_serializing_if = "Option::is_none")] pub error: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct ReInviteUserRequest { pub email: pii::Email, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct AcceptInviteFromEmailRequest { pub token: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchOrganizationRequest { pub org_id: id_type::OrganizationId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchMerchantRequest { pub merchant_id: id_type::MerchantId, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SwitchProfileRequest { pub profile_id: id_type::ProfileId, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct CreateInternalUserRequest { pub name: Secret<String>, pub email: pii::Email, pub password: Secret<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct CreateTenantUserRequest { pub name: Secret<String>, pub email: pii::Email, pub password: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct UserOrgMerchantCreateRequest { pub organization_name: Secret<String>, pub organization_details: Option<pii::SecretSerdeValue>, pub metadata: Option<pii::SecretSerdeValue>, pub merchant_name: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserMerchantCreate { pub company_name: String, pub product_type: Option<common_enums::MerchantProductType>, } #[derive(serde::Serialize, Debug, Clone)] pub struct GetUserDetailsResponse { pub merchant_id: id_type::MerchantId, pub name: Secret<String>, pub email: pii::Email, pub verification_days_left: Option<i64>, pub role_id: String, // This field is added for audit/debug reasons #[serde(skip_serializing)] pub user_id: String, pub org_id: id_type::OrganizationId, pub is_two_factor_auth_setup: bool, pub recovery_codes_left: Option<usize>, pub profile_id: id_type::ProfileId, pub entity_type: EntityType, pub theme_id: Option<String>, pub version: common_enums::ApiVersion, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetUserRoleDetailsRequest { pub email: pii::Email, } #[derive(Debug, serde::Serialize)] pub struct GetUserRoleDetailsResponseV2 { pub role_id: String, pub org: NameIdUnit<Option<String>, id_type::OrganizationId>, pub merchant: Option<NameIdUnit<OptionalEncryptableName, id_type::MerchantId>>, pub profile: Option<NameIdUnit<String, id_type::ProfileId>>, pub status: UserStatus, pub entity_type: EntityType, pub role_name: String, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct NameIdUnit<N: Debug + Clone, I: Debug + Clone> { pub name: N, pub id: I, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyEmailRequest { pub token: Secret<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct SendVerifyEmailRequest { pub email: pii::Email, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UpdateUserAccountDetailsRequest { pub name: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SkipTwoFactorAuthQueryParam { pub skip_two_factor_auth: Option<bool>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TokenResponse { pub token: Secret<String>, pub token_type: TokenPurpose, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorAuthStatusResponse { pub totp: bool, pub recovery_code: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorAuthAttempts { pub is_completed: bool, pub remaining_attempts: u8, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorAuthStatusResponseWithAttempts { pub totp: TwoFactorAuthAttempts, pub recovery_code: TwoFactorAuthAttempts, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TwoFactorStatus { pub status: Option<TwoFactorAuthStatusResponseWithAttempts>, pub is_skippable: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserFromEmailRequest { pub token: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct BeginTotpResponse { pub secret: Option<TotpSecret>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct TotpSecret { pub secret: Secret<String>, pub totp_url: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyTotpRequest { pub totp: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyRecoveryCodeRequest { pub recovery_code: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct RecoveryCodes { pub recovery_codes: Vec<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(tag = "auth_type")] #[serde(rename_all = "snake_case")] pub enum AuthConfig { OpenIdConnect { private_config: OpenIdConnectPrivateConfig, public_config: OpenIdConnectPublicConfig, }, MagicLink, Password, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct OpenIdConnectPrivateConfig { pub base_url: String, pub client_id: Secret<String>, pub client_secret: Secret<String>, pub private_key: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct OpenIdConnectPublicConfig { pub name: OpenIdProvider, } #[derive( Debug, serde::Deserialize, serde::Serialize, Copy, Clone, strum::Display, Eq, PartialEq, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum OpenIdProvider { Okta, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct OpenIdConnect { pub name: OpenIdProvider, pub base_url: String, pub client_id: String, pub client_secret: Secret<String>, pub private_key: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CreateUserAuthenticationMethodRequest { pub owner_id: String, pub owner_type: common_enums::Owner, pub auth_method: AuthConfig, pub allow_signup: bool, pub email_domain: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum UpdateUserAuthenticationMethodRequest { AuthMethod { id: String, auth_config: AuthConfig, }, EmailDomain { owner_id: String, email_domain: String, }, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetUserAuthenticationMethodsRequest { pub auth_id: Option<String>, pub email_domain: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserAuthenticationMethodResponse { pub id: String, pub auth_id: String, pub auth_method: AuthMethodDetails, pub allow_signup: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AuthMethodDetails { #[serde(rename = "type")] pub auth_type: common_enums::UserAuthType, pub name: Option<OpenIdProvider>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetSsoAuthUrlRequest { pub id: String, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct SsoSignInRequest { pub state: Secret<String>, pub code: Secret<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AuthIdAndThemeIdQueryParam { pub auth_id: Option<String>, pub theme_id: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct AuthSelectRequest { pub id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct UserKeyTransferRequest { pub from: u32, pub limit: u32, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UserTransferKeyResponse { pub total_transferred: usize, } #[derive(Debug, serde::Serialize)] pub struct ListOrgsForUserResponse { pub org_id: id_type::OrganizationId, pub org_name: Option<String>, } #[derive(Debug, serde::Serialize)] pub struct UserMerchantAccountResponse { pub merchant_id: id_type::MerchantId, pub merchant_name: OptionalEncryptableName, pub product_type: Option<common_enums::MerchantProductType>, pub version: common_enums::ApiVersion, } #[derive(Debug, serde::Serialize)] pub struct ListProfilesForUserInOrgAndMerchantAccountResponse { pub profile_id: id_type::ProfileId, pub profile_name: String, }
2,538
1,950
hyperswitch
crates/api_models/src/health_check.rs
.rs
use std::collections::hash_map::HashMap; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RouterHealthCheckResponse { pub database: bool, pub redis: bool, #[serde(skip_serializing_if = "Option::is_none")] pub vault: Option<bool>, #[cfg(feature = "olap")] pub analytics: bool, #[cfg(feature = "olap")] pub opensearch: bool, pub outgoing_request: bool, #[cfg(feature = "dynamic_routing")] pub grpc_health_check: HealthCheckMap, } impl common_utils::events::ApiEventMetric for RouterHealthCheckResponse {} /// gRPC based services eligible for Health check #[derive(Debug, Clone, Eq, PartialEq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum HealthCheckServices { /// Dynamic routing service DynamicRoutingService, } pub type HealthCheckMap = HashMap<HealthCheckServices, bool>; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SchedulerHealthCheckResponse { pub database: bool, pub redis: bool, pub outgoing_request: bool, } pub enum HealthState { Running, Error, NotApplicable, } impl From<HealthState> for bool { fn from(value: HealthState) -> Self { match value { HealthState::Running => true, HealthState::Error | HealthState::NotApplicable => false, } } } impl From<HealthState> for Option<bool> { fn from(value: HealthState) -> Self { match value { HealthState::Running => Some(true), HealthState::Error => Some(false), HealthState::NotApplicable => None, } } } impl common_utils::events::ApiEventMetric for SchedulerHealthCheckResponse {}
393
1,951
hyperswitch
crates/api_models/src/verify_connector.rs
.rs
use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::{admin, enums}; #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct VerifyConnectorRequest { pub connector_name: enums::Connector, pub connector_account_details: admin::ConnectorAuthType, } common_utils::impl_api_event_type!(Miscellaneous, (VerifyConnectorRequest));
79
1,952
hyperswitch
crates/api_models/src/payments.rs
.rs
use std::{ collections::{HashMap, HashSet}, fmt, num::NonZeroI64, }; pub mod additional_info; pub mod trait_impls; use cards::CardNumber; #[cfg(feature = "v2")] use common_enums::enums::PaymentConnectorTransmission; use common_enums::ProductType; use common_types::primitive_wrappers::{ ExtendedAuthorizationAppliedBool, RequestExtendedAuthorizationBool, }; use common_utils::{ consts::default_payments_list_limit, crypto, errors::ValidationError, ext_traits::{ConfigExt, Encode, ValueExt}, hashing::HashedString, id_type, pii::{self, Email}, types::{MinorUnit, StringMajorUnit}, }; use error_stack::ResultExt; use masking::{PeekInterface, Secret, WithType}; use router_derive::Setter; use serde::{de, ser::Serializer, Deserialize, Deserializer, Serialize}; use strum::Display; use time::{Date, PrimitiveDateTime}; use url::Url; use utoipa::ToSchema; #[cfg(feature = "v1")] use crate::ephemeral_key::EphemeralKeyCreateResponse; #[cfg(feature = "v2")] use crate::mandates::ProcessorPaymentToken; #[cfg(feature = "v2")] use crate::payment_methods; use crate::{ admin::{self, MerchantConnectorInfo}, disputes, enums as api_enums, mandates::RecurringDetails, refunds, ValidateFieldAndGet, }; #[derive(Clone, Copy, Debug, Eq, PartialEq)] pub enum PaymentOp { Create, Update, Confirm, } use crate::enums; #[derive(serde::Deserialize)] pub struct BankData { pub payment_method_type: api_enums::PaymentMethodType, pub code_information: Vec<BankCodeInformation>, } #[derive(serde::Deserialize)] pub struct BankCodeInformation { pub bank_name: common_enums::BankNames, pub connector_codes: Vec<ConnectorCode>, } #[derive(serde::Deserialize)] pub struct ConnectorCode { pub connector: api_enums::Connector, pub code: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankCodeResponse { #[schema(value_type = Vec<BankNames>)] pub bank_name: Vec<common_enums::BankNames>, pub eligible_connectors: Vec<String>, } /// Passing this object creates a new customer or attaches an existing customer to the payment #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, PartialEq)] pub struct CustomerDetails { /// The identifier for the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v1")] /// Details of customer attached to this payment #[derive( Debug, Default, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter, )] pub struct CustomerDetailsResponse { /// The identifier for the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } #[cfg(feature = "v2")] /// Details of customer attached to this payment #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, PartialEq, Setter)] pub struct CustomerDetailsResponse { /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 10, example = "9123456789")] pub phone: Option<Secret<String>>, /// The country code for the customer's phone number #[schema(max_length = 2, example = "+1")] pub phone_country_code: Option<String>, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsCreateIntentRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl PaymentsCreateIntentRequest { pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<pii::SecretSerdeValue>, common_utils::errors::ParsingError, > { Ok(self .allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose()? .map(Secret::new)) } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } // This struct is only used internally, not visible in API Reference #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[cfg(feature = "v2")] pub struct PaymentsGetIntentRequest { pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsUpdateIntentRequest { pub amount_details: Option<AmountDetailsUpdate>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. This metadata will override the metadata that was passed in payments #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, /// Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, #[schema(value_type = Option<UpdateActiveAttempt>)] /// Whether to set / unset the active attempt id pub set_active_attempt_id: Option<api_enums::UpdateActiveAttempt>, } #[cfg(feature = "v2")] impl PaymentsUpdateIntentRequest { pub fn update_feature_metadata_and_active_attempt_with_api( feature_metadata: FeatureMetadata, set_active_attempt_id: api_enums::UpdateActiveAttempt, ) -> Self { Self { feature_metadata: Some(feature_metadata), set_active_attempt_id: Some(set_active_attempt_id), amount_details: None, routing_algorithm_id: None, capture_method: None, authentication_type: None, billing: None, shipping: None, customer_present: None, description: None, return_url: None, setup_future_usage: None, apply_mit_exemption: None, statement_descriptor: None, order_details: None, allowed_payment_method_types: None, metadata: None, connector_metadata: None, payment_link_config: None, request_incremental_authorization: None, session_expiry: None, frm_metadata: None, request_external_three_ds_authentication: None, } } } #[derive(Debug, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsIntentResponse { /// Global Payment Id for the payment #[schema(value_type = String)] pub id: id_type::GlobalPaymentId, /// The status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// The amount details for the payment pub amount_details: AmountDetailsResponse, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: common_utils::types::ClientSecret, /// The identifier for the profile. This is inferred from the `x-profile-id` header #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = CaptureMethod, example = "automatic")] pub capture_method: api_enums::CaptureMethod, /// The authentication type for the payment #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. #[schema(value_type = Option<Address>)] pub billing: Option<Address>, /// The shipping address for the payment #[schema(value_type = Option<Address>)] pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = PresenceOfCustomerDuringPayment)] pub customer_present: common_enums::PresenceOfCustomerDuringPayment, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = FutureUsage, example = "off_session")] pub setup_future_usage: api_enums::FutureUsage, /// Apply MIT exemption for a payment #[schema(value_type = MitExemptionRequest)] pub apply_mit_exemption: common_enums::MitExemptionRequest, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = EnablePaymentLinkRequest)] pub payment_link_enabled: common_enums::EnablePaymentLinkRequest, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = RequestIncrementalAuthorization)] pub request_incremental_authorization: common_enums::RequestIncrementalAuthorization, ///Will be used to expire client secret after certain amount of time to be supplied in seconds #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_on: PrimitiveDateTime, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = External3dsAuthenticationRequest)] pub request_external_three_ds_authentication: common_enums::External3dsAuthenticationRequest, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetails { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] order_amount: Amount, /// The currency of the order #[schema(example = "USD", value_type = Currency)] currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[serde(default)] #[schema(value_type = TaxCalculationOverride)] skip_external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[serde(default)] #[schema(value_type = SurchargeCalculationOverride)] skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new_for_zero_auth_payment(currency: common_enums::Currency) -> Self { Self { order_amount: Amount::Zero, currency, shipping_cost: None, order_tax_amount: None, skip_external_tax_calculation: common_enums::TaxCalculationOverride::Skip, skip_surcharge_calculation: common_enums::SurchargeCalculationOverride::Skip, surcharge_amount: None, tax_on_surcharge: None, } } } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AmountDetailsUpdate { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] order_amount: Option<Amount>, /// The currency of the order #[schema(example = "USD", value_type = Option<Currency>)] currency: Option<common_enums::Currency>, /// The shipping cost of the order. This has to be collected from the merchant shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = Option<TaxCalculationOverride>)] skip_external_tax_calculation: Option<common_enums::TaxCalculationOverride>, /// The action to whether calculate surcharge or not #[schema(value_type = Option<SurchargeCalculationOverride>)] skip_surcharge_calculation: Option<common_enums::SurchargeCalculationOverride>, /// The surcharge amount to be added to the order, collected from the merchant surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] pub struct AmountDetailsSetter { pub order_amount: Amount, pub currency: common_enums::Currency, pub shipping_cost: Option<MinorUnit>, pub order_tax_amount: Option<MinorUnit>, pub skip_external_tax_calculation: common_enums::TaxCalculationOverride, pub skip_surcharge_calculation: common_enums::SurchargeCalculationOverride, pub surcharge_amount: Option<MinorUnit>, pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct AmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct PaymentAmountDetailsResponse { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = u64, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize")] pub order_amount: MinorUnit, /// The currency of the order #[schema(example = "USD", value_type = Currency)] pub currency: common_enums::Currency, /// The shipping cost of the order. This has to be collected from the merchant pub shipping_cost: Option<MinorUnit>, /// Tax amount related to the order. This will be calculated by the external tax provider pub order_tax_amount: Option<MinorUnit>, /// The action to whether calculate tax by calling external tax provider or not #[schema(value_type = TaxCalculationOverride)] pub external_tax_calculation: common_enums::TaxCalculationOverride, /// The action to whether calculate surcharge or not #[schema(value_type = SurchargeCalculationOverride)] pub surcharge_calculation: common_enums::SurchargeCalculationOverride, /// The surcharge amount to be added to the order, collected from the merchant pub surcharge_amount: Option<MinorUnit>, /// tax on surcharge amount pub tax_on_surcharge: Option<MinorUnit>, /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// The amount that can be captured on the payment. Either in one go or through multiple captures. /// This is applicable in case the capture method was either `manual` or `manual_multiple` pub amount_capturable: MinorUnit, /// The amount that was captured for this payment. This is the sum of all the captures done on this payment pub amount_captured: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentAttemptAmountDetails { /// The total amount of the order including tax, surcharge and shipping cost pub net_amount: MinorUnit, /// The amount that was requested to be captured for this payment pub amount_to_capture: Option<MinorUnit>, /// Surcharge amount for the payment attempt. /// This is either derived by surcharge rules, or sent by the merchant pub surcharge_amount: Option<MinorUnit>, /// Tax amount for the payment attempt /// This is either derived by surcharge rules, or sent by the merchant pub tax_on_surcharge: Option<MinorUnit>, /// The total amount that can be captured for this payment attempt. pub amount_capturable: MinorUnit, /// Shipping cost for the payment attempt. /// Shipping cost for the payment attempt. pub shipping_cost: Option<MinorUnit>, /// Tax amount for the order. /// This is either derived by calling an external tax processor, or sent by the merchant pub order_tax_amount: Option<MinorUnit>, } #[cfg(feature = "v2")] impl AmountDetails { pub fn new(amount_details_setter: AmountDetailsSetter) -> Self { Self { order_amount: amount_details_setter.order_amount, currency: amount_details_setter.currency, shipping_cost: amount_details_setter.shipping_cost, order_tax_amount: amount_details_setter.order_tax_amount, skip_external_tax_calculation: amount_details_setter.skip_external_tax_calculation, skip_surcharge_calculation: amount_details_setter.skip_surcharge_calculation, surcharge_amount: amount_details_setter.surcharge_amount, tax_on_surcharge: amount_details_setter.tax_on_surcharge, } } pub fn order_amount(&self) -> Amount { self.order_amount } pub fn currency(&self) -> common_enums::Currency { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> common_enums::TaxCalculationOverride { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> common_enums::SurchargeCalculationOverride { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v2")] impl AmountDetailsUpdate { pub fn order_amount(&self) -> Option<Amount> { self.order_amount } pub fn currency(&self) -> Option<common_enums::Currency> { self.currency } pub fn shipping_cost(&self) -> Option<MinorUnit> { self.shipping_cost } pub fn order_tax_amount(&self) -> Option<MinorUnit> { self.order_tax_amount } pub fn skip_external_tax_calculation(&self) -> Option<common_enums::TaxCalculationOverride> { self.skip_external_tax_calculation } pub fn skip_surcharge_calculation(&self) -> Option<common_enums::SurchargeCalculationOverride> { self.skip_surcharge_calculation } pub fn surcharge_amount(&self) -> Option<MinorUnit> { self.surcharge_amount } pub fn tax_on_surcharge(&self) -> Option<MinorUnit> { self.tax_on_surcharge } } #[cfg(feature = "v1")] #[derive( Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PaymentsCreateRequest, PaymentsUpdateRequest, PaymentsConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PaymentsRequest { /// The payment amount. Amount for the payment in the lowest denomination of the currency, (i.e) in cents for USD denomination, in yen for JPY denomination etc. E.g., Pass 100 to charge $1.00 and 1 for 1¥ since ¥ is a zero-decimal currency. Read more about [the Decimal and Non-Decimal Currencies](https://github.com/juspay/hyperswitch/wiki/Decimal-and-Non%E2%80%90Decimal-Currencies) #[schema(value_type = Option<u64>, example = 6540)] #[serde(default, deserialize_with = "amount::deserialize_option")] #[mandatory_in(PaymentsCreateRequest = u64)] // Makes the field mandatory in PaymentsCreateRequest pub amount: Option<Amount>, /// Total tax amount applicable to the order #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The three letter ISO currency code in uppercase. Eg: 'USD' to charge US Dollars #[schema(example = "USD", value_type = Option<Currency>)] #[mandatory_in(PaymentsCreateRequest = Currency)] pub currency: Option<api_enums::Currency>, /// The Amount to be captured / debited from the users payment method. It shall be in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, the default amount_to_capture will be the payment amount. Also, it must be less than or equal to the original payment account. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// The shipping cost for the payment. This is required for tax calculation in some regions. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. The value for this field can be specified in the request, it will be auto generated otherwise and returned in the API response. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] #[serde(default, deserialize_with = "payment_id_type::deserialize_option")] pub payment_id: Option<PaymentIdType>, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = Option<String>)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// Details of the routing configuration for that payment #[schema(value_type = Option<StraightThroughAlgorithm>, example = json!({ "type": "single", "data": {"connector": "stripe", "merchant_connector_id": "mca_123"} }))] pub routing: Option<serde_json::Value>, /// This allows to manually select a connector with which the payment can go through. #[schema(value_type = Option<Vec<Connector>>, max_length = 255, example = json!(["stripe", "adyen"]))] pub connector: Option<Vec<api_enums::Connector>>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub capture_on: Option<PrimitiveDateTime>, /// Whether to confirm the payment (if applicable). It can be used to completely process a payment by attaching a payment method, setting `confirm=true` and `capture_method = automatic` in the *Payments/Create API* request itself. #[schema(default = false, example = true)] pub confirm: Option<bool>, /// Passing this object creates a new customer or attaches an existing customer to the payment pub customer: Option<CustomerDetails>, /// The identifier for the customer #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The customer's email address. /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub email: Option<Email>, /// The customer's name. /// This field will be deprecated soon, use the customer object instead. #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub name: Option<Secret<String>>, /// The customer's phone number /// This field will be deprecated soon, use the customer object instead #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone: Option<Secret<String>>, /// The country code for the customer phone number /// This field will be deprecated soon, use the customer object instead #[schema(max_length = 255, example = "+1", deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub phone_country_code: Option<String>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. When making a recurring payment by passing a mandate_id, this parameter is mandatory #[schema(example = true)] pub off_session: Option<bool>, /// A description for the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, #[schema(example = "bank_transfer")] #[serde(with = "payment_method_data_serde", default)] pub payment_method_data: Option<PaymentMethodDataRequest>, #[schema(value_type = Option<PaymentMethod>, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// As Hyperswitch tokenises the sensitive details about the payments method, it provides the payment_token as a reference to a stored payment method, ensuring that the sensitive details are not exposed in any manner. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// This is used along with the payment_token field while collecting during saved card payments. This field will be deprecated soon, use the payment_method_data.card_token object instead #[schema(value_type = Option<String>, deprecated)] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub card_cvc: Option<Secret<String>>, /// The shipping address for the payment pub shipping: Option<Address>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 22 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// It's a token used for client side verification. #[schema(example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest)] pub client_secret: Option<String>, /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. pub mandate_data: Option<MandateData>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// A unique identifier to link the payment to a mandate. To do Recurring payments after a mandate has been created, pass the mandate_id instead of payment_method_data #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] #[remove_in(PaymentsUpdateRequest)] pub mandate_id: Option<String>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>, example = r#"{ "user_agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.110 Safari/537.36", "accept_header": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", "language": "nl-NL", "color_depth": 24, "screen_height": 723, "screen_width": 1536, "time_zone": 0, "java_enabled": true, "java_script_enabled":true }"#)] pub browser_info: Option<serde_json::Value>, /// To indicate the type of payment experience that the payment method would go through #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Business country of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(value_type = Option<CountryAlpha2>, example = "US")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payment. /// To be deprecated soon. Pass the profile_id instead #[schema(example = "food")] #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] pub business_label: Option<String>, #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Business sub label for the payment #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest, PaymentsCreateRequest)] pub business_sub_label: Option<String>, /// Denotes the retry action #[schema(value_type = Option<RetryAction>)] #[remove_in(PaymentsCreateRequest)] pub retry_action: Option<api_enums::RetryAction>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. #[remove_in(PaymentsUpdateRequest, PaymentsCreateRequest, PaymentsConfirmRequest)] pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(default = false, example = true)] pub payment_link: Option<bool>, #[schema(value_type = Option<PaymentCreatePaymentLinkConfig>)] pub payment_link_config: Option<PaymentCreatePaymentLinkConfig>, /// Custom payment link config id set at business profile, send only if business_specific_configs is configured pub payment_link_config_id: Option<String>, /// The business profile to be used for this payment, if not passed the default business profile associated with the merchant account will be used. It is mandatory in case multiple business profiles have been set up. #[remove_in(PaymentsUpdateRequest, PaymentsConfirmRequest)] #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, #[remove_in(PaymentsConfirmRequest)] #[schema(value_type = Option<RequestSurchargeDetails>)] pub surcharge_details: Option<RequestSurchargeDetails>, /// The type of the payment that differentiates between normal and various types of mandate payments #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. pub request_incremental_authorization: Option<bool>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(example = true)] pub request_external_three_ds_authentication: Option<bool>, /// Details required for recurring payment pub recurring_details: Option<RecurringDetails>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<SplitPaymentsRequest>)] pub split_payments: Option<common_types::payments::SplitPaymentsRequest>, /// Optional boolean value to extent authorization period of this payment /// /// capture method must be manual or manual_multiple #[schema(value_type = Option<bool>, default = false)] pub request_extended_authorization: Option<RequestExtendedAuthorizationBool>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// Whether to calculate tax for this payment intent pub skip_external_tax_calculation: Option<bool>, /// Choose what kind of sca exemption is required for this payment #[schema(value_type = Option<ScaExemptionType>)] pub psd2_sca_exemption_type: Option<api_enums::ScaExemptionType>, /// Service details for click to pay external authentication #[schema(value_type = Option<CtpServiceDetails>)] pub ctp_service_details: Option<CtpServiceDetails>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CtpServiceDetails { /// merchant transaction id pub merchant_transaction_id: Option<String>, /// network transaction correlation id pub correlation_id: Option<String>, /// session transaction flow id pub x_src_flow_id: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, /// Encrypted payload #[schema(value_type = Option<String>)] pub encypted_payload: Option<Secret<String>>, } impl CtpServiceDetails { pub fn is_network_confirmation_call_required(&self) -> bool { self.provider == Some(api_enums::CtpServiceProvider::Mastercard) } } #[cfg(feature = "v1")] /// Checks if the inner values of two options are equal /// Returns true if values are not equal, returns false in other cases fn are_optional_values_invalid<T: PartialEq>( first_option: Option<&T>, second_option: Option<&T>, ) -> bool { match (first_option, second_option) { (Some(first_option), Some(second_option)) => first_option != second_option, _ => false, } } #[cfg(feature = "v1")] impl PaymentsRequest { /// Get the customer id /// /// First check the id for `customer.id` /// If not present, check for `customer_id` at the root level pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } pub fn validate_and_get_request_extended_authorization( &self, ) -> common_utils::errors::CustomResult<Option<RequestExtendedAuthorizationBool>, ValidationError> { self.request_extended_authorization .as_ref() .map(|request_extended_authorization| { request_extended_authorization.validate_field_and_get(self) }) .transpose() } /// Checks if the customer details are passed in both places /// If they are passed in both places, check for both the values to be equal /// Or else, return the field which has inconsistent data pub fn validate_customer_details_in_request(&self) -> Option<Vec<&str>> { if let Some(CustomerDetails { id, name, email, phone, phone_country_code, }) = self.customer.as_ref() { let invalid_fields = [ are_optional_values_invalid(self.customer_id.as_ref(), Some(id)) .then_some("customer_id and customer.id"), are_optional_values_invalid(self.email.as_ref(), email.as_ref()) .then_some("email and customer.email"), are_optional_values_invalid(self.name.as_ref(), name.as_ref()) .then_some("name and customer.name"), are_optional_values_invalid(self.phone.as_ref(), phone.as_ref()) .then_some("phone and customer.phone"), are_optional_values_invalid( self.phone_country_code.as_ref(), phone_country_code.as_ref(), ) .then_some("phone_country_code and customer.phone_country_code"), ] .into_iter() .flatten() .collect::<Vec<_>>(); if invalid_fields.is_empty() { None } else { Some(invalid_fields) } } else { None } } pub fn get_feature_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.feature_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_connector_metadata_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.connector_metadata .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_allowed_payment_method_types_as_value( &self, ) -> common_utils::errors::CustomResult< Option<serde_json::Value>, common_utils::errors::ParsingError, > { self.allowed_payment_method_types .as_ref() .map(Encode::encode_to_value) .transpose() } pub fn get_order_details_as_value( &self, ) -> common_utils::errors::CustomResult< Option<Vec<pii::SecretSerdeValue>>, common_utils::errors::ParsingError, > { self.order_details .as_ref() .map(|od| { od.iter() .map(|order| order.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() }) .transpose() } } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_test { use common_utils::generate_customer_id_of_default_length; use super::*; #[test] fn test_valid_case_where_customer_details_are_passed_only_once() { let customer_id = generate_customer_id_of_default_length(); let payments_request = PaymentsRequest { customer_id: Some(customer_id), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_valid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(customer_id), customer: Some(customer_object), ..Default::default() }; assert!(payments_request .validate_customer_details_in_request() .is_none()); } #[test] fn test_invalid_case_where_customer_id_is_passed_in_both_places() { let customer_id = generate_customer_id_of_default_length(); let another_customer_id = generate_customer_id_of_default_length(); let customer_object = CustomerDetails { id: customer_id.clone(), name: None, email: None, phone: None, phone_country_code: None, }; let payments_request = PaymentsRequest { customer_id: Some(another_customer_id), customer: Some(customer_object), ..Default::default() }; assert_eq!( payments_request.validate_customer_details_in_request(), Some(vec!["customer_id and customer.id"]) ); } } /// Details of surcharge applied on this payment, if applicable #[derive( Default, Debug, Clone, serde::Serialize, serde::Deserialize, Copy, ToSchema, PartialEq, )] pub struct RequestSurchargeDetails { #[schema(value_type = i64, example = 6540)] pub surcharge_amount: MinorUnit, pub tax_amount: Option<MinorUnit>, } // for v2 use the type from common_utils::types #[cfg(feature = "v1")] /// Browser information to be used for 3DS 2.0 #[derive(ToSchema, Debug, serde::Deserialize, serde::Serialize)] pub struct BrowserInformation { /// Color depth supported by the browser pub color_depth: Option<u8>, /// Whether java is enabled in the browser pub java_enabled: Option<bool>, /// Whether javascript is enabled in the browser pub java_script_enabled: Option<bool>, /// Language supported pub language: Option<String>, /// The screen height in pixels pub screen_height: Option<u32>, /// The screen width in pixels pub screen_width: Option<u32>, /// Time zone of the client pub time_zone: Option<i32>, /// Ip address of the client #[schema(value_type = Option<String>)] pub ip_address: Option<std::net::IpAddr>, /// List of headers that are accepted #[schema( example = "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8" )] pub accept_header: Option<String>, /// User-agent of the browser pub user_agent: Option<String>, /// The os type of the client device pub os_type: Option<String>, /// The os version of the client device pub os_version: Option<String>, /// The device model of the client pub device_model: Option<String>, } impl RequestSurchargeDetails { pub fn is_surcharge_zero(&self) -> bool { self.surcharge_amount == MinorUnit::new(0) && self.tax_amount.unwrap_or_default() == MinorUnit::new(0) } pub fn get_total_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount + self.tax_amount.unwrap_or_default() } pub fn get_surcharge_amount(&self) -> MinorUnit { self.surcharge_amount } pub fn get_tax_amount(&self) -> Option<MinorUnit> { self.tax_amount } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The payment attempt amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment attempt tax_amount. #[schema(value_type = Option<i64>, example = 6540)] pub order_tax_amount: Option<MinorUnit>, /// The currency of the amount of the payment attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: Option<String>, /// If there was an error while calling the connector, the error message is received here pub error_message: Option<String>, /// The payment method that is to be used #[schema(value_type = Option<PaymentMethod>, example = "bank_transfer")] pub payment_method: Option<enums::PaymentMethod>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "scheduled")] pub capture_method: Option<enums::CaptureMethod>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<enums::AuthenticationType>, /// Time at which the payment attempt was created #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[schema(value_type = PrimitiveDateTime, example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// A unique identifier to link the payment to a mandate, can be use instead of payment_method_data pub mandate_id: Option<String>, /// If there was an error while calling the connectors the error code is received here pub error_code: Option<String>, /// Provide a reference to a stored payment method pub payment_token: Option<String>, /// Additional data related to some connectors pub connector_metadata: Option<serde_json::Value>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "google_pay")] pub payment_method_type: Option<enums::PaymentMethodType>, /// Reference to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// (This field is not live yet)Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// (This field is not live yet)Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema)] pub struct PaymentAttemptResponse { /// The global identifier for the payment attempt #[schema(value_type = String)] pub id: id_type::GlobalAttemptId, /// /// The status of the attempt #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// Amount related information for this payment and attempt pub amount: PaymentAttemptAmountDetails, /// Name of the connector that was used for the payment attempt. #[schema(example = "stripe")] pub connector: Option<String>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = AuthenticationType, example = "no_three_ds", default = "three_ds")] pub authentication_type: api_enums::AuthenticationType, /// Date and time of Payment attempt creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Time at which the payment attempt was last modified #[serde(with = "common_utils::custom_serde::iso8601")] pub modified_at: PrimitiveDateTime, /// The reason for the cancellation of the payment attempt. Some connectors will have strict rules regarding the values this can have /// Cancellation reason will be validated at the connector level when building the request pub cancellation_reason: Option<String>, /// Payment token is the token used for temporary use in case the payment method is stored in vault #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<pii::SecretSerdeValue>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<enums::PaymentExperience>, /// Payment method type for the payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: common_enums::PaymentMethod, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// The payment method subtype for the payment attempt. #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = String)] pub connector_payment_id: Option<common_utils::types::ConnectorTransactionId>, /// Identifier for Payment Method used for the payment attempt #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Value passed in X-CLIENT-SOURCE header during payments confirm request by the client pub client_source: Option<String>, /// Value passed in X-CLIENT-VERSION header during payments confirm request by the client pub client_version: Option<String>, /// Additional data that might be required by hyperswitch, to enable some specific features. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptFeatureMetadata { /// Revenue recovery metadata that might be required by hyperswitch. pub revenue_recovery: Option<PaymentAttemptRevenueRecoveryData>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentAttemptRevenueRecoveryData { /// Flag to find out whether an attempt was created by external or internal system. #[schema(value_type = Option<TriggeredBy>, example = "internal")] pub attempt_triggered_by: common_enums::TriggeredBy, } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct CaptureResponse { /// Unique identifier for the capture pub capture_id: String, /// The status of the capture #[schema(value_type = CaptureStatus, example = "charged")] pub status: enums::CaptureStatus, /// The capture amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency of the amount of the capture #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<enums::Currency>, /// The connector used for the payment pub connector: String, /// Unique identifier for the parent attempt on which this capture is made pub authorized_attempt_id: String, /// A unique identifier for this capture provided by the connector pub connector_capture_id: Option<String>, /// Sequence number of this capture, in the series of captures made for the parent attempt pub capture_sequence: i16, /// If there was an error while calling the connector the error message is received here pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here pub error_code: Option<String>, /// If there was an error while calling the connectors the reason is received here pub error_reason: Option<String>, /// Reference to the capture at connector side pub reference_id: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, Copy, PartialEq, Eq)] pub enum Amount { Value(NonZeroI64), #[default] Zero, } impl From<Amount> for MinorUnit { fn from(amount: Amount) -> Self { match amount { Amount::Value(val) => Self::new(val.get()), Amount::Zero => Self::new(0), } } } impl From<MinorUnit> for Amount { fn from(minor_unit: MinorUnit) -> Self { match minor_unit.get_amount_as_i64() { 0 => Self::Zero, val => NonZeroI64::new(val).map_or(Self::Zero, Self::Value), } } } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct PaymentsRedirectRequest { pub payment_id: id_type::PaymentId, pub merchant_id: id_type::MerchantId, pub connector: String, pub param: String, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] #[serde(deny_unknown_fields)] pub struct VerifyRequest { // The merchant_id is generated through api key // and is later passed in the struct pub merchant_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub email: Option<Email>, pub name: Option<Secret<String>>, pub phone: Option<Secret<String>>, pub phone_country_code: Option<String>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_data: Option<PaymentMethodData>, pub payment_token: Option<String>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, pub client_secret: Option<String>, pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Eq, PartialEq, Copy)] #[serde(rename_all = "snake_case")] pub enum MandateTransactionType { NewMandateTransaction, RecurringMandateTransaction, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct MandateIds { pub mandate_id: Option<String>, pub mandate_reference_id: Option<MandateReferenceId>, } impl MandateIds { pub fn is_network_transaction_id_flow(&self) -> bool { matches!( self.mandate_reference_id, Some(MandateReferenceId::NetworkMandateId(_)) ) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone)] pub enum MandateReferenceId { ConnectorMandateId(ConnectorMandateReferenceId), // mandate_id send by connector NetworkMandateId(String), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with card data NetworkTokenWithNTI(NetworkTokenWithNTIRef), // network_txns_id send by Issuer to connector, Used for PG agnostic mandate txns along with network token data } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct NetworkTokenWithNTIRef { pub network_transaction_id: String, pub token_exp_month: Option<Secret<String>>, pub token_exp_year: Option<Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, Eq, PartialEq)] pub struct ConnectorMandateReferenceId { connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, } impl ConnectorMandateReferenceId { pub fn new( connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) -> Self { Self { connector_mandate_id, payment_method_id, update_history, mandate_metadata, connector_mandate_request_reference_id, } } pub fn get_connector_mandate_id(&self) -> Option<String> { self.connector_mandate_id.clone() } pub fn get_payment_method_id(&self) -> Option<String> { self.payment_method_id.clone() } pub fn get_mandate_metadata(&self) -> Option<pii::SecretSerdeValue> { self.mandate_metadata.clone() } pub fn get_connector_mandate_request_reference_id(&self) -> Option<String> { self.connector_mandate_request_reference_id.clone() } pub fn update( &mut self, connector_mandate_id: Option<String>, payment_method_id: Option<String>, update_history: Option<Vec<UpdateHistory>>, mandate_metadata: Option<pii::SecretSerdeValue>, connector_mandate_request_reference_id: Option<String>, ) { self.connector_mandate_id = connector_mandate_id.or(self.connector_mandate_id.clone()); self.payment_method_id = payment_method_id.or(self.payment_method_id.clone()); self.update_history = update_history.or(self.update_history.clone()); self.mandate_metadata = mandate_metadata.or(self.mandate_metadata.clone()); self.connector_mandate_request_reference_id = connector_mandate_request_reference_id .or(self.connector_mandate_request_reference_id.clone()); } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Eq, PartialEq)] pub struct UpdateHistory { pub connector_mandate_id: Option<String>, pub payment_method_id: String, pub original_payment_id: Option<id_type::PaymentId>, } impl MandateIds { pub fn new(mandate_id: String) -> Self { Self { mandate_id: Some(mandate_id), mandate_reference_id: None, } } } /// Passing this object during payments creates a mandate. The mandate_type sub object is passed by the server. // The fields on this struct are optional, as we want to allow the merchant to provide partial // information about creating mandates #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MandateData { /// A way to update the mandate's payment method details pub update_mandate_id: Option<String>, /// A consent from the customer to store the payment method pub customer_acceptance: Option<CustomerAcceptance>, /// A way to select the type of mandate used pub mandate_type: Option<MandateType>, } #[derive(Clone, Eq, PartialEq, Copy, Debug, Default, serde::Serialize, serde::Deserialize)] pub struct SingleUseMandate { pub amount: MinorUnit, pub currency: api_enums::Currency, } #[derive(Clone, Eq, PartialEq, Debug, Default, ToSchema, serde::Serialize, serde::Deserialize)] pub struct MandateAmountData { /// The maximum amount to be debited for the mandate transaction #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The currency for the transaction #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// Specifying start date of the mandate #[schema(example = "2022-09-10T00:00:00Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub start_date: Option<PrimitiveDateTime>, /// Specifying end date of the mandate #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub end_date: Option<PrimitiveDateTime>, /// Additional details required by mandate #[schema(value_type = Option<Object>, example = r#"{ "frequency": "DAILY" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MandateType { /// If the mandate should only be valid for 1 off-session use SingleUse(MandateAmountData), /// If the mandate should be valid for multiple debits MultiUse(Option<MandateAmountData>), } impl Default for MandateType { fn default() -> Self { Self::MultiUse(None) } } /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerAcceptance { /// Type of acceptance provided by the #[schema(example = "online")] pub acceptance_type: AcceptanceType, /// Specifying when the customer acceptance was provided #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub accepted_at: Option<PrimitiveDateTime>, /// Information required for online mandate generation pub online: Option<OnlineMandate>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, PartialEq, Eq, Clone, ToSchema)] #[serde(rename_all = "lowercase")] /// This is used to indicate if the mandate was accepted online or offline pub enum AcceptanceType { Online, #[default] Offline, } #[derive(Default, Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct OnlineMandate { /// Ip address of the customer machine from which the mandate was created #[schema(value_type = String, example = "123.32.25.123")] pub ip_address: Option<Secret<String, pii::IpAddress>>, /// The user-agent of the customer's browser pub user_agent: String, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Card { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, } #[cfg(feature = "v2")] impl TryFrom<payment_methods::CardDetail> for Card { type Error = error_stack::Report<ValidationError>; fn try_from(value: payment_methods::CardDetail) -> Result<Self, Self::Error> { use common_utils::ext_traits::OptionExt; let payment_methods::CardDetail { card_number, card_exp_month, card_exp_year, card_holder_name, nick_name, card_network, card_issuer, card_cvc, .. } = value; let card_cvc = card_cvc.get_required_value("card_cvc")?; Ok(Self { card_number, card_exp_month, card_exp_year, card_holder_name, card_cvc, card_issuer, card_network, card_type: None, card_issuing_country: None, bank_code: None, nick_name, }) } } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ExtendedCardInfo { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = String, example = "242")] pub card_cvc: Secret<String>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, } impl From<Card> for ExtendedCardInfo { fn from(value: Card) -> Self { Self { card_number: value.card_number, card_exp_month: value.card_exp_month, card_exp_year: value.card_exp_year, card_holder_name: value.card_holder_name, card_cvc: value.card_cvc, card_issuer: value.card_issuer, card_network: value.card_network, card_type: value.card_type, card_issuing_country: value.card_issuing_country, bank_code: value.bank_code, } } } impl GetAddressFromPaymentMethodData for Card { fn get_billing_address(&self) -> Option<Address> { // Create billing address if first_name is some or if it is not "" self.card_holder_name .as_ref() .filter(|card_holder_name| !card_holder_name.is_empty_after_trim()) .map(|card_holder_name| { // Split the `card_holder_name` into `first_name` and `last_name` based on the // first occurrence of ' '. For example // John Wheat Dough // first_name -> John // last_name -> Wheat Dough card_holder_name.peek().split_whitespace() }) .map(|mut card_holder_name_iter| { let first_name = card_holder_name_iter .next() .map(ToOwned::to_owned) .map(Secret::new); let last_name = card_holder_name_iter.collect::<Vec<_>>().join(" "); let last_name = if last_name.is_empty_after_trim() { None } else { Some(Secret::new(last_name)) }; AddressDetails { first_name, last_name, ..Default::default() } }) .map(|address_details| Address { address: Some(address_details), phone: None, email: None, }) } } impl Card { fn apply_additional_card_info( &self, additional_card_info: AdditionalCardInfo, ) -> Result<Self, error_stack::Report<ValidationError>> { Ok(Self { card_number: self.card_number.clone(), card_exp_month: self.card_exp_month.clone(), card_exp_year: self.card_exp_year.clone(), card_holder_name: self.card_holder_name.clone(), card_cvc: self.card_cvc.clone(), card_issuer: self .card_issuer .clone() .or(additional_card_info.card_issuer), card_network: self .card_network .clone() .or(additional_card_info.card_network.clone()), card_type: self.card_type.clone().or(additional_card_info.card_type), card_issuing_country: self .card_issuing_country .clone() .or(additional_card_info.card_issuing_country), bank_code: self.bank_code.clone().or(additional_card_info.bank_code), nick_name: self.nick_name.clone(), }) } } #[derive(Eq, PartialEq, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, Default)] #[serde(rename_all = "snake_case")] pub struct CardToken { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The CVC number for the card #[schema(value_type = Option<String>)] pub card_cvc: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardRedirectData { Knet {}, Benefit {}, MomoAtm {}, CardRedirect {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayLaterData { /// For KlarnaRedirect as PayLater Option KlarnaRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, // The billing country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] billing_country: Option<api_enums::CountryAlpha2>, }, /// For Klarna Sdk as PayLater Option KlarnaSdk { /// The token for the sdk workflow token: String, }, /// For Affirm redirect as PayLater Option AffirmRedirect {}, /// For AfterpayClearpay redirect as PayLater Option AfterpayClearpayRedirect { /// The billing email #[schema(value_type = Option<String>)] billing_email: Option<Email>, /// The billing name #[schema(value_type = Option<String>)] billing_name: Option<Secret<String>>, }, /// For PayBright Redirect as PayLater Option PayBrightRedirect {}, /// For WalleyRedirect as PayLater Option WalleyRedirect {}, /// For Alma Redirection as PayLater Option AlmaRedirect {}, AtomeRedirect {}, } impl GetAddressFromPaymentMethodData for PayLaterData { fn get_billing_address(&self) -> Option<Address> { match self { Self::KlarnaRedirect { billing_email, billing_country, } => { let address_details = AddressDetails { country: *billing_country, ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::AfterpayClearpayRedirect { billing_email, billing_name, } => { let address_details = AddressDetails { first_name: billing_name.clone(), ..AddressDetails::default() }; Some(Address { address: Some(address_details), email: billing_email.clone(), phone: None, }) } Self::PayBrightRedirect {} | Self::WalleyRedirect {} | Self::AlmaRedirect {} | Self::KlarnaSdk { .. } | Self::AffirmRedirect {} | Self::AtomeRedirect {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum BankDebitData { /// Payment Method data for Ach bank debit AchBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for ach bank debit payment #[schema(value_type = String, example = "000123456789")] account_number: Secret<String>, /// Routing number for ach bank debit payment #[schema(value_type = String, example = "110000000")] routing_number: Secret<String>, #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "John Doe")] bank_account_holder_name: Option<Secret<String>>, #[schema(value_type = String, example = "ACH")] bank_name: Option<common_enums::BankNames>, #[schema(value_type = String, example = "Checking")] bank_type: Option<common_enums::BankType>, #[schema(value_type = String, example = "Personal")] bank_holder_type: Option<common_enums::BankHolderType>, }, SepaBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// International bank account number (iban) for SEPA #[schema(value_type = String, example = "DE89370400440532013000")] iban: Secret<String>, /// Owner name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BecsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Becs payment method #[schema(value_type = String, example = "000123456")] account_number: Secret<String>, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] bsb_number: Secret<String>, /// Owner name for bank debit #[schema(value_type = Option<String>, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, BacsBankDebit { /// Billing details for bank debit billing_details: Option<BankDebitBilling>, /// Account number for Bacs payment method #[schema(value_type = String, example = "00012345")] account_number: Secret<String>, /// Sort code for Bacs payment method #[schema(value_type = String, example = "108800")] sort_code: Secret<String>, /// holder name for bank debit #[schema(value_type = String, example = "A. Schneider")] bank_account_holder_name: Option<Secret<String>>, }, } impl GetAddressFromPaymentMethodData for BankDebitData { fn get_billing_address(&self) -> Option<Address> { fn get_billing_address_inner( bank_debit_billing: Option<&BankDebitBilling>, bank_account_holder_name: Option<&Secret<String>>, ) -> Option<Address> { // We will always have address here let mut address = bank_debit_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address)?; // Prefer `account_holder_name` over `name` address.address.as_mut().map(|address| { address.first_name = bank_account_holder_name .or(address.first_name.as_ref()) .cloned(); }); Some(address) } match self { Self::AchBankDebit { billing_details, bank_account_holder_name, .. } | Self::SepaBankDebit { billing_details, bank_account_holder_name, .. } | Self::BecsBankDebit { billing_details, bank_account_holder_name, .. } | Self::BacsBankDebit { billing_details, bank_account_holder_name, .. } => get_billing_address_inner( billing_details.as_ref(), bank_account_holder_name.as_ref(), ), } } } #[cfg(feature = "v1")] /// Custom serializer and deserializer for PaymentMethodData mod payment_method_data_serde { use super::*; /// Deserialize `reward` payment_method as string for backwards compatibility /// The api contract would be /// ```json /// { /// "payment_method": "reward", /// "payment_method_type": "evoucher", /// "payment_method_data": "reward", /// } /// ``` /// /// For other payment methods, use the provided deserializer /// ```json /// "payment_method_data": { /// "card": { /// "card_number": "4242424242424242", /// "card_exp_month": "10", /// "card_exp_year": "25", /// "card_holder_name": "joseph Doe", /// "card_cvc": "123" /// } /// } /// ``` pub fn deserialize<'de, D>( deserializer: D, ) -> Result<Option<PaymentMethodDataRequest>, D::Error> where D: Deserializer<'de>, { #[derive(serde::Deserialize, Debug)] #[serde(untagged)] enum __Inner { RewardString(String), OptionalPaymentMethod(serde_json::Value), } // This struct is an intermediate representation // This is required in order to catch deserialization errors when deserializing `payment_method_data` // The #[serde(flatten)] attribute applied on `payment_method_data` discards // any of the error when deserializing and deserializes to an option instead #[derive(serde::Deserialize, Debug)] struct __InnerPaymentMethodData { billing: Option<Address>, #[serde(flatten)] payment_method_data: Option<serde_json::Value>, } let deserialize_to_inner = __Inner::deserialize(deserializer)?; match deserialize_to_inner { __Inner::OptionalPaymentMethod(value) => { let parsed_value = serde_json::from_value::<__InnerPaymentMethodData>(value) .map_err(|serde_json_error| de::Error::custom(serde_json_error.to_string()))?; let payment_method_data = if let Some(payment_method_data_value) = parsed_value.payment_method_data { // Even though no data is passed, the flatten serde_json::Value is deserialized as Some(Object {}) if let serde_json::Value::Object(ref inner_map) = payment_method_data_value { if inner_map.is_empty() { None } else { let payment_method_data = serde_json::from_value::<PaymentMethodData>( payment_method_data_value, ) .map_err(|serde_json_error| { de::Error::custom(serde_json_error.to_string()) })?; let address_details = parsed_value .billing .as_ref() .and_then(|billing| billing.address.clone()); match (payment_method_data.clone(), address_details.as_ref()) { ( PaymentMethodData::Card(ref mut card), Some(billing_address_details), ) => { if card.card_holder_name.is_none() { card.card_holder_name = billing_address_details.get_optional_full_name(); } Some(PaymentMethodData::Card(card.clone())) } _ => Some(payment_method_data), } } } else { Err(de::Error::custom("Expected a map for payment_method_data"))? } } else { None }; Ok(Some(PaymentMethodDataRequest { payment_method_data, billing: parsed_value.billing, })) } __Inner::RewardString(inner_string) => { let payment_method_data = match inner_string.as_str() { "reward" => PaymentMethodData::Reward, _ => Err(de::Error::custom("Invalid Variant"))?, }; Ok(Some(PaymentMethodDataRequest { payment_method_data: Some(payment_method_data), billing: None, })) } } } pub fn serialize<S>( payment_method_data_request: &Option<PaymentMethodDataRequest>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_request) = payment_method_data_request { if let Some(payment_method_data) = payment_method_data_request.payment_method_data.as_ref() { match payment_method_data { PaymentMethodData::Reward => serializer.serialize_str("reward"), PaymentMethodData::CardRedirect(_) | PaymentMethodData::BankDebit(_) | PaymentMethodData::BankRedirect(_) | PaymentMethodData::BankTransfer(_) | PaymentMethodData::RealTimePayment(_) | PaymentMethodData::MobilePayment(_) | PaymentMethodData::CardToken(_) | PaymentMethodData::Crypto(_) | PaymentMethodData::GiftCard(_) | PaymentMethodData::PayLater(_) | PaymentMethodData::Upi(_) | PaymentMethodData::Voucher(_) | PaymentMethodData::Card(_) | PaymentMethodData::MandatePayment | PaymentMethodData::OpenBanking(_) | PaymentMethodData::Wallet(_) => { payment_method_data_request.serialize(serializer) } } } else { payment_method_data_request.serialize(serializer) } } else { serializer.serialize_none() } } } /// The payment method information provided for making a payment #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] pub struct PaymentMethodDataRequest { /// This field is optional because, in case of saved cards we pass the payment_token /// There might be cases where we don't need to pass the payment_method_data and pass only payment method billing details /// We have flattened it because to maintain backwards compatibility with the old API contract #[serde(flatten)] pub payment_method_data: Option<PaymentMethodData>, /// billing details for the payment method. /// This billing details will be passed to the processor as billing address. /// If not passed, then payment.billing will be considered pub billing: Option<Address>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodData { #[schema(title = "Card")] Card(Card), #[schema(title = "CardRedirect")] CardRedirect(CardRedirectData), #[schema(title = "Wallet")] Wallet(WalletData), #[schema(title = "PayLater")] PayLater(PayLaterData), #[schema(title = "BankRedirect")] BankRedirect(BankRedirectData), #[schema(title = "BankDebit")] BankDebit(BankDebitData), #[schema(title = "BankTransfer")] BankTransfer(Box<BankTransferData>), #[schema(title = "RealTimePayment")] RealTimePayment(Box<RealTimePaymentData>), #[schema(title = "Crypto")] Crypto(CryptoData), #[schema(title = "MandatePayment")] MandatePayment, #[schema(title = "Reward")] Reward, #[schema(title = "Upi")] Upi(UpiData), #[schema(title = "Voucher")] Voucher(VoucherData), #[schema(title = "GiftCard")] GiftCard(Box<GiftCardData>), #[schema(title = "CardToken")] CardToken(CardToken), #[schema(title = "OpenBanking")] OpenBanking(OpenBankingData), #[schema(title = "MobilePayment")] MobilePayment(MobilePaymentData), } pub trait GetAddressFromPaymentMethodData { fn get_billing_address(&self) -> Option<Address>; } impl GetAddressFromPaymentMethodData for PaymentMethodData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Card(card_data) => card_data.get_billing_address(), Self::CardRedirect(_) => None, Self::Wallet(wallet_data) => wallet_data.get_billing_address(), Self::PayLater(pay_later) => pay_later.get_billing_address(), Self::BankRedirect(bank_redirect_data) => bank_redirect_data.get_billing_address(), Self::BankDebit(bank_debit_data) => bank_debit_data.get_billing_address(), Self::BankTransfer(bank_transfer_data) => bank_transfer_data.get_billing_address(), Self::Voucher(voucher_data) => voucher_data.get_billing_address(), Self::Crypto(_) | Self::Reward | Self::RealTimePayment(_) | Self::Upi(_) | Self::GiftCard(_) | Self::CardToken(_) | Self::OpenBanking(_) | Self::MandatePayment | Self::MobilePayment(_) => None, } } } impl PaymentMethodData { pub fn apply_additional_payment_data( &self, additional_payment_data: AdditionalPaymentData, ) -> Result<Self, error_stack::Report<ValidationError>> { if let AdditionalPaymentData::Card(additional_card_info) = additional_payment_data { match self { Self::Card(card) => Ok(Self::Card( card.apply_additional_card_info(*additional_card_info)?, )), _ => Ok(self.to_owned()), } } else { Ok(self.to_owned()) } } pub fn get_payment_method(&self) -> Option<api_enums::PaymentMethod> { match self { Self::Card(_) => Some(api_enums::PaymentMethod::Card), Self::CardRedirect(_) => Some(api_enums::PaymentMethod::CardRedirect), Self::Wallet(_) => Some(api_enums::PaymentMethod::Wallet), Self::PayLater(_) => Some(api_enums::PaymentMethod::PayLater), Self::BankRedirect(_) => Some(api_enums::PaymentMethod::BankRedirect), Self::BankDebit(_) => Some(api_enums::PaymentMethod::BankDebit), Self::BankTransfer(_) => Some(api_enums::PaymentMethod::BankTransfer), Self::RealTimePayment(_) => Some(api_enums::PaymentMethod::RealTimePayment), Self::Crypto(_) => Some(api_enums::PaymentMethod::Crypto), Self::Reward => Some(api_enums::PaymentMethod::Reward), Self::Upi(_) => Some(api_enums::PaymentMethod::Upi), Self::Voucher(_) => Some(api_enums::PaymentMethod::Voucher), Self::GiftCard(_) => Some(api_enums::PaymentMethod::GiftCard), Self::OpenBanking(_) => Some(api_enums::PaymentMethod::OpenBanking), Self::MobilePayment(_) => Some(api_enums::PaymentMethod::MobilePayment), Self::CardToken(_) | Self::MandatePayment => None, } } } pub trait GetPaymentMethodType { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType; } impl GetPaymentMethodType for CardRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Knet {} => api_enums::PaymentMethodType::Knet, Self::Benefit {} => api_enums::PaymentMethodType::Benefit, Self::MomoAtm {} => api_enums::PaymentMethodType::MomoAtm, Self::CardRedirect {} => api_enums::PaymentMethodType::CardRedirect, } } } impl GetPaymentMethodType for MobilePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::DirectCarrierBilling { .. } => api_enums::PaymentMethodType::DirectCarrierBilling, } } } impl GetPaymentMethodType for WalletData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AliPayQr(_) | Self::AliPayRedirect(_) => api_enums::PaymentMethodType::AliPay, Self::AliPayHkRedirect(_) => api_enums::PaymentMethodType::AliPayHk, Self::AmazonPayRedirect(_) => api_enums::PaymentMethodType::AmazonPay, Self::MomoRedirect(_) => api_enums::PaymentMethodType::Momo, Self::KakaoPayRedirect(_) => api_enums::PaymentMethodType::KakaoPay, Self::GoPayRedirect(_) => api_enums::PaymentMethodType::GoPay, Self::GcashRedirect(_) => api_enums::PaymentMethodType::Gcash, Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) => { api_enums::PaymentMethodType::ApplePay } Self::DanaRedirect {} => api_enums::PaymentMethodType::Dana, Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) => { api_enums::PaymentMethodType::GooglePay } Self::MbWayRedirect(_) => api_enums::PaymentMethodType::MbWay, Self::MobilePayRedirect(_) => api_enums::PaymentMethodType::MobilePay, Self::PaypalRedirect(_) | Self::PaypalSdk(_) => api_enums::PaymentMethodType::Paypal, Self::Paze(_) => api_enums::PaymentMethodType::Paze, Self::SamsungPay(_) => api_enums::PaymentMethodType::SamsungPay, Self::TwintRedirect {} => api_enums::PaymentMethodType::Twint, Self::VippsRedirect {} => api_enums::PaymentMethodType::Vipps, Self::TouchNGoRedirect(_) => api_enums::PaymentMethodType::TouchNGo, Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) => { api_enums::PaymentMethodType::WeChatPay } Self::CashappQr(_) => api_enums::PaymentMethodType::Cashapp, Self::SwishQr(_) => api_enums::PaymentMethodType::Swish, Self::Mifinity(_) => api_enums::PaymentMethodType::Mifinity, } } } impl GetPaymentMethodType for PayLaterData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::KlarnaRedirect { .. } => api_enums::PaymentMethodType::Klarna, Self::KlarnaSdk { .. } => api_enums::PaymentMethodType::Klarna, Self::AffirmRedirect {} => api_enums::PaymentMethodType::Affirm, Self::AfterpayClearpayRedirect { .. } => api_enums::PaymentMethodType::AfterpayClearpay, Self::PayBrightRedirect {} => api_enums::PaymentMethodType::PayBright, Self::WalleyRedirect {} => api_enums::PaymentMethodType::Walley, Self::AlmaRedirect {} => api_enums::PaymentMethodType::Alma, Self::AtomeRedirect {} => api_enums::PaymentMethodType::Atome, } } } impl GetPaymentMethodType for OpenBankingData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::OpenBankingPIS {} => api_enums::PaymentMethodType::OpenBankingPIS, } } } impl GetPaymentMethodType for BankRedirectData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::BancontactCard { .. } => api_enums::PaymentMethodType::BancontactCard, Self::Bizum {} => api_enums::PaymentMethodType::Bizum, Self::Blik { .. } => api_enums::PaymentMethodType::Blik, Self::Eft { .. } => api_enums::PaymentMethodType::Eft, Self::Eps { .. } => api_enums::PaymentMethodType::Eps, Self::Giropay { .. } => api_enums::PaymentMethodType::Giropay, Self::Ideal { .. } => api_enums::PaymentMethodType::Ideal, Self::Interac { .. } => api_enums::PaymentMethodType::Interac, Self::OnlineBankingCzechRepublic { .. } => { api_enums::PaymentMethodType::OnlineBankingCzechRepublic } Self::OnlineBankingFinland { .. } => api_enums::PaymentMethodType::OnlineBankingFinland, Self::OnlineBankingPoland { .. } => api_enums::PaymentMethodType::OnlineBankingPoland, Self::OnlineBankingSlovakia { .. } => { api_enums::PaymentMethodType::OnlineBankingSlovakia } Self::OpenBankingUk { .. } => api_enums::PaymentMethodType::OpenBankingUk, Self::Przelewy24 { .. } => api_enums::PaymentMethodType::Przelewy24, Self::Sofort { .. } => api_enums::PaymentMethodType::Sofort, Self::Trustly { .. } => api_enums::PaymentMethodType::Trustly, Self::OnlineBankingFpx { .. } => api_enums::PaymentMethodType::OnlineBankingFpx, Self::OnlineBankingThailand { .. } => { api_enums::PaymentMethodType::OnlineBankingThailand } Self::LocalBankRedirect { .. } => api_enums::PaymentMethodType::LocalBankRedirect, } } } impl GetPaymentMethodType for BankDebitData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankDebit { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankDebit { .. } => api_enums::PaymentMethodType::Sepa, Self::BecsBankDebit { .. } => api_enums::PaymentMethodType::Becs, Self::BacsBankDebit { .. } => api_enums::PaymentMethodType::Bacs, } } } impl GetPaymentMethodType for BankTransferData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::AchBankTransfer { .. } => api_enums::PaymentMethodType::Ach, Self::SepaBankTransfer { .. } => api_enums::PaymentMethodType::SepaBankTransfer, Self::BacsBankTransfer { .. } => api_enums::PaymentMethodType::Bacs, Self::MultibancoBankTransfer { .. } => api_enums::PaymentMethodType::Multibanco, Self::PermataBankTransfer { .. } => api_enums::PaymentMethodType::PermataBankTransfer, Self::BcaBankTransfer { .. } => api_enums::PaymentMethodType::BcaBankTransfer, Self::BniVaBankTransfer { .. } => api_enums::PaymentMethodType::BniVa, Self::BriVaBankTransfer { .. } => api_enums::PaymentMethodType::BriVa, Self::CimbVaBankTransfer { .. } => api_enums::PaymentMethodType::CimbVa, Self::DanamonVaBankTransfer { .. } => api_enums::PaymentMethodType::DanamonVa, Self::MandiriVaBankTransfer { .. } => api_enums::PaymentMethodType::MandiriVa, Self::Pix { .. } => api_enums::PaymentMethodType::Pix, Self::Pse {} => api_enums::PaymentMethodType::Pse, Self::LocalBankTransfer { .. } => api_enums::PaymentMethodType::LocalBankTransfer, Self::InstantBankTransfer {} => api_enums::PaymentMethodType::InstantBankTransfer, } } } impl GetPaymentMethodType for CryptoData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { api_enums::PaymentMethodType::CryptoCurrency } } impl GetPaymentMethodType for RealTimePaymentData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Fps {} => api_enums::PaymentMethodType::Fps, Self::DuitNow {} => api_enums::PaymentMethodType::DuitNow, Self::PromptPay {} => api_enums::PaymentMethodType::PromptPay, Self::VietQr {} => api_enums::PaymentMethodType::VietQr, } } } impl GetPaymentMethodType for UpiData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::UpiCollect(_) => api_enums::PaymentMethodType::UpiCollect, Self::UpiIntent(_) => api_enums::PaymentMethodType::UpiIntent, } } } impl GetPaymentMethodType for VoucherData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Boleto(_) => api_enums::PaymentMethodType::Boleto, Self::Efecty => api_enums::PaymentMethodType::Efecty, Self::PagoEfectivo => api_enums::PaymentMethodType::PagoEfectivo, Self::RedCompra => api_enums::PaymentMethodType::RedCompra, Self::RedPagos => api_enums::PaymentMethodType::RedPagos, Self::Alfamart(_) => api_enums::PaymentMethodType::Alfamart, Self::Indomaret(_) => api_enums::PaymentMethodType::Indomaret, Self::Oxxo => api_enums::PaymentMethodType::Oxxo, Self::SevenEleven(_) => api_enums::PaymentMethodType::SevenEleven, Self::Lawson(_) => api_enums::PaymentMethodType::Lawson, Self::MiniStop(_) => api_enums::PaymentMethodType::MiniStop, Self::FamilyMart(_) => api_enums::PaymentMethodType::FamilyMart, Self::Seicomart(_) => api_enums::PaymentMethodType::Seicomart, Self::PayEasy(_) => api_enums::PaymentMethodType::PayEasy, } } } impl GetPaymentMethodType for GiftCardData { fn get_payment_method_type(&self) -> api_enums::PaymentMethodType { match self { Self::Givex(_) => api_enums::PaymentMethodType::Givex, Self::PaySafeCard {} => api_enums::PaymentMethodType::PaySafeCard, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum GiftCardData { Givex(GiftCardDetails), PaySafeCard {}, } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub struct GiftCardDetails { /// The gift card number #[schema(value_type = String)] pub number: Secret<String>, /// The card verification code. #[schema(value_type = String)] pub cvc: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct AdditionalCardInfo { /// The name of issuer of the card pub card_issuer: Option<String>, /// Card network of the card pub card_network: Option<api_enums::CardNetwork>, /// Card type, can be either `credit` or `debit` pub card_type: Option<String>, pub card_issuing_country: Option<String>, pub bank_code: Option<String>, /// Last 4 digits of the card number pub last4: Option<String>, /// The ISIN of the card pub card_isin: Option<String>, /// Extended bin of card, contains the first 8 digits of card number pub card_extended_bin: Option<String>, pub card_exp_month: Option<Secret<String>>, pub card_exp_year: Option<Secret<String>>, pub card_holder_name: Option<Secret<String>>, /// Additional payment checks done on the cvv and billing address by the processors. /// This is a free form field and the structure varies from processor to processor pub payment_checks: Option<serde_json::Value>, /// Details about the threeds environment. /// This is a free form field and the structure varies from processor to processor pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub enum AdditionalPaymentData { Card(Box<AdditionalCardInfo>), BankRedirect { bank_name: Option<common_enums::BankNames>, #[serde(flatten)] details: Option<additional_info::BankRedirectDetails>, }, Wallet { apple_pay: Option<ApplepayPaymentMethod>, google_pay: Option<additional_info::WalletAdditionalDataForCard>, samsung_pay: Option<additional_info::WalletAdditionalDataForCard>, }, PayLater { klarna_sdk: Option<KlarnaSdkPaymentMethod>, }, BankTransfer { #[serde(flatten)] details: Option<additional_info::BankTransferAdditionalData>, }, Crypto { #[serde(flatten)] details: Option<CryptoData>, }, BankDebit { #[serde(flatten)] details: Option<additional_info::BankDebitAdditionalData>, }, MandatePayment {}, Reward {}, RealTimePayment { #[serde(flatten)] details: Option<RealTimePaymentData>, }, Upi { #[serde(flatten)] details: Option<additional_info::UpiAdditionalData>, }, GiftCard { #[serde(flatten)] details: Option<additional_info::GiftCardAdditionalData>, }, Voucher { #[serde(flatten)] details: Option<VoucherData>, }, CardRedirect { #[serde(flatten)] details: Option<CardRedirectData>, }, CardToken { #[serde(flatten)] details: Option<additional_info::CardTokenAdditionalData>, }, OpenBanking { #[serde(flatten)] details: Option<OpenBankingData>, }, MobilePayment { #[serde(flatten)] details: Option<MobilePaymentData>, }, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct KlarnaSdkPaymentMethod { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankRedirectData { BancontactCard { /// The card number #[schema(value_type = String, example = "4242424242424242")] card_number: Option<CardNumber>, /// The card's expiry month #[schema(value_type = String, example = "24")] card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = String, example = "24")] card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = String, example = "John Test")] card_holder_name: Option<Secret<String>>, //Required by Stripes billing_details: Option<BankRedirectBilling>, }, Bizum {}, Blik { // Blik Code blik_code: Option<String>, }, Eps { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for eps #[schema(value_type = BankNames, example = "triodos_bank")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Giropay { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, #[schema(value_type = Option<String>)] /// Bank account bic code bank_account_bic: Option<Secret<String>>, /// Bank account iban #[schema(value_type = Option<String>)] bank_account_iban: Option<Secret<String>>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Ideal { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The hyperswitch bank code for ideal #[schema(value_type = BankNames, example = "abn_amro")] bank_name: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Interac { /// The country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] country: Option<api_enums::CountryAlpha2>, #[schema(value_type = Option<String>, example = "john.doe@example.com")] email: Option<Email>, }, OnlineBankingCzechRepublic { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingFinland { // Shopper Email #[schema(value_type = Option<String>)] email: Option<Email>, }, OnlineBankingPoland { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingSlovakia { // Issuer value corresponds to the bank #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OpenBankingUk { // Issuer banks #[schema(value_type = BankNames)] issuer: Option<common_enums::BankNames>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, Przelewy24 { //Issuer banks #[schema(value_type = Option<BankNames>)] bank_name: Option<common_enums::BankNames>, // The billing details for bank redirect billing_details: Option<BankRedirectBilling>, }, Sofort { /// The billing details for bank redirection billing_details: Option<BankRedirectBilling>, /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, /// The preferred language #[schema(example = "en")] preferred_language: Option<String>, }, Trustly { /// The country for bank payment #[schema(value_type = CountryAlpha2, example = "US")] country: api_enums::CountryAlpha2, }, OnlineBankingFpx { // Issuer banks #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, OnlineBankingThailand { #[schema(value_type = BankNames)] issuer: common_enums::BankNames, }, LocalBankRedirect {}, Eft { /// The preferred eft provider #[schema(example = "ozow")] provider: String, }, } impl GetAddressFromPaymentMethodData for BankRedirectData { fn get_billing_address(&self) -> Option<Address> { let get_billing_address_inner = |bank_redirect_billing: Option<&BankRedirectBilling>, billing_country: Option<&common_enums::CountryAlpha2>, billing_email: Option<&Email>| -> Option<Address> { let address = bank_redirect_billing .and_then(GetAddressFromPaymentMethodData::get_billing_address); let address = match (address, billing_country) { (Some(mut address), Some(billing_country)) => { address .address .as_mut() .map(|address| address.country = Some(*billing_country)); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_country)) => Some(Address { address: Some(AddressDetails { country: Some(*billing_country), ..AddressDetails::default() }), phone: None, email: None, }), (None, None) => None, }; match (address, billing_email) { (Some(mut address), Some(email)) => { address.email = Some(email.clone()); Some(address) } (Some(address), None) => Some(address), (None, Some(billing_email)) => Some(Address { address: None, phone: None, email: Some(billing_email.clone()), }), (None, None) => None, } }; match self { Self::BancontactCard { billing_details, card_holder_name, .. } => { let address = get_billing_address_inner(billing_details.as_ref(), None, None); if let Some(mut address) = address { address.address.as_mut().map(|address| { address.first_name = card_holder_name .as_ref() .or(address.first_name.as_ref()) .cloned(); }); Some(address) } else { Some(Address { address: Some(AddressDetails { first_name: card_holder_name.clone(), ..AddressDetails::default() }), phone: None, email: None, }) } } Self::Eps { billing_details, country, .. } | Self::Giropay { billing_details, country, .. } | Self::Ideal { billing_details, country, .. } | Self::Sofort { billing_details, country, .. } => get_billing_address_inner(billing_details.as_ref(), country.as_ref(), None), Self::Interac { country, email } => { get_billing_address_inner(None, country.as_ref(), email.as_ref()) } Self::OnlineBankingFinland { email } => { get_billing_address_inner(None, None, email.as_ref()) } Self::OpenBankingUk { country, .. } => { get_billing_address_inner(None, country.as_ref(), None) } Self::Przelewy24 { billing_details, .. } => get_billing_address_inner(billing_details.as_ref(), None, None), Self::Trustly { country } => get_billing_address_inner(None, Some(country), None), Self::OnlineBankingFpx { .. } | Self::LocalBankRedirect {} | Self::OnlineBankingThailand { .. } | Self::Bizum {} | Self::OnlineBankingPoland { .. } | Self::OnlineBankingSlovakia { .. } | Self::OnlineBankingCzechRepublic { .. } | Self::Blik { .. } | Self::Eft { .. } => None, } } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AlfamartVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct IndomaretVoucherData { /// The billing first name for Alfamart #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Alfamart #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Alfamart #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct JCSVoucherData { /// The billing first name for Japanese convenience stores #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name Japanese convenience stores #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Japanese convenience stores #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The telephone number for Japanese convenience stores #[schema(value_type = Option<String>, example = "9123456789")] pub phone_number: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBillingDetails { /// The Email ID for ACH billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct DokuBillingDetails { /// The billing first name for Doku #[schema(value_type = Option<String>, example = "Jane")] pub first_name: Option<Secret<String>>, /// The billing second name for Doku #[schema(value_type = Option<String>, example = "Doe")] pub last_name: Option<Secret<String>>, /// The Email ID for Doku billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MultibancoBillingDetails { #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaAndBacsBillingDetails { /// The Email ID for SEPA and BACS billing #[schema(value_type = Option<String>, example = "example@me.com")] pub email: Option<Email>, /// The billing name for SEPA and BACS billing #[schema(value_type = Option<String>, example = "Jane Doe")] pub name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct CryptoData { pub pay_currency: Option<String>, pub network: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiData { UpiCollect(UpiCollectData), UpiIntent(UpiIntentData), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct UpiCollectData { #[schema(value_type = Option<String>, example = "successtest@iata")] pub vpa_id: Option<Secret<String, pii::UpiVpaMaskingStrategy>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiIntentData {} #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SofortBilling { /// The country associated with the billing #[schema(value_type = CountryAlpha2, example = "US")] pub billing_country: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BankRedirectBilling { /// The name for which billing is issued #[schema(value_type = String, example = "John Doe")] pub billing_name: Option<Secret<String>>, /// The billing email for bank redirect #[schema(value_type = String, example = "example@example.com")] pub email: Option<Email>, } impl GetAddressFromPaymentMethodData for BankRedirectBilling { fn get_billing_address(&self) -> Option<Address> { let address_details = self .billing_name .as_ref() .map(|billing_name| AddressDetails { first_name: Some(billing_name.clone()), ..AddressDetails::default() }); if address_details.is_some() || self.email.is_some() { Some(Address { address: address_details, phone: None, email: self.email.clone(), }) } else { None } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferData { AchBankTransfer { /// The billing details for ACH Bank Transfer billing_details: Option<AchBillingDetails>, }, SepaBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, /// The two-letter ISO country code for SEPA and BACS #[schema(value_type = CountryAlpha2, example = "US")] country: Option<api_enums::CountryAlpha2>, }, BacsBankTransfer { /// The billing details for SEPA billing_details: Option<SepaAndBacsBillingDetails>, }, MultibancoBankTransfer { /// The billing details for Multibanco billing_details: Option<MultibancoBillingDetails>, }, PermataBankTransfer { /// The billing details for Permata Bank Transfer billing_details: Option<DokuBillingDetails>, }, BcaBankTransfer { /// The billing details for BCA Bank Transfer billing_details: Option<DokuBillingDetails>, }, BniVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, BriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, CimbVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, DanamonVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, MandiriVaBankTransfer { /// The billing details for BniVa Bank Transfer billing_details: Option<DokuBillingDetails>, }, Pix { /// Unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e-a446-4a57-bcce-6fa48899c1d1")] pix_key: Option<Secret<String>>, /// CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "10599054689")] cpf: Option<Secret<String>>, /// CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "74469027417312")] cnpj: Option<Secret<String>>, }, Pse {}, LocalBankTransfer { bank_code: Option<String>, }, InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RealTimePaymentData { Fps {}, DuitNow {}, PromptPay {}, VietQr {}, } impl GetAddressFromPaymentMethodData for BankTransferData { fn get_billing_address(&self) -> Option<Address> { match self { Self::AchBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::SepaBankTransfer { billing_details, country, } => billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { country: *country, first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }), Self::BacsBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::MultibancoBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: None, phone: None, email: details.email.clone(), }) } Self::PermataBankTransfer { billing_details } | Self::BcaBankTransfer { billing_details } | Self::BniVaBankTransfer { billing_details } | Self::BriVaBankTransfer { billing_details } | Self::CimbVaBankTransfer { billing_details } | Self::DanamonVaBankTransfer { billing_details } | Self::MandiriVaBankTransfer { billing_details } => { billing_details.as_ref().map(|details| Address { address: Some(AddressDetails { first_name: details.first_name.clone(), last_name: details.last_name.clone(), ..AddressDetails::default() }), phone: None, email: details.email.clone(), }) } Self::LocalBankTransfer { .. } | Self::Pix { .. } | Self::Pse {} | Self::InstantBankTransfer {} => None, } } } #[derive(serde::Deserialize, serde::Serialize, Debug, Clone, ToSchema, Eq, PartialEq)] pub struct BankDebitBilling { /// The billing name for bank debits #[schema(value_type = Option<String>, example = "John Doe")] pub name: Option<Secret<String>>, /// The billing email for bank debits #[schema(value_type = Option<String>, example = "example@example.com")] pub email: Option<Email>, /// The billing address for bank debits pub address: Option<AddressDetails>, } impl GetAddressFromPaymentMethodData for BankDebitBilling { fn get_billing_address(&self) -> Option<Address> { let address = if let Some(mut address) = self.address.clone() { address.first_name = self.name.clone().or(address.first_name); Address { address: Some(address), email: self.email.clone(), phone: None, } } else { Address { address: Some(AddressDetails { first_name: self.name.clone(), ..AddressDetails::default() }), email: self.email.clone(), phone: None, } }; Some(address) } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletData { /// The wallet data for Ali Pay QrCode AliPayQr(Box<AliPayQr>), /// The wallet data for Ali Pay redirect AliPayRedirect(AliPayRedirection), /// The wallet data for Ali Pay HK redirect AliPayHkRedirect(AliPayHkRedirection), /// The wallet data for Amazon Pay redirect AmazonPayRedirect(AmazonPayRedirectData), /// The wallet data for Momo redirect MomoRedirect(MomoRedirection), /// The wallet data for KakaoPay redirect KakaoPayRedirect(KakaoPayRedirection), /// The wallet data for GoPay redirect GoPayRedirect(GoPayRedirection), /// The wallet data for Gcash redirect GcashRedirect(GcashRedirection), /// The wallet data for Apple pay ApplePay(ApplePayWalletData), /// Wallet data for apple pay redirect flow ApplePayRedirect(Box<ApplePayRedirectData>), /// Wallet data for apple pay third party sdk flow ApplePayThirdPartySdk(Box<ApplePayThirdPartySdkData>), /// Wallet data for DANA redirect flow DanaRedirect {}, /// The wallet data for Google pay GooglePay(GooglePayWalletData), /// Wallet data for google pay redirect flow GooglePayRedirect(Box<GooglePayRedirectData>), /// Wallet data for Google pay third party sdk flow GooglePayThirdPartySdk(Box<GooglePayThirdPartySdkData>), MbWayRedirect(Box<MbWayRedirection>), /// The wallet data for MobilePay redirect MobilePayRedirect(Box<MobilePayRedirection>), /// This is for paypal redirection PaypalRedirect(PaypalRedirection), /// The wallet data for Paypal PaypalSdk(PayPalWalletData), /// The wallet data for Paze Paze(PazeWalletData), /// The wallet data for Samsung Pay SamsungPay(Box<SamsungPayWalletData>), /// Wallet data for Twint Redirection TwintRedirect {}, /// Wallet data for Vipps Redirection VippsRedirect {}, /// The wallet data for Touch n Go Redirection TouchNGoRedirect(Box<TouchNGoRedirection>), /// The wallet data for WeChat Pay Redirection WeChatPayRedirect(Box<WeChatPayRedirection>), /// The wallet data for WeChat Pay Display QrCode WeChatPayQr(Box<WeChatPayQr>), /// The wallet data for Cashapp Qr CashappQr(Box<CashappQr>), // The wallet data for Swish SwishQr(SwishQrData), // The wallet data for Mifinity Ewallet Mifinity(MifinityData), } impl GetAddressFromPaymentMethodData for WalletData { fn get_billing_address(&self) -> Option<Address> { match self { Self::MbWayRedirect(mb_way_redirect) => { let phone = PhoneDetails { // Portuguese country code, this payment method is applicable only in portugal country_code: Some("+351".into()), number: mb_way_redirect.telephone_number.clone(), }; Some(Address { phone: Some(phone), address: None, email: None, }) } Self::MobilePayRedirect(_) => None, Self::PaypalRedirect(paypal_redirect) => { paypal_redirect.email.clone().map(|email| Address { email: Some(email), address: None, phone: None, }) } Self::Mifinity(_) | Self::AliPayQr(_) | Self::AliPayRedirect(_) | Self::AliPayHkRedirect(_) | Self::MomoRedirect(_) | Self::KakaoPayRedirect(_) | Self::GoPayRedirect(_) | Self::GcashRedirect(_) | Self::AmazonPayRedirect(_) | Self::ApplePay(_) | Self::ApplePayRedirect(_) | Self::ApplePayThirdPartySdk(_) | Self::DanaRedirect {} | Self::GooglePay(_) | Self::GooglePayRedirect(_) | Self::GooglePayThirdPartySdk(_) | Self::PaypalSdk(_) | Self::Paze(_) | Self::SamsungPay(_) | Self::TwintRedirect {} | Self::VippsRedirect {} | Self::TouchNGoRedirect(_) | Self::WeChatPayRedirect(_) | Self::WeChatPayQr(_) | Self::CashappQr(_) | Self::SwishQr(_) => None, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct PazeWalletData { #[schema(value_type = String)] pub complete_response: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWalletData { pub payment_credential: SamsungPayWalletCredentials, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", untagged)] pub enum SamsungPayWalletCredentials { SamsungPayWalletDataForWeb(SamsungPayWebWalletData), SamsungPayWalletDataForApp(SamsungPayAppWalletData), } impl From<SamsungPayCardBrand> for common_enums::SamsungPayCardBrand { fn from(samsung_pay_card_brand: SamsungPayCardBrand) -> Self { match samsung_pay_card_brand { SamsungPayCardBrand::Visa => Self::Visa, SamsungPayCardBrand::MasterCard => Self::MasterCard, SamsungPayCardBrand::Amex => Self::Amex, SamsungPayCardBrand::Discover => Self::Discover, SamsungPayCardBrand::Unknown => Self::Unknown, } } } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayAppWalletData { /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, /// Brand of the payment card pub payment_card_brand: SamsungPayCardBrand, /// Currency type of the payment pub payment_currency_type: String, /// Last 4 digits of the device specific card number pub payment_last4_dpan: Option<String>, /// Last 4 digits of the card number pub payment_last4_fpan: String, /// Merchant reference id that was passed in the session call request pub merchant_ref: Option<String>, /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayWebWalletData { /// Specifies authentication method used pub method: Option<String>, /// Value if credential is enabled for recurring payment pub recurring_payment: Option<bool>, /// Brand of the payment card pub card_brand: SamsungPayCardBrand, /// Last 4 digits of the card number #[serde(rename = "card_last4digits")] pub card_last_four_digits: String, /// Samsung Pay token data #[serde(rename = "3_d_s")] pub token_data: SamsungPayTokenData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SamsungPayTokenData { /// 3DS type used by Samsung Pay #[serde(rename = "type")] pub three_ds_type: Option<String>, /// 3DS version used by Samsung Pay pub version: String, /// Samsung Pay encrypted payment credential data #[schema(value_type = String)] pub data: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub enum SamsungPayCardBrand { #[serde(alias = "VI")] Visa, #[serde(alias = "MC")] MasterCard, #[serde(alias = "AX")] Amex, #[serde(alias = "DC")] Discover, #[serde(other)] Unknown, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum OpenBankingData { #[serde(rename = "open_banking_pis")] OpenBankingPIS {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentData { DirectCarrierBilling { /// The phone number of the user #[schema(value_type = String, example = "1234567890")] msisdn: String, /// Unique user id #[schema(value_type = Option<String>, example = "02iacdYXGI9CnyJdoN8c7")] client_uid: Option<String>, }, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayWalletData { /// The type of payment method #[serde(rename = "type")] pub pm_type: String, /// User-facing message to describe the payment method that funds this transaction. pub description: String, /// The information of the payment method pub info: GooglePayPaymentMethodInfo, /// The tokenization data of Google pay pub tokenization_data: GpayTokenizationData, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmazonPayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayRedirectData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GooglePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayThirdPartySdkData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPay {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WeChatPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CashappQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaypalRedirection { /// paypal's email address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayQr {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AliPayHkRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MomoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KakaoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GoPayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GcashRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MobilePayRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MbWayRedirection { /// Telephone number of the shopper. Should be Portuguese phone number. #[schema(value_type = String)] pub telephone_number: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayPaymentMethodInfo { /// The name of the card network pub card_network: String, /// The details of the card pub card_details: String, //assurance_details of the card pub assurance_details: Option<GooglePayAssuranceDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct GooglePayAssuranceDetails { ///indicates that Cardholder possession validation has been performed pub card_holder_authenticated: bool, /// indicates that identification and verifications (ID&V) was performed pub account_verified: bool, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PayPalWalletData { /// Token generated for the Apple pay pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TouchNGoRedirection {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SwishQrData {} #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MifinityData { #[schema(value_type = Date)] pub date_of_birth: Secret<Date>, pub language_preference: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GpayTokenizationData { /// The type of the token #[serde(rename = "type")] pub token_type: String, /// Token generated for the wallet pub token: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayWalletData { /// The payment data of Apple pay pub payment_data: String, /// The payment method of Apple pay pub payment_method: ApplepayPaymentMethod, /// The unique identifier for the transaction pub transaction_identifier: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplepayPaymentMethod { /// The name to be displayed on Apple Pay button pub display_name: String, /// The network of the Apple pay payment method pub network: String, /// The type of the payment method #[serde(rename = "type")] pub pm_type: String, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardResponse { pub last4: Option<String>, pub card_type: Option<String>, #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, pub card_issuer: Option<String>, pub card_issuing_country: Option<String>, pub card_isin: Option<String>, pub card_extended_bin: Option<String>, #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, pub payment_checks: Option<serde_json::Value>, pub authentication_data: Option<serde_json::Value>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct RewardData { /// The merchant ID with which we have to call the connector #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BoletoVoucherData { /// The shopper's social security number #[schema(value_type = Option<String>)] pub social_security_number: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum VoucherData { Boleto(Box<BoletoVoucherData>), Efecty, PagoEfectivo, RedCompra, RedPagos, Alfamart(Box<AlfamartVoucherData>), Indomaret(Box<IndomaretVoucherData>), Oxxo, SevenEleven(Box<JCSVoucherData>), Lawson(Box<JCSVoucherData>), MiniStop(Box<JCSVoucherData>), FamilyMart(Box<JCSVoucherData>), Seicomart(Box<JCSVoucherData>), PayEasy(Box<JCSVoucherData>), } impl GetAddressFromPaymentMethodData for VoucherData { fn get_billing_address(&self) -> Option<Address> { match self { Self::Alfamart(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Indomaret(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: None, email: voucher_data.email.clone(), }), Self::Lawson(voucher_data) | Self::MiniStop(voucher_data) | Self::FamilyMart(voucher_data) | Self::Seicomart(voucher_data) | Self::PayEasy(voucher_data) | Self::SevenEleven(voucher_data) => Some(Address { address: Some(AddressDetails { first_name: voucher_data.first_name.clone(), last_name: voucher_data.last_name.clone(), ..AddressDetails::default() }), phone: Some(PhoneDetails { number: voucher_data.phone_number.clone().map(Secret::new), country_code: None, }), email: voucher_data.email.clone(), }), Self::Boleto(_) | Self::Efecty | Self::PagoEfectivo | Self::RedCompra | Self::RedPagos | Self::Oxxo => None, } } } /// Use custom serializer to provide backwards compatible response for `reward` payment_method_data pub fn serialize_payment_method_data_response<S>( payment_method_data_response: &Option<PaymentMethodDataResponseWithBilling>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, { if let Some(payment_method_data_response) = payment_method_data_response { if let Some(payment_method_data) = payment_method_data_response.payment_method_data.as_ref() { match payment_method_data { PaymentMethodDataResponse::Reward {} => serializer.serialize_str("reward"), PaymentMethodDataResponse::BankDebit(_) | PaymentMethodDataResponse::BankRedirect(_) | PaymentMethodDataResponse::Card(_) | PaymentMethodDataResponse::CardRedirect(_) | PaymentMethodDataResponse::CardToken(_) | PaymentMethodDataResponse::Crypto(_) | PaymentMethodDataResponse::MandatePayment {} | PaymentMethodDataResponse::GiftCard(_) | PaymentMethodDataResponse::PayLater(_) | PaymentMethodDataResponse::RealTimePayment(_) | PaymentMethodDataResponse::MobilePayment(_) | PaymentMethodDataResponse::Upi(_) | PaymentMethodDataResponse::Wallet(_) | PaymentMethodDataResponse::BankTransfer(_) | PaymentMethodDataResponse::OpenBanking(_) | PaymentMethodDataResponse::Voucher(_) => { payment_method_data_response.serialize(serializer) } } } else { // Can serialize directly because there is no `payment_method_data` payment_method_data_response.serialize(serializer) } } else { serializer.serialize_none() } } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodDataResponse { Card(Box<CardResponse>), BankTransfer(Box<BankTransferResponse>), Wallet(Box<WalletResponse>), PayLater(Box<PaylaterResponse>), BankRedirect(Box<BankRedirectResponse>), Crypto(Box<CryptoResponse>), BankDebit(Box<BankDebitResponse>), MandatePayment {}, Reward {}, RealTimePayment(Box<RealTimePaymentDataResponse>), Upi(Box<UpiResponse>), Voucher(Box<VoucherResponse>), GiftCard(Box<GiftCardResponse>), CardRedirect(Box<CardRedirectResponse>), CardToken(Box<CardTokenResponse>), OpenBanking(Box<OpenBankingResponse>), MobilePayment(Box<MobilePaymentResponse>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankDebitResponse { #[serde(flatten)] #[schema(value_type = Option<BankDebitAdditionalData>)] details: Option<additional_info::BankDebitAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type")] pub struct BankRedirectResponse { /// Name of the bank #[schema(value_type = Option<BankNames>)] pub bank_name: Option<common_enums::BankNames>, #[serde(flatten)] #[schema(value_type = Option<BankRedirectDetails>)] pub details: Option<additional_info::BankRedirectDetails>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferResponse { #[serde(flatten)] #[schema(value_type = Option<BankTransferAdditionalData>)] details: Option<additional_info::BankTransferAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardRedirectResponse { #[serde(flatten)] details: Option<CardRedirectData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CardTokenResponse { #[serde(flatten)] #[schema(value_type = Option<CardTokenAdditionalData>)] details: Option<additional_info::CardTokenAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct CryptoResponse { #[serde(flatten)] details: Option<CryptoData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GiftCardResponse { #[serde(flatten)] #[schema(value_type = Option<GiftCardAdditionalData>)] details: Option<additional_info::GiftCardAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OpenBankingResponse { #[serde(flatten)] details: Option<OpenBankingData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentResponse { #[serde(flatten)] details: Option<MobilePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RealTimePaymentDataResponse { #[serde(flatten)] details: Option<RealTimePaymentData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct UpiResponse { #[serde(flatten)] #[schema(value_type = Option<UpiAdditionalData>)] details: Option<additional_info::UpiAdditionalData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherResponse { #[serde(flatten)] details: Option<VoucherData>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaylaterResponse { klarna_sdk: Option<KlarnaSdkPaymentMethodResponse>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct WalletResponse { #[serde(flatten)] details: Option<WalletResponseData>, } /// Hyperswitch supports SDK integration with Apple Pay and Google Pay wallets. For other wallets, we integrate with their respective connectors, redirecting the customer to the connector for wallet payments. As a result, we don’t receive any payment method data in the confirm call for payments made through other wallets. #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum WalletResponseData { #[schema(value_type = WalletAdditionalDataForCard)] ApplePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] GooglePay(Box<additional_info::WalletAdditionalDataForCard>), #[schema(value_type = WalletAdditionalDataForCard)] SamsungPay(Box<additional_info::WalletAdditionalDataForCard>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct KlarnaSdkPaymentMethodResponse { pub payment_type: Option<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentMethodDataResponseWithBilling { // The struct is flattened in order to provide backwards compatibility #[serde(flatten)] pub payment_method_data: Option<PaymentMethodDataResponse>, pub billing: Option<Address>, } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v1")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::PaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[derive(Debug, Clone, PartialEq, Eq, serde::Serialize, serde::Deserialize, ToSchema)] #[cfg(feature = "v2")] pub enum PaymentIdType { /// The identifier for payment intent PaymentIntentId(id_type::GlobalPaymentId), /// The identifier for connector transaction ConnectorTransactionId(String), /// The identifier for payment attempt PaymentAttemptId(String), /// The identifier for preprocessing step PreprocessingId(String), } #[cfg(feature = "v1")] impl fmt::Display for PaymentIdType { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Self::PaymentIntentId(payment_id) => { write!( f, "payment_intent_id = \"{}\"", payment_id.get_string_repr() ) } Self::ConnectorTransactionId(connector_transaction_id) => write!( f, "connector_transaction_id = \"{connector_transaction_id}\"" ), Self::PaymentAttemptId(payment_attempt_id) => { write!(f, "payment_attempt_id = \"{payment_attempt_id}\"") } Self::PreprocessingId(preprocessing_id) => { write!(f, "preprocessing_id = \"{preprocessing_id}\"") } } } } #[cfg(feature = "v1")] impl Default for PaymentIdType { fn default() -> Self { Self::PaymentIntentId(Default::default()) } } #[derive(Default, Clone, Debug, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct Address { /// Provide the address details pub address: Option<AddressDetails>, pub phone: Option<PhoneDetails>, #[schema(value_type = Option<String>)] pub email: Option<Email>, } impl masking::SerializableSecret for Address {} impl Address { /// Unify the address, giving priority to `self` when details are present in both pub fn unify_address(self, other: Option<&Self>) -> Self { let other_address_details = other.and_then(|address| address.address.as_ref()); Self { address: self .address .map(|address| address.unify_address_details(other_address_details)) .or(other_address_details.cloned()), email: self.email.or(other.and_then(|other| other.email.clone())), phone: self.phone.or(other.and_then(|other| other.phone.clone())), } } } // used by customers also, could be moved outside /// Address details #[derive(Clone, Default, Debug, Eq, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] #[serde(deny_unknown_fields)] pub struct AddressDetails { /// The address city #[schema(max_length = 50, example = "New York")] pub city: Option<String>, /// The two-letter ISO country code for the address #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, /// The first line of the address #[schema(value_type = Option<String>, max_length = 200, example = "123, King Street")] pub line1: Option<Secret<String>>, /// The second line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Powelson Avenue")] pub line2: Option<Secret<String>>, /// The third line of the address #[schema(value_type = Option<String>, max_length = 50, example = "Bridgewater")] pub line3: Option<Secret<String>>, /// The zip/postal code for the address #[schema(value_type = Option<String>, max_length = 50, example = "08807")] pub zip: Option<Secret<String>>, /// The address state #[schema(value_type = Option<String>, example = "New York")] pub state: Option<Secret<String>>, /// The first name for the address #[schema(value_type = Option<String>, max_length = 255, example = "John")] pub first_name: Option<Secret<String>>, /// The last name for the address #[schema(value_type = Option<String>, max_length = 255, example = "Doe")] pub last_name: Option<Secret<String>>, } impl AddressDetails { pub fn get_optional_full_name(&self) -> Option<Secret<String>> { match (self.first_name.as_ref(), self.last_name.as_ref()) { (Some(first_name), Some(last_name)) => Some(Secret::new(format!( "{} {}", first_name.peek(), last_name.peek() ))), (Some(name), None) | (None, Some(name)) => Some(name.to_owned()), _ => None, } } pub fn unify_address_details(self, other: Option<&Self>) -> Self { if let Some(other) = other { let (first_name, last_name) = if self .first_name .as_ref() .is_some_and(|first_name| !first_name.is_empty_after_trim()) { (self.first_name, self.last_name) } else { (other.first_name.clone(), other.last_name.clone()) }; Self { first_name, last_name, city: self.city.or(other.city.clone()), country: self.country.or(other.country), line1: self.line1.or(other.line1.clone()), line2: self.line2.or(other.line2.clone()), line3: self.line3.or(other.line3.clone()), zip: self.zip.or(other.zip.clone()), state: self.state.or(other.state.clone()), } } else { self } } } pub struct AddressDetailsWithPhone { pub address: Option<AddressDetails>, pub phone_number: Option<Secret<String>>, pub email: Option<Email>, } pub struct EncryptableAddressDetails { pub line1: crypto::OptionalEncryptableSecretString, pub line2: crypto::OptionalEncryptableSecretString, pub line3: crypto::OptionalEncryptableSecretString, pub state: crypto::OptionalEncryptableSecretString, pub zip: crypto::OptionalEncryptableSecretString, pub first_name: crypto::OptionalEncryptableSecretString, pub last_name: crypto::OptionalEncryptableSecretString, pub phone_number: crypto::OptionalEncryptableSecretString, pub email: crypto::OptionalEncryptableEmail, } #[derive(Debug, Clone, Default, Eq, PartialEq, ToSchema, serde::Deserialize, serde::Serialize)] pub struct PhoneDetails { /// The contact number #[schema(value_type = Option<String>, example = "9123456789")] pub number: Option<Secret<String>>, /// The country code attached to the number #[schema(example = "+1")] pub country_code: Option<String>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The unique identifier for the merchant #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = i64, example = 6540)] pub amount_to_capture: Option<MinorUnit>, /// Decider to refund the uncaptured amount pub refund_uncaptured_amount: Option<bool>, /// Provides information about a card payment that customers see on their statements. pub statement_descriptor_suffix: Option<String>, /// Concatenated with the statement descriptor suffix that’s set on the account to form the complete statement descriptor. pub statement_descriptor_prefix: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsCaptureRequest { /// The Amount to be captured/ debited from the user's payment method. If not passed the full amount will be captured. #[schema(value_type = Option<i64>, example = 6540)] pub amount_to_capture: Option<MinorUnit>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct PaymentsCaptureResponse { /// The unique identifier for the payment pub id: id_type::GlobalPaymentId, /// Status of the payment #[schema(value_type = IntentStatus, example = "succeeded")] pub status: common_enums::IntentStatus, /// Amount details related to the payment pub amount: PaymentAmountDetailsResponse, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct UrlDetails { pub url: String, pub method: String, } #[derive(Default, Clone, Debug, Eq, PartialEq, serde::Serialize)] pub struct AuthenticationForStartResponse { pub authentication: UrlDetails, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionType { RedirectToUrl, DisplayQrCode, InvokeSdkClient, TriggerApi, DisplayBankTransferInformation, DisplayWaitScreen, CollectOtp, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "type", rename_all = "snake_case")] pub enum NextActionData { /// Contains the url for redirection flow #[cfg(feature = "v1")] RedirectToUrl { redirect_to_url: String, }, /// Contains the url for redirection flow #[cfg(feature = "v2")] RedirectToUrl { #[schema(value_type = String)] redirect_to_url: Url, }, /// Informs the next steps for bank transfer and also contains the charges details (ex: amount received, amount charged etc) DisplayBankTransferInformation { bank_transfer_steps_and_charges_details: BankTransferNextStepsData, }, /// Contains third party sdk session token response ThirdPartySdkSessionToken { session_token: Option<SessionToken>, }, /// Contains url for Qr code image, this qr code has to be shown in sdk QrCodeInformation { #[schema(value_type = String)] /// Hyperswitch generated image data source url image_data_url: Option<Url>, display_to_timestamp: Option<i64>, #[schema(value_type = String)] /// The url for Qr code given by the connector qr_code_url: Option<Url>, display_text: Option<String>, border_color: Option<String>, }, /// Contains url to fetch Qr code data FetchQrCodeInformation { #[schema(value_type = String)] qr_code_fetch_url: Url, }, /// Contains the download url and the reference number for transaction DisplayVoucherInformation { #[schema(value_type = String)] voucher_details: VoucherNextStepData, }, /// Contains duration for displaying a wait screen, wait screen with timer is displayed by sdk WaitScreenInformation { display_from_timestamp: i128, display_to_timestamp: Option<i128>, }, /// Contains the information regarding three_ds_method_data submission, three_ds authentication, and authorization flows ThreeDsInvoke { three_ds_data: ThreeDsData, }, InvokeSdkClient { next_action_data: SdkNextActionData, }, /// Contains consent to collect otp for mobile payment CollectOtp { consent_data_required: MobilePaymentConsent, }, /// Contains data required to invoke hidden iframe InvokeHiddenIframe { iframe_data: IframeData, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "method_key")] pub enum IframeData { #[serde(rename = "threeDSMethodData")] ThreedsInvokeAndCompleteAutorize { /// ThreeDS method url three_ds_method_url: String, /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS Server ID directory_server_id: String, /// ThreeDS Protocol version message_version: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThreeDsData { /// ThreeDS authentication url - to initiate authentication pub three_ds_authentication_url: String, /// ThreeDS authorize url - to complete the payment authorization after authentication pub three_ds_authorize_url: String, /// ThreeDS method details pub three_ds_method_details: ThreeDsMethodData, /// Poll config for a connector pub poll_config: PollConfigResponse, /// Message Version pub message_version: Option<String>, /// Directory Server ID pub directory_server_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "three_ds_method_key")] pub enum ThreeDsMethodData { #[serde(rename = "threeDSMethodData")] AcsThreeDsMethodData { /// Whether ThreeDS method data submission is required three_ds_method_data_submission: bool, /// ThreeDS method data three_ds_method_data: Option<String>, /// ThreeDS method url three_ds_method_url: Option<String>, }, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct PollConfigResponse { /// Poll Id pub poll_id: String, /// Interval of the poll pub delay_in_secs: i8, /// Frequency of the poll pub frequency: i8, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] #[serde(untagged)] // the enum order shouldn't be changed as this is being used during serialization and deserialization pub enum QrCodeInformation { QrCodeUrl { image_data_url: Url, qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrDataUrl { image_data_url: Url, display_to_timestamp: Option<i64>, }, QrCodeImageUrl { qr_code_url: Url, display_to_timestamp: Option<i64>, }, QrColorDataUrl { color_image_data_url: Url, display_to_timestamp: Option<i64>, display_text: Option<String>, border_color: Option<String>, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, Eq, PartialEq, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SdkNextActionData { pub next_action: NextActionCall, pub order_id: Option<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct FetchQrCodeInformation { pub qr_code_fetch_url: Url, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BankTransferNextStepsData { /// The instructions for performing a bank transfer #[serde(flatten)] pub bank_transfer_instructions: BankTransferInstructions, /// The details received by the receiver pub receiver: Option<ReceiverDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct VoucherNextStepData { /// Voucher expiry date and time pub expires_at: Option<i64>, /// Reference number required for the transaction pub reference: String, /// Url to download the payment instruction pub download_url: Option<Url>, /// Url to payment instruction page pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MobilePaymentNextStepData { /// is consent details required to be shown by sdk pub consent_data_required: MobilePaymentConsent, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MobilePaymentConsent { ConsentRequired, ConsentNotRequired, ConsentOptional, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct QrCodeNextStepsInstruction { pub image_data_url: Url, pub display_to_timestamp: Option<i64>, pub qr_code_url: Option<Url>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct WaitScreenInstructions { pub display_from_timestamp: i128, pub display_to_timestamp: Option<i128>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferInstructions { /// The instructions for Doku bank transactions DokuBankTransferInstructions(Box<DokuBankTransferInstructions>), /// The credit transfer for ACH transactions AchCreditTransfer(Box<AchTransfer>), /// The instructions for SEPA bank transactions SepaBankInstructions(Box<SepaBankTransferInstructions>), /// The instructions for BACS bank transactions BacsBankInstructions(Box<BacsBankTransferInstructions>), /// The instructions for Multibanco bank transactions Multibanco(Box<MultibancoTransferInstructions>), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "9123456789")] pub bic: Secret<String>, pub country: String, #[schema(value_type = String, example = "123456789")] pub iban: Secret<String>, #[schema(value_type = String, example = "U2PVVSEV4V9Y")] pub reference: Secret<String>, } #[derive(Clone, Debug, serde::Deserialize)] pub struct PaymentsConnectorThreeDsInvokeData { pub directory_server_id: String, pub three_ds_method_url: String, pub three_ds_method_data: String, pub message_version: Option<String>, pub three_ds_method_data_submission: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankTransferInstructions { #[schema(value_type = String, example = "Jane Doe")] pub account_holder_name: Secret<String>, #[schema(value_type = String, example = "10244123908")] pub account_number: Secret<String>, #[schema(value_type = String, example = "012")] pub sort_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MultibancoTransferInstructions { #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String, example = "12345")] pub entity: String, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DokuBankTransferInstructions { #[schema(value_type = String, example = "1707091200000")] pub expires_at: Option<i64>, #[schema(value_type = String, example = "122385736258")] pub reference: Secret<String>, #[schema(value_type = String)] pub instructions_url: Option<Url>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AchTransfer { #[schema(value_type = String, example = "122385736258")] pub account_number: Secret<String>, pub bank_name: String, #[schema(value_type = String, example = "012")] pub routing_number: Secret<String>, #[schema(value_type = String, example = "234")] pub swift_code: Secret<String>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ReceiverDetails { /// The amount received by receiver amount_received: i64, /// The amount charged by ACH amount_charged: Option<i64>, /// The amount remaining to be sent via ACH amount_remaining: Option<i64>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema, router_derive::PolymorphicSchema)] #[generate_schemas(PaymentsCreateResponseOpenApi)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: id_type::PaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// The payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// The payment net amount. net_amount = amount + surcharge_details.surcharge_amount + surcharge_details.tax_amount + shipping_cost + order_tax_amount, /// If no surcharge_details, shipping_cost, order_tax_amount, net_amount = amount #[schema(value_type = i64, example = 6540)] pub net_amount: MinorUnit, /// The shipping cost for the payment. #[schema(value_type = Option<i64>, example = 6540)] pub shipping_cost: Option<MinorUnit>, /// The maximum amount that could be captured from the payment #[schema(value_type = i64, minimum = 100, example = 6540)] pub amount_capturable: MinorUnit, /// The amount which is already captured from the payment, this helps in the cases where merchants can't capture all capturable amount at once. #[schema(value_type = Option<i64>, example = 6540)] pub amount_received: Option<MinorUnit>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<Secret<String>>, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The currency of the amount of the payment #[schema(value_type = Currency, example = "USD")] pub currency: String, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. /// This field will be deprecated soon. Please refer to `customer.id` #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", deprecated, value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, pub customer: Option<CustomerDetailsResponse>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// List of refunds that happened on this intent, as same payment intent can have multiple refund requests depending on the nature of order #[schema(value_type = Option<Vec<RefundResponse>>)] pub refunds: Option<Vec<refunds::RefundResponse>>, /// List of disputes that happened on this intent #[schema(value_type = Option<Vec<DisputeResponsePaymentsRetrieve>>)] pub disputes: Option<Vec<disputes::DisputeResponsePaymentsRetrieve>>, /// List of attempts that happened on this intent #[schema(value_type = Option<Vec<PaymentAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PaymentAttemptResponse>>, /// List of captures done on latest attempt #[schema(value_type = Option<Vec<CaptureResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub captures: Option<Vec<CaptureResponse>>, /// A unique identifier to link the payment to a mandate, can be used instead of payment_method_data, in case of setting up recurring payments #[schema(max_length = 255, example = "mandate_iwer89rnjef349dni3")] pub mandate_id: Option<String>, /// Provided mandate information for creating a mandate pub mandate_data: Option<MandateData>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Set to true to indicate that the customer is not in your checkout flow during this payment, and therefore is unable to authenticate. This parameter is intended for scenarios where you collect card details and charge them later. This parameter can only be used with confirm=true. #[schema(example = true)] pub off_session: Option<bool>, /// A timestamp (ISO 8601 code) that determines when the payment should be captured. /// Providing this field will automatically set `capture` to true #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] #[remove_in(PaymentsCreateResponseOpenApi)] pub capture_on: Option<PrimitiveDateTime>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// The payment method that is to be used #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method: Option<api_enums::PaymentMethod>, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>, example = "bank_transfer")] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// Provide a reference to a stored payment method #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432")] pub payment_token: Option<String>, /// The shipping address for the payment pub shipping: Option<Address>, /// The billing address for the payment pub billing: Option<Address>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<pii::SecretSerdeValue>>, /// description: The customer's email address /// This field will be deprecated soon. Please refer to `customer.email` object #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com", deprecated)] pub email: crypto::OptionalEncryptableEmail, /// description: The customer's name /// This field will be deprecated soon. Please refer to `customer.name` object #[schema(value_type = Option<String>, max_length = 255, example = "John Test", deprecated)] pub name: crypto::OptionalEncryptableName, /// The customer's phone number /// This field will be deprecated soon. Please refer to `customer.phone` object #[schema(value_type = Option<String>, max_length = 255, example = "9123456789", deprecated)] pub phone: crypto::OptionalEncryptablePhone, /// The URL to redirect after the completion of the operation #[schema(example = "https://hyperswitch.io")] pub return_url: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS, as the 3DS method helps with more robust payer authentication #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor_name: Option<String>, /// Provides information about a card payment that customers see on their statements. Concatenated with the prefix (shortened descriptor) or statement descriptor that’s set on the account to form the complete statement descriptor. Maximum 255 characters for the concatenated descriptor. #[schema(max_length = 255, example = "Payment for shoes purchase")] pub statement_descriptor_suffix: Option<String>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, /// error code unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_code: Option<String>, /// error message unified across the connectors is received here if there was an error while calling connector #[remove_in(PaymentsCreateResponseOpenApi)] pub unified_message: Option<String>, /// Payment Experience for the current payment #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience: Option<api_enums::PaymentExperience>, /// Can be used to specify the Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "gpay")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The connector used for this payment along with the country and business details #[schema(example = "stripe_US_food")] pub connector_label: Option<String>, /// The business country of merchant for this payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub business_country: Option<api_enums::CountryAlpha2>, /// The business label of merchant for this payment pub business_label: Option<String>, /// The business_sub_label for this payment pub business_sub_label: Option<String>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<serde_json::Value>, /// ephemeral_key for the customer_id mentioned pub ephemeral_key: Option<EphemeralKeyCreateResponse>, /// If true the payment can be retried with same or different payment method which means the confirm call can be made again. pub manual_retry_allowed: Option<bool>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// Frm message contains information about the frm response pub frm_message: Option<FrmMessage>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<serde_json::Value>, /// Additional data related to some connectors #[schema(value_type = Option<ConnectorMetadata>)] pub connector_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<FeatureMetadata>)] pub feature_metadata: Option<serde_json::Value>, // This is Value because it is fetched from DB and before putting in DB the type is validated /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub reference_id: Option<String>, /// Details for Payment link pub payment_link: Option<PaymentLinkResponse>, /// The business profile that is associated with this payment #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// Details of surcharge applied on this payment pub surcharge_details: Option<RequestSurchargeDetails>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Denotes the action(approve or reject) taken by merchant in case of manual review. Manual review can occur when the transaction is marked as risky by the frm_processor, payment processor or when there is underpayment/over payment incase of crypto payment pub merchant_decision: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// If true, incremental authorization can be performed on this payment, in case the funds authorized initially fall short. pub incremental_authorization_allowed: Option<bool>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// List of incremental authorizations happened to the payment pub incremental_authorizations: Option<Vec<IncrementalAuthorizationResponse>>, /// Details of external authentication pub external_authentication_details: Option<ExternalAuthenticationDetailsResponse>, /// Flag indicating if external 3ds authentication is made or not pub external_3ds_authentication_attempted: Option<bool>, /// Date Time for expiry of the payment #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub expires_on: Option<PrimitiveDateTime>, /// Payment Fingerprint, to identify a particular card. /// It is a 20 character long alphanumeric code. pub fingerprint: Option<String>, #[schema(value_type = Option<BrowserInformation>)] /// The browser information used for this payment pub browser_info: Option<serde_json::Value>, /// Identifier for Payment Method used for the payment pub payment_method_id: Option<String>, /// Payment Method Status, refers to the status of the payment method used for this payment. #[schema(value_type = Option<PaymentMethodStatus>)] pub payment_method_status: Option<common_enums::PaymentMethodStatus>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub updated: Option<PrimitiveDateTime>, /// Fee information to be charged on the payment being collected #[schema(value_type = Option<ConnectorChargeResponseData>)] pub split_payments: Option<common_types::payments::ConnectorChargeResponseData>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. FRM Metadata is useful for storing additional, structured information on an object related to FRM. #[schema(value_type = Option<Object>, example = r#"{ "fulfillment_method" : "deliver", "coverage_request" : "fraud" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// flag that indicates if extended authorization is applied on this payment or not #[schema(value_type = Option<bool>)] pub extended_authorization_applied: Option<ExtendedAuthorizationAppliedBool>, /// date and time after which this payment cannot be captured #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub capture_before: Option<PrimitiveDateTime>, /// Merchant's identifier for the payment/invoice. This will be sent to the connector /// if the connector provides support to accept multiple reference ids. /// In case the connector supports only one reference id, Hyperswitch's Payment ID will be sent as reference. #[schema( value_type = Option<String>, max_length = 255, example = "Custom_Order_id_123" )] pub merchant_order_reference_id: Option<String>, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// Connector Identifier for the payment method pub connector_mandate_id: Option<String>, /// Method through which card was discovered #[schema(value_type = Option<CardDiscovery>, example = "manual")] pub card_discovery: Option<enums::CardDiscovery>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if 3ds challenge is triggered pub force_3ds_challenge_trigger: Option<bool>, /// Error code received from the issuer in case of failed payments pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed payments pub issuer_error_message: Option<String>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentsListResponseItem { /// Unique identifier for the payment #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, example = "merchant_1668273825", value_type = String)] pub merchant_id: id_type::MerchantId, /// The business profile that is associated with this payment #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = Option<String> )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Identifier for Payment Method used for the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Status of the payment #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// The connector used for the payment #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Details of the customer pub customer: Option<CustomerDetailsResponse>, /// The reference id for the order in the merchant's system. This value can be passed by the merchant. #[schema(value_type = Option<String>)] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_payment_id: Option<String>, /// Reference to the capture at connector side pub connector_response_reference_id: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<Secret<serde_json::Value>>, /// A description of the payment #[schema(example = "It's my first payment request")] pub description: Option<String>, /// The transaction authentication can be set to undergo payer authentication. By default, the authentication will be marked as NO_THREE_DS #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// This is the instruction for capture/ debit the money from the users' card. On the other hand authorization refers to blocking the amount on the users' payment method. #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, /// Indicates that you intend to make future payments with this Payment’s payment method. Providing this parameter will attach the payment method to the Customer, if present, after the Payment is confirmed and any required actions from the user are complete. #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Total number of attempts associated with this payment pub attempt_count: i16, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// If the payment was cancelled the reason will be provided here pub cancellation_reason: Option<String>, /// Information about the product , quantity and amount for connectors. (e.g. Klarna) #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "gillete creme", "quantity": 15, "amount" : 900 }]"#)] pub order_details: Option<Vec<Secret<OrderDetailsWithAmount>>>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(value_type = Option<String>, max_length = 255, example = "Hyperswitch Router")] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Allowed Payment Method Types for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<common_enums::PaymentMethodType>>, /// Total number of authorizations happened in an incremental_authorization payment pub authorization_count: Option<i32>, /// Date time at which payment was updated #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub modified_at: Option<PrimitiveDateTime>, } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Intent Confirm #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentsConfirmIntentRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The shipping address for the payment. This will override the shipping address provided in the create-intent request pub shipping: Option<Address>, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ProxyPaymentsRequest { /// The URL to which you want the user to be redirected after the completion of the payment operation /// If this url is not passed, the url configured in the business profile will be used #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, pub amount: AmountDetails, pub recurring_details: ProcessorPaymentToken, pub shipping: Option<Address>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, #[schema(example = "stripe")] pub connector: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } // This struct contains the union of fields in `PaymentsCreateIntentRequest` and // `PaymentsConfirmIntentRequest` #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsRequest { /// The amount details for the payment pub amount_details: AmountDetails, /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4" )] pub merchant_reference_id: Option<id_type::PaymentReferenceId>, /// The routing algorithm id to be used for the payment #[schema(value_type = Option<String>)] pub routing_algorithm_id: Option<id_type::RoutingId>, #[schema(value_type = Option<CaptureMethod>, example = "automatic")] pub capture_method: Option<api_enums::CaptureMethod>, #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The billing details of the payment. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment pub shipping: Option<Address>, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// Set to `present` to indicate that the customer is in your checkout flow during this payment, and therefore is able to authenticate. This parameter should be `absent` when merchant's doing merchant initiated payments and customer is not present while doing the payment. #[schema(example = "present", value_type = Option<PresenceOfCustomerDuringPayment>)] pub customer_present: Option<common_enums::PresenceOfCustomerDuringPayment>, /// A description for the payment #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// The URL to which you want the user to be redirected after the completion of the payment operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<common_utils::types::Url>, #[schema(value_type = Option<FutureUsage>, example = "off_session")] pub setup_future_usage: Option<api_enums::FutureUsage>, /// Apply MIT exemption for a payment #[schema(value_type = Option<MitExemptionRequest>)] pub apply_mit_exemption: Option<common_enums::MitExemptionRequest>, /// For non-card charges, you can use this value as the complete description that appears on your customers’ statements. Must contain at least one letter, maximum 22 characters. #[schema(max_length = 22, example = "Hyperswitch Router", value_type = Option<String>)] pub statement_descriptor: Option<common_utils::types::StatementDescriptor>, /// Use this object to capture the details about the different products for which the payment is being made. The sum of amount across different products here should be equal to the overall payment amount #[schema(value_type = Option<Vec<OrderDetailsWithAmount>>, example = r#"[{ "product_name": "Apple iPhone 16", "quantity": 1, "amount" : 69000 "product_img_link" : "https://dummy-img-link.com" }]"#)] pub order_details: Option<Vec<OrderDetailsWithAmount>>, /// Use this parameter to restrict the Payment Method Types to show for a given PaymentIntent #[schema(value_type = Option<Vec<PaymentMethodType>>)] pub allowed_payment_method_types: Option<Vec<api_enums::PaymentMethodType>>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Some connectors like Apple pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. pub connector_metadata: Option<ConnectorMetadata>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<FeatureMetadata>, /// Whether to generate the payment link for this payment or not (if applicable) #[schema(value_type = Option<EnablePaymentLinkRequest>)] pub payment_link_enabled: Option<common_enums::EnablePaymentLinkRequest>, /// Configure a custom payment link for the particular payment #[schema(value_type = Option<PaymentLinkConfigRequest>)] pub payment_link_config: Option<admin::PaymentLinkConfigRequest>, ///Request an incremental authorization, i.e., increase the authorized amount on a confirmed payment before you capture it. #[schema(value_type = Option<RequestIncrementalAuthorization>)] pub request_incremental_authorization: Option<common_enums::RequestIncrementalAuthorization>, ///Will be used to expire client secret after certain amount of time to be supplied in seconds, if not sent it will be taken from profile config ///(900) for 15 mins #[schema(example = 900)] pub session_expiry: Option<u32>, /// Additional data related to some frm(Fraud Risk Management) connectors #[schema(value_type = Option<Object>, example = r#"{ "coverage_request" : "fraud", "fulfillment_method" : "delivery" }"#)] pub frm_metadata: Option<pii::SecretSerdeValue>, /// Whether to perform external authentication (if applicable) #[schema(value_type = Option<External3dsAuthenticationRequest>)] pub request_external_three_ds_authentication: Option<common_enums::External3dsAuthenticationRequest>, /// The payment instrument data to be used for the payment pub payment_method_data: PaymentMethodDataRequest, /// The payment method type to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// This "CustomerAcceptance" object is passed during Payments-Confirm request, it enlists the type, time, and mode of acceptance properties related to an acceptance done by the customer. The customer_acceptance sub object is usually passed by the SDK or client. #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<CustomerAcceptance>, /// Additional details required by 3DS 2.0 #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// The payment_method_id to be associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsCreateIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { amount_details: request.amount_details.clone(), merchant_reference_id: request.merchant_reference_id.clone(), routing_algorithm_id: request.routing_algorithm_id.clone(), capture_method: request.capture_method, authentication_type: request.authentication_type, billing: request.billing.clone(), shipping: request.shipping.clone(), customer_id: request.customer_id.clone(), customer_present: request.customer_present.clone(), description: request.description.clone(), return_url: request.return_url.clone(), setup_future_usage: request.setup_future_usage, apply_mit_exemption: request.apply_mit_exemption.clone(), statement_descriptor: request.statement_descriptor.clone(), order_details: request.order_details.clone(), allowed_payment_method_types: request.allowed_payment_method_types.clone(), metadata: request.metadata.clone(), connector_metadata: request.connector_metadata.clone(), feature_metadata: request.feature_metadata.clone(), payment_link_enabled: request.payment_link_enabled.clone(), payment_link_config: request.payment_link_config.clone(), request_incremental_authorization: request.request_incremental_authorization, session_expiry: request.session_expiry, frm_metadata: request.frm_metadata.clone(), request_external_three_ds_authentication: request .request_external_three_ds_authentication .clone(), force_3ds_challenge: request.force_3ds_challenge, } } } #[cfg(feature = "v2")] impl From<&PaymentsRequest> for PaymentsConfirmIntentRequest { fn from(request: &PaymentsRequest) -> Self { Self { return_url: request.return_url.clone(), payment_method_data: request.payment_method_data.clone(), payment_method_type: request.payment_method_type, payment_method_subtype: request.payment_method_subtype, shipping: request.shipping.clone(), customer_acceptance: request.customer_acceptance.clone(), browser_info: request.browser_info.clone(), payment_method_id: request.payment_method_id.clone(), } } } // Serialize is implemented because, this will be serialized in the api events. // Usually request types should not have serialize implemented. // /// Request for Payment Status #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentsRetrieveRequest { /// A boolean used to indicate if the payment status should be fetched from the connector /// If this is set to true, the status will be fetched from the connector #[serde(default)] pub force_sync: bool, /// A boolean used to indicate if all the attempts needs to be fetched for the intent. /// If this is set to true, attempts list will be available in the response. #[serde(default)] pub expand_attempts: bool, /// These are the query params that are sent in case of redirect response. /// These can be ingested by the connector to take necessary actions. pub param: Option<String>, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, PartialEq, ToSchema)] pub struct ErrorDetails { /// The error code pub code: String, /// The error message pub message: String, /// The unified error code across all connectors. /// This can be relied upon for taking decisions based on the error. pub unified_code: Option<String>, /// The unified error message across all connectors. /// If there is a translation available, this will have the translated message pub unified_message: Option<String>, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, } /// Token information that can be used to initiate transactions by the merchant. #[cfg(feature = "v2")] #[derive(Debug, Serialize, ToSchema)] pub struct ConnectorTokenDetails { /// A token that can be used to make payments directly with the connector. #[schema(example = "pm_9UhMqBMEOooRIvJFFdeW")] pub token: String, /// The reference id sent to the connector when creating the token pub connector_token_request_reference_id: Option<String>, } /// Response for Payment Intent Confirm /// Few fields should be expandable, we need not return these in the normal response /// But when explicitly requested for expanded objects, these can be returned /// For example /// shipping, billing, customer, payment_method #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentsResponse { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. #[schema( min_length = 32, max_length = 64, example = "12345_pay_01926c58bc6e77c09e809964e72af8c8", value_type = String, )] pub id: id_type::GlobalPaymentId, #[schema(value_type = IntentStatus, example = "succeeded")] pub status: api_enums::IntentStatus, /// Amount related information for this payment and attempt pub amount: PaymentAmountDetailsResponse, /// The identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: Option<id_type::GlobalCustomerId>, /// The connector used for the payment #[schema(example = "stripe")] pub connector: Option<String>, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: common_utils::types::ClientSecret, /// Time when the payment was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, /// The payment method information provided for making a payment #[schema(value_type = Option<PaymentMethodDataResponseWithBilling>)] #[serde(serialize_with = "serialize_payment_method_data_response")] pub payment_method_data: Option<PaymentMethodDataResponseWithBilling>, /// The payment method type for this payment attempt #[schema(value_type = Option<PaymentMethod>, example = "wallet")] pub payment_method_type: Option<api_enums::PaymentMethod>, #[schema(value_type = Option<PaymentMethodType>, example = "apple_pay")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payment provided by the connector #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_transaction_id: Option<String>, /// reference(Identifier) to the payment at connector side #[schema(value_type = Option<String>, example = "993672945374576J")] pub connector_reference_id: Option<String>, /// Identifier of the connector ( merchant connector account ) which was chosen to make the payment #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The browser information used for this payment #[schema(value_type = Option<BrowserInformation>)] pub browser_info: Option<common_utils::types::BrowserInformation>, /// Error details for the payment if any pub error: Option<ErrorDetails>, /// The shipping address associated with the payment intent pub shipping: Option<Address>, /// The billing address associated with the payment intent pub billing: Option<Address>, /// List of payment attempts associated with payment intent pub attempts: Option<Vec<PaymentAttemptResponse>>, /// Connector token information that can be used to make payments directly by the merchant. pub connector_token_details: Option<ConnectorTokenDetails>, /// The payment_method_id associated with the payment #[schema(value_type = Option<String>)] pub payment_method_id: Option<id_type::GlobalPaymentMethodId>, /// Additional information required for redirection pub next_action: Option<NextActionData>, /// The url to which user must be redirected to after completion of the purchase #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The authentication type that was requested for this order #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type: Option<api_enums::AuthenticationType>, /// The authentication type that was appliced for this order /// This depeneds on the 3DS rules configured, If not a default authentication type will be applied #[schema(value_type = Option<AuthenticationType>, example = "no_three_ds", default = "no_three_ds")] pub authentication_type_applied: Option<api_enums::AuthenticationType>, } #[cfg(feature = "v2")] impl PaymentsResponse { pub fn find_attempt_in_attempts_list_using_connector_transaction_id( self, connector_transaction_id: &common_utils::types::ConnectorTransactionId, ) -> Option<PaymentAttemptResponse> { self.attempts .as_ref() .and_then(|attempts| { attempts.iter().find(|attempt| { attempt .connector_payment_id .as_ref() .is_some_and(|txn_id| txn_id == connector_transaction_id) }) }) .cloned() } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionRequest { /// Global Payment ID pub id: id_type::GlobalPaymentId, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] #[cfg(feature = "v2")] pub struct PaymentStartRedirectionParams { /// The identifier for the Merchant Account. pub publishable_key: String, /// The identifier for business profile pub profile_id: id_type::ProfileId, } /// Details of external authentication #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct ExternalAuthenticationDetailsResponse { /// Authentication Type - Challenge / Frictionless #[schema(value_type = Option<DecoupledAuthenticationType>)] pub authentication_flow: Option<enums::DecoupledAuthenticationType>, /// Electronic Commerce Indicator (eci) pub electronic_commerce_indicator: Option<String>, /// Authentication Status #[schema(value_type = AuthenticationStatus)] pub status: enums::AuthenticationStatus, /// DS Transaction ID pub ds_transaction_id: Option<String>, /// Message Version pub version: Option<String>, /// Error Code pub error_code: Option<String>, /// Error Message pub error_message: Option<String>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for customer #[schema( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::PaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::PaymentId>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The time at which payment is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, utoipa::IntoParams)] #[serde(deny_unknown_fields)] pub struct PaymentListConstraints { /// The identifier for payment #[param(example = "pay_fafa124123", value_type = Option<String>)] pub payment_id: Option<id_type::GlobalPaymentId>, /// The identifier for business profile #[param(example = "pay_fafa124123", value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[param( max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>, )] pub customer_id: Option<id_type::GlobalCustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub starting_after: Option<id_type::GlobalPaymentId>, /// A cursor for use in pagination, fetch the previous list before some object #[param(example = "pay_fafa124123", value_type = Option<String>)] pub ending_before: Option<id_type::GlobalPaymentId>, /// limit on the number of objects to return #[param(default = 10, maximum = 100)] #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time at which payment is created #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment created time #[param(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, /// The connector to filter payments list #[param(value_type = Option<Connector>)] pub connector: Option<api_enums::Connector>, /// The currency to filter payments list #[param(value_type = Option<Currency>)] pub currency: Option<enums::Currency>, /// The payment status to filter payments list #[param(value_type = Option<IntentStatus>)] pub status: Option<enums::IntentStatus>, /// The payment method type to filter payments list #[param(value_type = Option<PaymentMethod>)] pub payment_method_type: Option<enums::PaymentMethod>, /// The payment method subtype to filter payments list #[param(value_type = Option<PaymentMethodType>)] pub payment_method_subtype: Option<enums::PaymentMethodType>, /// The authentication type to filter payments list #[param(value_type = Option<AuthenticationType>)] pub authentication_type: Option<enums::AuthenticationType>, /// The merchant connector id to filter payments list #[param(value_type = Option<String>)] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The field on which the payments list should be sorted #[serde(default)] pub order_on: SortOn, /// The order in which payments list should be sorted #[serde(default)] pub order_by: SortBy, /// The card networks to filter payments list #[param(value_type = Option<CardNetwork>)] pub card_network: Option<enums::CardNetwork>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, } #[cfg(feature = "v2")] impl PaymentListConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method_type.is_none() && self.payment_method_subtype.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the list pub size: usize, // The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentListResponse { /// The number of payments included in the current response pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsListResponseItem>, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct IncrementalAuthorizationResponse { /// The unique identifier of authorization pub authorization_id: String, /// Amount the authorization has been made for #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, #[schema(value_type= AuthorizationStatus)] /// The status of the authorization pub status: common_enums::AuthorizationStatus, /// Error code sent by the connector for authorization pub error_code: Option<String>, /// Error message sent by the connector for authorization pub error_message: Option<String>, /// Previously authorized amount for the payment pub previously_authorized_amount: MinorUnit, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListResponseV2 { /// The number of payments included in the list for given constraints pub count: usize, /// The total number of available payments for given constraints pub total_count: i64, /// The list of payments response objects pub data: Vec<PaymentsResponse>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentListFilterConstraints { /// The identifier for payment pub payment_id: Option<id_type::PaymentId>, /// The identifier for business profile pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payments_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The amount to filter payments list pub amount_filter: Option<AmountFilter>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payments list pub connector: Option<Vec<api_enums::Connector>>, /// The list of currencies to filter payments list pub currency: Option<Vec<enums::Currency>>, /// The list of payment status to filter payments list pub status: Option<Vec<enums::IntentStatus>>, /// The list of payment methods to filter payments list pub payment_method: Option<Vec<enums::PaymentMethod>>, /// The list of payment method types to filter payments list pub payment_method_type: Option<Vec<enums::PaymentMethodType>>, /// The list of authentication types to filter payments list pub authentication_type: Option<Vec<enums::AuthenticationType>>, /// The list of merchant connector ids to filter payments list for selected label pub merchant_connector_id: Option<Vec<id_type::MerchantConnectorAccountId>>, /// The order in which payments list should be sorted #[serde(default)] pub order: Order, /// The List of all the card networks to filter payments list pub card_network: Option<Vec<enums::CardNetwork>>, /// The identifier for merchant order reference id pub merchant_order_reference_id: Option<String>, /// Indicates the method by which a card is discovered during a payment pub card_discovery: Option<Vec<enums::CardDiscovery>>, } #[cfg(feature = "v1")] impl PaymentListFilterConstraints { pub fn has_no_attempt_filters(&self) -> bool { self.connector.is_none() && self.payment_method.is_none() && self.payment_method_type.is_none() && self.authentication_type.is_none() && self.merchant_connector_id.is_none() && self.card_network.is_none() && self.card_discovery.is_none() } } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFilters { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list of available payment method filters pub payment_method: Vec<enums::PaymentMethod>, /// The list of available payment method types pub payment_method_type: Vec<enums::PaymentMethodType>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentListFiltersV2 { /// The list of available connector filters pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters pub currency: Vec<enums::Currency>, /// The list of available payment status filters pub status: Vec<enums::IntentStatus>, /// The list payment method and their corresponding types pub payment_method: HashMap<enums::PaymentMethod, HashSet<enums::PaymentMethodType>>, /// The list of available authentication types pub authentication_type: Vec<enums::AuthenticationType>, /// The list of available card networks pub card_network: Vec<enums::CardNetwork>, /// The list of available Card discovery methods pub card_discovery: Vec<enums::CardDiscovery>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentsAggregateResponse { /// The list of intent status with their count pub status_with_count: HashMap<enums::IntentStatus, i64>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AmountFilter { /// The start amount to filter list of transactions which are greater than or equal to the start amount pub start_amount: Option<i64>, /// The end amount to filter list of transactions which are less than or equal to the end amount pub end_amount: Option<i64>, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct Order { /// The field to sort, such as Amount or Created etc. pub on: SortOn, /// The order in which to sort the items, either Ascending or Descending pub by: SortBy, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortOn { /// Sort by the amount field Amount, /// Sort by the created_at field #[default] Created, } #[derive(Clone, Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SortBy { /// Sort in ascending order Asc, /// Sort in descending order #[default] Desc, } #[derive(Setter, Clone, Default, Debug, PartialEq, serde::Serialize)] pub struct VerifyResponse { pub verify_id: Option<id_type::PaymentId>, pub merchant_id: Option<id_type::MerchantId>, // pub status: enums::VerifyStatus, pub client_secret: Option<Secret<String>>, pub customer_id: Option<id_type::CustomerId>, pub email: crypto::OptionalEncryptableEmail, pub name: crypto::OptionalEncryptableName, pub phone: crypto::OptionalEncryptablePhone, pub mandate_id: Option<String>, #[auth_based] pub payment_method: Option<api_enums::PaymentMethod>, #[auth_based] pub payment_method_data: Option<PaymentMethodDataResponse>, pub payment_token: Option<String>, pub error_code: Option<String>, pub error_message: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize)] pub struct PaymentsRedirectionResponse { pub redirect_url: String, } pub struct MandateValidationFields { pub recurring_details: Option<RecurringDetails>, pub confirm: Option<bool>, pub customer_id: Option<id_type::CustomerId>, pub mandate_data: Option<MandateData>, pub setup_future_usage: Option<api_enums::FutureUsage>, pub off_session: Option<bool>, } #[cfg(feature = "v1")] impl From<&PaymentsRequest> for MandateValidationFields { fn from(req: &PaymentsRequest) -> Self { let recurring_details = req .mandate_id .clone() .map(RecurringDetails::MandateId) .or(req.recurring_details.clone()); Self { recurring_details, confirm: req.confirm, customer_id: req .customer .as_ref() .map(|customer_details| &customer_details.id) .or(req.customer_id.as_ref()) .map(ToOwned::to_owned), mandate_data: req.mandate_data.clone(), setup_future_usage: req.setup_future_usage, off_session: req.off_session, } } } impl From<&VerifyRequest> for MandateValidationFields { fn from(req: &VerifyRequest) -> Self { Self { recurring_details: None, confirm: Some(true), customer_id: req.customer_id.clone(), mandate_data: req.mandate_data.clone(), off_session: req.off_session, setup_future_usage: req.setup_future_usage, } } } // #[cfg(all(feature = "v2", feature = "payment_v2"))] // impl From<PaymentsSessionRequest> for PaymentsSessionResponse { // fn from(item: PaymentsSessionRequest) -> Self { // let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); // Self { // session_token: vec![], // payment_id: item.payment_id, // client_secret, // } // } // } #[cfg(feature = "v1")] impl From<PaymentsSessionRequest> for PaymentsSessionResponse { fn from(item: PaymentsSessionRequest) -> Self { let client_secret: Secret<String, pii::ClientSecret> = Secret::new(item.client_secret); Self { session_token: vec![], payment_id: item.payment_id, client_secret, } } } #[cfg(feature = "v1")] impl From<PaymentsStartRequest> for PaymentsRequest { fn from(item: PaymentsStartRequest) -> Self { Self { payment_id: Some(PaymentIdType::PaymentIntentId(item.payment_id)), merchant_id: Some(item.merchant_id), ..Default::default() } } } impl From<AdditionalCardInfo> for CardResponse { fn from(card: AdditionalCardInfo) -> Self { Self { last4: card.last4, card_type: card.card_type, card_network: card.card_network, card_issuer: card.card_issuer, card_issuing_country: card.card_issuing_country, card_isin: card.card_isin, card_extended_bin: card.card_extended_bin, card_exp_month: card.card_exp_month, card_exp_year: card.card_exp_year, card_holder_name: card.card_holder_name, payment_checks: card.payment_checks, authentication_data: card.authentication_data, } } } impl From<KlarnaSdkPaymentMethod> for PaylaterResponse { fn from(klarna_sdk: KlarnaSdkPaymentMethod) -> Self { Self { klarna_sdk: Some(KlarnaSdkPaymentMethodResponse { payment_type: klarna_sdk.payment_type, }), } } } impl From<AdditionalPaymentData> for PaymentMethodDataResponse { fn from(payment_method_data: AdditionalPaymentData) -> Self { match payment_method_data { AdditionalPaymentData::Card(card) => Self::Card(Box::new(CardResponse::from(*card))), AdditionalPaymentData::PayLater { klarna_sdk } => match klarna_sdk { Some(sdk) => Self::PayLater(Box::new(PaylaterResponse::from(sdk))), None => Self::PayLater(Box::new(PaylaterResponse { klarna_sdk: None })), }, AdditionalPaymentData::Wallet { apple_pay, google_pay, samsung_pay, } => match (apple_pay, google_pay, samsung_pay) { (Some(apple_pay_pm), _, _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::ApplePay(Box::new( additional_info::WalletAdditionalDataForCard { last4: apple_pay_pm .display_name .clone() .chars() .rev() .take(4) .collect::<String>() .chars() .rev() .collect::<String>(), card_network: apple_pay_pm.network.clone(), card_type: Some(apple_pay_pm.pm_type.clone()), }, ))), })), (_, Some(google_pay_pm), _) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::GooglePay(Box::new(google_pay_pm))), })), (_, _, Some(samsung_pay_pm)) => Self::Wallet(Box::new(WalletResponse { details: Some(WalletResponseData::SamsungPay(Box::new(samsung_pay_pm))), })), _ => Self::Wallet(Box::new(WalletResponse { details: None })), }, AdditionalPaymentData::BankRedirect { bank_name, details } => { Self::BankRedirect(Box::new(BankRedirectResponse { bank_name, details })) } AdditionalPaymentData::Crypto { details } => { Self::Crypto(Box::new(CryptoResponse { details })) } AdditionalPaymentData::BankDebit { details } => { Self::BankDebit(Box::new(BankDebitResponse { details })) } AdditionalPaymentData::MandatePayment {} => Self::MandatePayment {}, AdditionalPaymentData::Reward {} => Self::Reward {}, AdditionalPaymentData::RealTimePayment { details } => { Self::RealTimePayment(Box::new(RealTimePaymentDataResponse { details })) } AdditionalPaymentData::Upi { details } => Self::Upi(Box::new(UpiResponse { details })), AdditionalPaymentData::BankTransfer { details } => { Self::BankTransfer(Box::new(BankTransferResponse { details })) } AdditionalPaymentData::Voucher { details } => { Self::Voucher(Box::new(VoucherResponse { details })) } AdditionalPaymentData::GiftCard { details } => { Self::GiftCard(Box::new(GiftCardResponse { details })) } AdditionalPaymentData::CardRedirect { details } => { Self::CardRedirect(Box::new(CardRedirectResponse { details })) } AdditionalPaymentData::CardToken { details } => { Self::CardToken(Box::new(CardTokenResponse { details })) } AdditionalPaymentData::OpenBanking { details } => { Self::OpenBanking(Box::new(OpenBankingResponse { details })) } AdditionalPaymentData::MobilePayment { details } => { Self::MobilePayment(Box::new(MobilePaymentResponse { details })) } } } } #[derive(Debug, Clone, serde::Serialize)] pub struct PgRedirectResponse { pub payment_id: id_type::PaymentId, pub status: api_enums::IntentStatus, pub gateway_id: String, pub customer_id: Option<id_type::CustomerId>, pub amount: Option<MinorUnit>, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url: String, pub params: Vec<(String, String)>, pub return_url_with_query_params: String, pub http_method: String, pub headers: Vec<(String, String)>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, PartialEq, Eq, serde::Deserialize)] pub struct RedirectionResponse { pub return_url_with_query_params: String, } #[derive(Debug, serde::Deserialize)] pub struct PaymentsResponseForm { pub transaction_id: String, // pub transaction_reference_id: String, pub merchant_id: id_type::MerchantId, pub order_id: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRetrieveRequest { /// The type of ID (ex: payment intent id, payment attempt id or connector txn id) #[schema(value_type = String)] pub resource_id: PaymentIdType, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: bool, /// The parameters passed to a retrieve request pub param: Option<String>, /// The name of the connector pub connector: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Debug, Default, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product #[schema(value_type = i64)] pub amount: MinorUnit, /// tax rate applicable to the product pub tax_rate: Option<f64>, /// total tax amount applicable to the product #[schema(value_type = Option<i64>)] pub total_tax_amount: Option<MinorUnit>, // Does the order includes shipping pub requires_shipping: Option<bool>, /// The image URL of the product pub product_img_link: Option<String>, /// ID of the product that is being purchased pub product_id: Option<String>, /// Category of the product that is being purchased pub category: Option<String>, /// Sub category of the product that is being purchased pub sub_category: Option<String>, /// Brand of the product that is being purchased pub brand: Option<String>, /// Type of the product that is being purchased pub product_type: Option<ProductType>, /// The tax code for the product pub product_tax_code: Option<String>, } impl masking::SerializableSecret for OrderDetailsWithAmount {} #[derive(Default, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct RedirectResponse { #[schema(value_type = Option<String>)] pub param: Option<Secret<String>>, #[schema(value_type = Option<Object>)] pub json_payload: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest {} #[cfg(feature = "v1")] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionRequest { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: String, /// The list of the supported wallets #[schema(value_type = Vec<PaymentMethodType>)] pub wallets: Vec<api_enums::PaymentMethodType>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// It's a token used for client side verification. #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The payment method that is to be used for the payment #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: api_enums::PaymentMethod, } #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsPostSessionTokensResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// Additional information required for redirection pub next_action: Option<NextActionData>, #[schema(value_type = IntentStatus, example = "failed", default = "requires_confirmation")] pub status: api_enums::IntentStatus, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Address, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Payment method type #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// Session Id pub session_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsDynamicTaxCalculationResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// net amount = amount + order_tax_amount + shipping_cost pub net_amount: MinorUnit, /// order tax amount calculated by tax connectors pub order_tax_amount: Option<MinorUnit>, /// shipping cost for the order pub shipping_cost: Option<MinorUnit>, /// amount in Base Unit display format pub display_amount: DisplayAmountOnSdk, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DisplayAmountOnSdk { /// net amount = amount + order_tax_amount + shipping_cost #[schema(value_type = String)] pub net_amount: StringMajorUnit, /// order tax amount calculated by tax connectors #[schema(value_type = String)] pub order_tax_amount: Option<StringMajorUnit>, /// shipping cost for the order #[schema(value_type = String)] pub shipping_cost: Option<StringMajorUnit>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedMethodsParameters { /// The list of allowed auth methods (ex: 3DS, No3DS, PAN_ONLY etc) pub allowed_auth_methods: Vec<String>, /// The list of allowed card networks (ex: AMEX,JCB etc) pub allowed_card_networks: Vec<String>, /// Is billing address required #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_required: Option<bool>, /// Billing address parameters #[serde(skip_serializing_if = "Option::is_none")] pub billing_address_parameters: Option<GpayBillingAddressParameters>, /// Whether assurance details are required #[serde(skip_serializing_if = "Option::is_none")] pub assurance_details_required: Option<bool>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayBillingAddressParameters { /// Is billing phone number required pub phone_number_required: bool, /// Billing address format pub format: GpayBillingAddressFormat, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub enum GpayBillingAddressFormat { FULL, MIN, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenParameters { /// The name of the connector #[serde(skip_serializing_if = "Option::is_none")] pub gateway: Option<String>, /// The merchant ID registered in the connector associated #[serde(skip_serializing_if = "Option::is_none")] pub gateway_merchant_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none", rename = "stripe:version")] pub stripe_version: Option<String>, #[serde( skip_serializing_if = "Option::is_none", rename = "stripe:publishableKey" )] pub stripe_publishable_key: Option<String>, /// The protocol version for encryption #[serde(skip_serializing_if = "Option::is_none")] pub protocol_version: Option<String>, /// The public key provided by the merchant #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<String>)] pub public_key: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTokenizationSpecification { /// The token specification type(ex: PAYMENT_GATEWAY) #[serde(rename = "type")] pub token_specification_type: String, /// The parameters for the token specification Google Pay pub parameters: GpayTokenParameters, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayAllowedPaymentMethods { /// The type of payment method #[serde(rename = "type")] pub payment_method_type: String, /// The parameters Google Pay requires pub parameters: GpayAllowedMethodsParameters, /// The tokenization specification for Google Pay pub tokenization_specification: GpayTokenizationSpecification, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayTransactionInfo { /// The country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total price status (ex: 'FINAL') pub total_price_status: String, /// The total price #[schema(value_type = String, example = "38.02")] pub total_price: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GpayMerchantInfo { /// The merchant Identifier that needs to be passed while invoking Gpay SDK #[serde(skip_serializing_if = "Option::is_none")] pub merchant_id: Option<String>, /// The name of the merchant that needs to be displayed on Gpay PopUp pub merchant_name: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpayMetaData { pub merchant_info: GpayMerchantInfo, pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GpaySessionTokenData { #[serde(rename = "google_pay")] pub data: GpayMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeSessionTokenData { #[serde(rename = "paze")] pub data: PazeMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PazeMetadata { pub client_id: String, pub client_name: String, pub client_profile_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum SamsungPayCombinedMetadata { // This is to support the Samsung Pay decryption flow with application credentials, // where the private key, certificates, or any other information required for decryption // will be obtained from the application configuration. ApplicationCredentials(SamsungPayApplicationCredentials), MerchantCredentials(SamsungPayMerchantCredentials), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPaySessionTokenData { #[serde(rename = "samsung_pay")] pub data: SamsungPayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayMerchantCredentials { pub service_id: String, pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SamsungPayApplicationCredentials { pub merchant_display_name: String, pub merchant_business_country: api_enums::CountryAlpha2, pub allowed_brands: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkMetaData { pub client_id: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaypalSdkSessionTokenData { #[serde(rename = "paypal_sdk")] pub data: PaypalSdkMetaData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepaySessionRequest { pub merchant_identifier: String, pub display_name: String, pub initiative: String, pub initiative_context: String, } /// Some connectors like Apple Pay, Airwallex and Noon might require some additional information, find specific details in the child attributes below. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ConnectorMetadata { pub apple_pay: Option<ApplepayConnectorMetadataRequest>, pub airwallex: Option<AirwallexData>, pub noon: Option<NoonData>, pub braintree: Option<BraintreeData>, } impl ConnectorMetadata { pub fn from_value( value: pii::SecretSerdeValue, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ParsingError> { value .parse_value::<Self>("ConnectorMetadata") .change_context(common_utils::errors::ParsingError::StructParseFailure( "Metadata", )) } pub fn get_apple_pay_certificates(self) -> Option<(Secret<String>, Secret<String>)> { self.apple_pay.and_then(|applepay_metadata| { applepay_metadata .session_token_data .map(|session_token_data| { let SessionTokenInfo { certificate, certificate_keys, .. } = session_token_data; (certificate, certificate_keys) }) }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct AirwallexData { /// payload required by airwallex payload: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct NoonData { /// Information about the order category that merchant wants to specify at connector level. (e.g. In Noon Payments it can take values like "pay", "food", or any other custom string set by the merchant in Noon's Dashboard) pub order_category: Option<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BraintreeData { /// Information about the merchant_account_id that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_account_id: Option<Secret<String>>, /// Information about the merchant_config_currency that merchant wants to specify at connector level. #[schema(value_type = String)] pub merchant_config_currency: Option<api_enums::Currency>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ApplepayConnectorMetadataRequest { pub session_token_data: Option<SessionTokenInfo>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepaySessionTokenData { pub apple_pay: ApplePayMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplepayCombinedSessionTokenData { pub apple_pay_combined: ApplePayCombinedMetadata, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplepaySessionTokenMetadata { ApplePayCombined(ApplePayCombinedMetadata), ApplePay(ApplePayMetadata), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ApplePayMetadata { pub payment_request_data: PaymentRequestMetadata, pub session_token_data: SessionTokenInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub enum ApplePayCombinedMetadata { Simplified { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenForSimplifiedApplePay, }, Manual { payment_request_data: PaymentRequestMetadata, session_token_data: SessionTokenInfo, }, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentRequestMetadata { pub supported_networks: Vec<String>, pub merchant_capabilities: Vec<String>, pub label: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenInfo { #[schema(value_type = String)] pub certificate: Secret<String>, #[schema(value_type = String)] pub certificate_keys: Secret<String>, pub merchant_identifier: String, pub display_name: String, pub initiative: ApplepayInitiative, pub initiative_context: Option<String>, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, #[serde(flatten)] pub payment_processing_details_at: Option<PaymentProcessingDetailsAt>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, Display, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplepayInitiative { Web, Ios, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(tag = "payment_processing_details_at")] pub enum PaymentProcessingDetailsAt { Hyperswitch(PaymentProcessingDetails), Connector, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] pub struct PaymentProcessingDetails { #[schema(value_type = String)] pub payment_processing_certificate: Secret<String>, #[schema(value_type = String)] pub payment_processing_certificate_key: Secret<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct SessionTokenForSimplifiedApplePay { pub initiative_context: String, #[schema(value_type = Option<CountryAlpha2>)] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayWalletDetails { pub google_pay: GooglePayDetails, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayDetails { pub provider_details: GooglePayProviderDetails, pub cards: GpayAllowedMethodsParameters, } // Google Pay Provider Details can of two types: GooglePayMerchantDetails or GooglePayHyperSwitchDetails // GooglePayHyperSwitchDetails is not implemented yet #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum GooglePayProviderDetails { GooglePayMerchantDetails(GooglePayMerchantDetails), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantDetails { pub merchant_info: GooglePayMerchantInfo, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayMerchantInfo { pub merchant_name: String, pub merchant_id: Option<String>, pub tokenization_specification: GooglePayTokenizationSpecification, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationSpecification { #[serde(rename = "type")] pub tokenization_type: GooglePayTokenizationType, pub parameters: GooglePayTokenizationParameters, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, strum::Display)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] #[strum(serialize_all = "SCREAMING_SNAKE_CASE")] pub enum GooglePayTokenizationType { PaymentGateway, Direct, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct GooglePayTokenizationParameters { pub gateway: Option<String>, pub public_key: Option<Secret<String>>, pub private_key: Option<Secret<String>>, pub recipient_id: Option<Secret<String>>, pub gateway_merchant_id: Option<Secret<String>>, pub stripe_publishable_key: Option<Secret<String>>, pub stripe_version: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(tag = "wallet_name")] #[serde(rename_all = "snake_case")] pub enum SessionToken { /// The session response structure for Google Pay GooglePay(Box<GpaySessionTokenResponse>), /// The session response structure for Samsung Pay SamsungPay(Box<SamsungPaySessionTokenResponse>), /// The session response structure for Klarna Klarna(Box<KlarnaSessionTokenResponse>), /// The session response structure for PayPal Paypal(Box<PaypalSessionTokenResponse>), /// The session response structure for Apple Pay ApplePay(Box<ApplepaySessionTokenResponse>), /// Session token for OpenBanking PIS flow OpenBanking(OpenBankingSessionToken), /// The session response structure for Paze Paze(Box<PazeSessionTokenResponse>), /// The sessions response structure for ClickToPay ClickToPay(Box<ClickToPaySessionResponse>), /// Whenever there is no session token response or an error in session response NoSessionTokenReceived, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PazeSessionTokenResponse { /// Paze Client ID pub client_id: String, /// Client Name to be displayed on the Paze screen pub client_name: String, /// Paze Client Profile ID pub client_profile_id: String, /// The transaction currency code #[schema(value_type = Currency, example = "USD")] pub transaction_currency_code: api_enums::Currency, /// The transaction amount #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, /// Email Address #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email_address: Option<Email>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum GpaySessionTokenResponse { /// Google pay response involving third party sdk ThirdPartyResponse(GooglePayThirdPartySdk), /// Google pay session response for non third party sdk GooglePaySession(GooglePaySessionResponse), } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePayThirdPartySdk { /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GooglePaySessionResponse { /// The merchant info pub merchant_info: GpayMerchantInfo, /// Is shipping address required pub shipping_address_required: bool, /// Is email required pub email_required: bool, /// Shipping address parameters pub shipping_address_parameters: GpayShippingAddressParameters, /// List of the allowed payment meythods pub allowed_payment_methods: Vec<GpayAllowedPaymentMethods>, /// The transaction info Google Pay requires pub transaction_info: GpayTransactionInfo, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The name of the connector pub connector: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// Secrets for sdk display and payment pub secrets: Option<SecretInfoToInitiateSdk>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPaySessionTokenResponse { /// Samsung Pay API version pub version: String, /// Samsung Pay service ID to which session call needs to be made pub service_id: String, /// Order number of the transaction pub order_number: String, /// Field containing merchant information #[serde(rename = "merchant")] pub merchant_payment_information: SamsungPayMerchantPaymentInformation, /// Field containing the payment amount pub amount: SamsungPayAmountDetails, /// Payment protocol type pub protocol: SamsungPayProtocolType, /// List of supported card brands pub allowed_brands: Vec<String>, /// Is billing address required to be collected from wallet pub billing_address_required: bool, /// Is shipping address required to be collected from wallet pub shipping_address_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayProtocolType { Protocol3ds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayMerchantPaymentInformation { /// Merchant name, this will be displayed on the Samsung Pay screen pub name: String, /// Merchant domain that process payments, required for web payments pub url: Option<String>, /// Merchant country code #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct SamsungPayAmountDetails { #[serde(rename = "option")] /// Amount format to be displayed pub amount_format: SamsungPayAmountFormat, /// The currency code #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// The total amount of the transaction #[serde(rename = "total")] #[schema(value_type = String, example = "38.02")] pub total_amount: StringMajorUnit, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "SCREAMING_SNAKE_CASE")] pub enum SamsungPayAmountFormat { /// Display the total amount only FormatTotalPriceOnly, /// Display "Total (Estimated amount)" and total amount FormatTotalEstimatedAmount, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct GpayShippingAddressParameters { /// Is shipping phone number required pub phone_number_required: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct KlarnaSessionTokenResponse { /// The session token for Klarna pub session_token: String, /// The identifier for the session pub session_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct PaypalSessionTokenResponse { /// Name of the connector pub connector: String, /// The session token for PayPal pub session_token: String, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct OpenBankingSessionToken { /// The session token for OpenBanking Connectors pub open_banking_session_token: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "lowercase")] pub struct ApplepaySessionTokenResponse { /// Session object for Apple Pay /// The session_token_data will be null for iOS devices because the Apple Pay session call is skipped, as there is no web domain involved #[serde(skip_serializing_if = "Option::is_none")] pub session_token_data: Option<ApplePaySessionResponse>, /// Payment request object for Apple Pay pub payment_request_data: Option<ApplePayPaymentRequest>, /// The session token is w.r.t this connector pub connector: String, /// Identifier for the delayed session response pub delayed_session_token: bool, /// The next action for the sdk (ex: calling confirm or sync call) pub sdk_next_action: SdkNextAction, /// The connector transaction id pub connector_reference_id: Option<String>, /// The public key id is to invoke third party sdk pub connector_sdk_public_key: Option<String>, /// The connector merchant id pub connector_merchant_id: Option<String>, } #[derive(Debug, Eq, PartialEq, serde::Serialize, Clone, ToSchema)] pub struct SdkNextAction { /// The type of next action pub next_action: NextActionCall, } #[derive(Debug, Eq, PartialEq, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum NextActionCall { /// The next action call is Post Session Tokens PostSessionTokens, /// The next action call is confirm Confirm, /// The next action call is sync Sync, /// The next action call is Complete Authorize CompleteAuthorize, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum ApplePaySessionResponse { /// We get this session response, when third party sdk is involved ThirdPartySdk(ThirdPartySdkSessionResponse), /// We get this session response, when there is no involvement of third party sdk /// This is the common response most of the times NoThirdPartySdk(NoThirdPartySdkSessionResponse), /// This is for the empty session response NoSessionResponse, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all(deserialize = "camelCase"))] pub struct NoThirdPartySdkSessionResponse { /// Timestamp at which session is requested pub epoch_timestamp: u64, /// Timestamp at which session expires pub expires_at: u64, /// The identifier for the merchant session pub merchant_session_identifier: String, /// Apple pay generated unique ID (UUID) value pub nonce: String, /// The identifier for the merchant pub merchant_identifier: String, /// The domain name of the merchant which is registered in Apple Pay pub domain_name: String, /// The name to be displayed on Apple Pay button pub display_name: String, /// A string which represents the properties of a payment pub signature: String, /// The identifier for the operational analytics pub operational_analytics_identifier: String, /// The number of retries to get the session response pub retries: u8, /// The identifier for the connector transaction pub psp_id: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ThirdPartySdkSessionResponse { pub secrets: SecretInfoToInitiateSdk, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct SecretInfoToInitiateSdk { // Authorization secrets used by client to initiate sdk #[schema(value_type = String)] pub display: Secret<String>, // Authorization secrets used by client for payment #[schema(value_type = String)] pub payment: Secret<String>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayPaymentRequest { /// The code for country #[schema(value_type = CountryAlpha2, example = "US")] pub country_code: api_enums::CountryAlpha2, /// The code for currency #[schema(value_type = Currency, example = "USD")] pub currency_code: api_enums::Currency, /// Represents the total for the payment. pub total: AmountInfo, /// The list of merchant capabilities(ex: whether capable of 3ds or no-3ds) pub merchant_capabilities: Option<Vec<String>>, /// The list of supported networks pub supported_networks: Option<Vec<String>>, pub merchant_identifier: Option<String>, /// The required billing contact fields for connector #[serde(skip_serializing_if = "Option::is_none")] pub required_billing_contact_fields: Option<ApplePayBillingContactFields>, #[serde(skip_serializing_if = "Option::is_none")] /// The required shipping contacht fields for connector pub required_shipping_contact_fields: Option<ApplePayShippingContactFields>, /// Recurring payment request for apple pay Merchant Token #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_request: Option<ApplePayRecurringPaymentRequest>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringPaymentRequest { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingRequest, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment #[serde(skip_serializing_if = "Option::is_none")] pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_u_r_l: common_utils::types::Url, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingRequest { /// The amount of the recurring payment #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The time that the payment occurs as part of a successful transaction pub payment_timing: ApplePayPaymentTiming, /// The date of the first payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[serde(skip_serializing_if = "Option::is_none")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval #[serde(skip_serializing_if = "Option::is_none")] pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ApplePayPaymentTiming { /// A value that specifies that the payment occurs when the transaction is complete Immediate, /// A value that specifies that the payment occurs on a regular basis Recurring, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayBillingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct ApplePayShippingContactFields(pub Vec<ApplePayAddressParameters>); #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub enum ApplePayAddressParameters { PostalAddress, Phone, Email, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema, serde::Deserialize)] pub struct AmountInfo { /// The label must be the name of the merchant. pub label: String, /// A value that indicates whether the line item(Ex: total, tax, discount, or grand total) is final or pending. #[serde(rename = "type")] pub total_type: Option<String>, /// The total amount for the payment in majot unit string (Ex: 38.02) #[schema(value_type = String, example = "38.02")] pub amount: StringMajorUnit, } #[derive(Debug, Clone, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayErrorResponse { pub status_code: String, pub status_message: String, } #[cfg(feature = "v1")] #[derive(Default, Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::PaymentId, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK #[schema(value_type = String)] pub client_secret: Secret<String, pii::ClientSecret>, /// The list of session token object pub session_token: Vec<SessionToken>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, Clone, ToSchema)] pub struct PaymentsSessionResponse { /// The identifier for the payment #[schema(value_type = String)] pub payment_id: id_type::GlobalPaymentId, /// The list of session token object pub session_token: Vec<SessionToken>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBody { /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// This is a token which expires after 15 minutes, used from the client to authenticate and create sessions from the SDK pub client_secret: Option<String>, /// If enabled provides list of captures linked to latest attempt pub expand_captures: Option<bool>, /// If enabled provides list of attempts linked to payment intent pub expand_attempts: Option<bool>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentRetrieveBodyWithCredentials { /// The identifier for payment. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, /// Decider to enable or disable the connector call for retrieve request pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCompleteAuthorizeRequest { /// The unique identifier for the payment #[serde(skip_deserializing)] pub payment_id: id_type::PaymentId, /// The shipping address for the payment pub shipping: Option<Address>, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: Option<ThreeDsCompletionIndicator>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsCancelRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The reason for the payment cancel pub cancellation_reason: Option<String>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>, deprecated)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsIncrementalAuthorizationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The total amount including previously authorized amount and additional amount #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Reason for incremental authorization pub reason: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// Client Secret #[schema(value_type = String)] pub client_secret: Secret<String>, /// SDK Information if request is from SDK pub sdk_information: Option<SdkInformation>, /// Device Channel indicating whether request is coming from App or Browser pub device_channel: DeviceChannel, /// Indicates if 3DS method data was successfully completed or not pub threeds_method_comp_ind: ThreeDsCompletionIndicator, } /// Indicates if 3DS method data was successfully completed or not #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: Option<enums::AttemptStatus>, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsManualUpdateResponse { /// The identifier for the payment pub payment_id: id_type::PaymentId, /// The identifier for the payment attempt pub attempt_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// The status of the attempt pub attempt_status: enums::AttemptStatus, /// Error code of the connector pub error_code: Option<String>, /// Error message of the connector pub error_message: Option<String>, /// Error reason of the connector pub error_reason: Option<String>, /// A unique identifier for a payment provided by the connector pub connector_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub enum ThreeDsCompletionIndicator { /// 3DS method successfully completed #[serde(rename = "Y")] Success, /// 3DS method was not successful #[serde(rename = "N")] Failure, /// 3DS method URL was unavailable #[serde(rename = "U")] NotAvailable, } /// Device Channel indicating whether request is coming from App or Browser #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema, Eq, PartialEq)] pub enum DeviceChannel { #[serde(rename = "APP")] App, #[serde(rename = "BRW")] Browser, } /// SDK Information if request is from SDK #[derive(Default, Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct SdkInformation { /// Unique ID created on installations of the 3DS Requestor App on a Consumer Device pub sdk_app_id: String, /// JWE Object containing data encrypted by the SDK for the DS to decrypt pub sdk_enc_data: String, /// Public key component of the ephemeral key pair generated by the 3DS SDK pub sdk_ephem_pub_key: HashMap<String, String>, /// Unique transaction identifier assigned by the 3DS SDK pub sdk_trans_id: String, /// Identifies the vendor and version for the 3DS SDK that is integrated in a 3DS Requestor App pub sdk_reference_number: String, /// Indicates maximum amount of time in minutes pub sdk_max_timeout: u8, /// Indicates the type of 3DS SDK pub sdk_type: Option<SdkType>, } /// Enum representing the type of 3DS SDK. #[derive(Serialize, Deserialize, Debug, Clone, ToSchema)] pub enum SdkType { #[serde(rename = "01")] DefaultSdk, #[serde(rename = "02")] SplitSdk, #[serde(rename = "03")] LimitedSdk, #[serde(rename = "04")] BrowserSdk, #[serde(rename = "05")] ShellSdk, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentMethodsListRequest {} #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponseForPayments { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypesForPayments>, /// The list of payment methods that are saved by the given customer /// This field is only returned if the customer_id is provided in the request #[schema(value_type = Option<Vec<CustomerPaymentMethod>>)] pub customer_payment_methods: Option<Vec<payment_methods::CustomerPaymentMethod>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypesForPayments { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] #[schema(value_type = Option<PaymentMethodSubtypeSpecificData>)] pub extra_information: Option<payment_methods::PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. #[schema(value_type = Option<RequiredFieldInfo>)] pub required_fields: Option<Vec<payment_methods::RequiredFieldInfo>>, /// surcharge details for this payment method type if exists #[schema(value_type = Option<SurchargeDetailsResponse>)] pub surcharge_details: Option<payment_methods::SurchargeDetailsResponse>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct PaymentsExternalAuthenticationResponse { /// Indicates the transaction status #[serde(rename = "trans_status")] #[schema(value_type = TransactionStatus)] pub transaction_status: common_enums::TransactionStatus, /// Access Server URL to be used for challenge submission pub acs_url: Option<String>, /// Challenge request which should be sent to acs_url pub challenge_request: Option<String>, /// Unique identifier assigned by the EMVCo(Europay, Mastercard and Visa) pub acs_reference_number: Option<String>, /// Unique identifier assigned by the ACS to identify a single transaction pub acs_trans_id: Option<String>, /// Unique identifier assigned by the 3DS Server to identify a single transaction pub three_dsserver_trans_id: Option<String>, /// Contains the JWS object created by the ACS for the ARes(Authentication Response) message pub acs_signed_content: Option<String>, /// Three DS Requestor URL pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred pub three_ds_requestor_app_url: Option<String>, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsApproveRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct PaymentsRejectRequest { /// The identifier for the payment #[serde(skip)] pub payment_id: id_type::PaymentId, } #[derive(Default, Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentsStartRequest { /// Unique identifier for the payment. This ensures idempotency for multiple payments /// that have been done by a single merchant. This field is auto generated and is returned in the API response. pub payment_id: id_type::PaymentId, /// The identifier for the Merchant Account. pub merchant_id: id_type::MerchantId, /// The identifier for the payment transaction pub attempt_id: String, } /// additional data that might be required by hyperswitch #[cfg(feature = "v2")] #[derive(Debug, Default, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, /// revenue recovery data for payment intent pub payment_revenue_recovery_metadata: Option<PaymentRevenueRecoveryMetadata>, } #[cfg(feature = "v2")] impl FeatureMetadata { pub fn get_retry_count(&self) -> Option<u16> { self.payment_revenue_recovery_metadata .as_ref() .map(|metadata| metadata.total_retry_count) } pub fn set_payment_revenue_recovery_metadata_using_api( self, payment_revenue_recovery_metadata: PaymentRevenueRecoveryMetadata, ) -> Self { Self { redirect_response: self.redirect_response, search_tags: self.search_tags, apple_pay_recurring_details: self.apple_pay_recurring_details, payment_revenue_recovery_metadata: Some(payment_revenue_recovery_metadata), } } } /// additional data that might be required by hyperswitch #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct FeatureMetadata { /// Redirection response coming in request as metadata field only for redirection scenarios #[schema(value_type = Option<RedirectResponse>)] pub redirect_response: Option<RedirectResponse>, /// Additional tags to be used for global search #[schema(value_type = Option<Vec<String>>)] pub search_tags: Option<Vec<HashedString<WithType>>>, /// Recurring payment details required for apple pay Merchant Token pub apple_pay_recurring_details: Option<ApplePayRecurringDetails>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRecurringDetails { /// A description of the recurring payment that Apple Pay displays to the user in the payment sheet pub payment_description: String, /// The regular billing cycle for the recurring payment, including start and end dates, an interval, and an interval count pub regular_billing: ApplePayRegularBillingDetails, /// A localized billing agreement that the payment sheet displays to the user before the user authorizes the payment pub billing_agreement: Option<String>, /// A URL to a web page where the user can update or delete the payment method for the recurring payment #[schema(value_type = String, example = "https://hyperswitch.io")] pub management_url: common_utils::types::Url, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ApplePayRegularBillingDetails { /// The label that Apple Pay displays to the user in the payment sheet with the recurring details pub label: String, /// The date of the first payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_start_date: Option<PrimitiveDateTime>, /// The date of the final payment #[schema(example = "2023-09-10T23:59:59Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub recurring_payment_end_date: Option<PrimitiveDateTime>, /// The amount of time — in calendar units, such as day, month, or year — that represents a fraction of the total payment interval pub recurring_payment_interval_unit: Option<RecurringPaymentIntervalUnit>, /// The number of interval units that make up the total payment interval pub recurring_payment_interval_count: Option<i32>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum RecurringPaymentIntervalUnit { Year, Month, Day, Hour, Minute, } ///frm message is an object sent inside the payments response...when frm is invoked, its value is Some(...), else its None #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct FrmMessage { pub frm_name: String, pub frm_transaction_id: Option<String>, pub frm_transaction_type: Option<String>, pub frm_status: Option<String>, pub frm_score: Option<i32>, pub frm_reason: Option<serde_json::Value>, pub frm_error: Option<String>, } #[cfg(feature = "v2")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::GlobalPaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } #[cfg(feature = "v1")] mod payment_id_type { use std::{borrow::Cow, fmt}; use serde::{ de::{self, Visitor}, Deserializer, }; use super::PaymentIdType; struct PaymentIdVisitor; struct OptionalPaymentIdVisitor; impl Visitor<'_> for PaymentIdVisitor { type Value = PaymentIdType; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> where E: de::Error, { common_utils::id_type::PaymentId::try_from(Cow::Owned(value.to_string())) .map_err(de::Error::custom) .map(PaymentIdType::PaymentIntentId) } } impl<'de> Visitor<'de> for OptionalPaymentIdVisitor { type Value = Option<PaymentIdType>; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("payment id") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: Deserializer<'de>, { deserializer.deserialize_any(PaymentIdVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } fn visit_unit<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'a, D>(deserializer: D) -> Result<PaymentIdType, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_any(PaymentIdVisitor) } pub(crate) fn deserialize_option<'a, D>( deserializer: D, ) -> Result<Option<PaymentIdType>, D::Error> where D: Deserializer<'a>, { deserializer.deserialize_option(OptionalPaymentIdVisitor) } } pub mod amount { use serde::de; use super::Amount; struct AmountVisitor; struct OptionalAmountVisitor; use crate::payments::MinorUnit; // This is defined to provide guarded deserialization of amount // which itself handles zero and non-zero values internally impl de::Visitor<'_> for AmountVisitor { type Value = Amount; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "amount as integer") } fn visit_u64<E>(self, v: u64) -> Result<Self::Value, E> where E: de::Error, { let v = i64::try_from(v).map_err(|_| { E::custom(format!( "invalid value `{v}`, expected an integer between 0 and {}", i64::MAX )) })?; self.visit_i64(v) } fn visit_i64<E>(self, v: i64) -> Result<Self::Value, E> where E: de::Error, { if v.is_negative() { return Err(E::custom(format!( "invalid value `{v}`, expected a positive integer" ))); } Ok(Amount::from(MinorUnit::new(v))) } } impl<'de> de::Visitor<'de> for OptionalAmountVisitor { type Value = Option<Amount>; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { write!(formatter, "option of amount (as integer)") } fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error> where D: serde::Deserializer<'de>, { deserializer.deserialize_i64(AmountVisitor).map(Some) } fn visit_none<E>(self) -> Result<Self::Value, E> where E: de::Error, { Ok(None) } } #[allow(dead_code)] pub(crate) fn deserialize<'de, D>(deserializer: D) -> Result<Amount, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_any(AmountVisitor) } pub(crate) fn deserialize_option<'de, D>(deserializer: D) -> Result<Option<Amount>, D::Error> where D: de::Deserializer<'de>, { deserializer.deserialize_option(OptionalAmountVisitor) } } #[cfg(test)] mod tests { #![allow(clippy::unwrap_used)] use super::*; #[test] fn test_mandate_type() { let mandate_type = MandateType::default(); assert_eq!( serde_json::to_string(&mandate_type).unwrap(), r#"{"multi_use":null}"# ) } } #[derive(Default, Debug, serde::Deserialize, Clone, ToSchema, serde::Serialize)] pub struct RetrievePaymentLinkRequest { /// It's a token used for client side verification. pub client_secret: Option<String>, } #[derive(Clone, Debug, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkResponse { /// URL for rendering the open payment link pub link: String, /// URL for rendering the secure payment link pub secure_link: Option<String>, /// Identifier for the payment link pub payment_link_id: String, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RetrievePaymentLinkResponse { /// Identifier for Payment Link pub payment_link_id: String, /// Identifier for Merchant #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Open payment link (without any security checks and listing SPMs) pub link_to_pay: String, /// The payment amount. Amount for the payment in the lowest denomination of the currency #[schema(value_type = i64, example = 6540)] pub amount: MinorUnit, /// Date and time of Payment Link creation #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// Date and time of Expiration for Payment Link #[serde(with = "common_utils::custom_serde::iso8601::option")] pub expiry: Option<PrimitiveDateTime>, /// Description for Payment Link pub description: Option<String>, /// Status Of the Payment Link pub status: PaymentLinkStatus, #[schema(value_type = Option<Currency>)] pub currency: Option<api_enums::Currency>, /// Secure payment link (with security checks and listing saved payment methods) pub secure_link: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PaymentLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub payment_id: id_type::PaymentId, } #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum PaymentLinkData { PaymentLinkDetails(Box<PaymentLinkDetails>), PaymentLinkStatusDetails(Box<PaymentLinkStatusDetails>), } #[derive(Debug, serde::Serialize, Clone)] pub struct PaymentLinkDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub pub_key: String, pub client_secret: String, pub payment_id: id_type::PaymentId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub merchant_logo: String, pub return_url: String, pub merchant_name: String, pub order_details: Option<Vec<OrderDetailsWithStringAmount>>, pub max_items_visible_after_collapse: i8, pub theme: String, pub merchant_description: Option<String>, pub sdk_layout: String, pub display_sdk_only: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub background_image: Option<admin::PaymentLinkBackgroundImageConfig>, pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, pub branding_visibility: Option<bool>, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub status: api_enums::IntentStatus, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize, Clone)] pub struct SecurePaymentLinkDetails { pub enabled_saved_payment_method: bool, pub hide_card_nickname_field: bool, pub show_card_form_by_default: bool, #[serde(flatten)] pub payment_link_details: PaymentLinkDetails, pub payment_button_text: Option<String>, pub skip_status_screen: Option<bool>, pub custom_message_for_card_terms: Option<String>, pub payment_button_colour: Option<String>, pub payment_button_text_colour: Option<String>, pub background_colour: Option<String>, pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, pub enable_button_only_on_form_ready: bool, } #[derive(Debug, serde::Serialize)] pub struct PaymentLinkStatusDetails { pub amount: StringMajorUnit, pub currency: api_enums::Currency, pub payment_id: id_type::PaymentId, pub merchant_logo: String, pub merchant_name: String, #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, pub status: PaymentLinkStatusWrap, pub error_code: Option<String>, pub error_message: Option<String>, pub redirect: bool, pub theme: String, pub return_url: String, pub locale: Option<String>, pub transaction_details: Option<Vec<admin::PaymentLinkTransactionDetails>>, pub unified_code: Option<String>, pub unified_message: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PaymentLinkListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// The time at which payment link is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Time less than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lt" )] pub created_lt: Option<PrimitiveDateTime>, /// Time greater than the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.gt" )] pub created_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde( default, with = "common_utils::custom_serde::iso8601::option", rename = "created.lte" )] pub created_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the payment link created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] #[serde(rename = "created.gte")] pub created_gte: Option<PrimitiveDateTime>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PaymentLinkListResponse { /// The number of payment links included in the list pub size: usize, // The list of payment link response objects pub data: Vec<PaymentLinkResponse>, } /// Configure a custom payment link for the particular payment #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentCreatePaymentLinkConfig { #[serde(flatten)] #[schema(value_type = Option<PaymentLinkConfigRequest>)] /// Theme config for the particular payment pub theme_config: admin::PaymentLinkConfigRequest, } #[derive(Debug, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct OrderDetailsWithStringAmount { /// Name of the product that is being purchased #[schema(max_length = 255, example = "shirt")] pub product_name: String, /// The quantity of the product to be purchased #[schema(example = 1)] pub quantity: u16, /// the amount per quantity of product pub amount: StringMajorUnit, /// Product Image link pub product_img_link: Option<String>, } /// Status Of the Payment Link #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentLinkStatus { Active, Expired, } #[derive(PartialEq, Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case")] #[serde(untagged)] pub enum PaymentLinkStatusWrap { PaymentLinkStatus(PaymentLinkStatus), IntentStatus(api_enums::IntentStatus), } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct ExtendedCardInfoResponse { // Encrypted customer payment method data pub payload: String, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, ToSchema)] pub struct ClickToPaySessionResponse { pub dpa_id: String, pub dpa_name: String, pub locale: String, pub card_brands: Vec<String>, pub acquirer_bin: String, pub acquirer_merchant_id: String, pub merchant_category_code: String, pub merchant_country_code: String, #[schema(value_type = String, example = "38.02")] pub transaction_amount: StringMajorUnit, #[schema(value_type = Currency)] pub transaction_currency_code: common_enums::Currency, #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone_number: Option<Secret<String>>, #[schema(max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, pub phone_country_code: Option<String>, /// provider Eg: Visa, Mastercard #[schema(value_type = Option<CtpServiceProvider>)] pub provider: Option<api_enums::CtpServiceProvider>, pub dpa_client_id: Option<String>, } #[cfg(feature = "v1")] #[cfg(test)] mod payments_request_api_contract { #![allow(clippy::unwrap_used)] #![allow(clippy::panic)] use std::str::FromStr; use super::*; #[test] fn test_successful_card_deser() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "card", "payment_method_data": { "card": { "card_number": "4242424242424242", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "joseph Doe", "card_cvc": "123" } } } "#; let expected_card_number_string = "4242424242424242"; let expected_card_number = CardNumber::from_str(expected_card_number_string).unwrap(); let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); if let Some(PaymentMethodData::Card(card_data)) = payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data { assert_eq!(card_data.card_number, expected_card_number); } else { panic!("Received unexpected response") } } #[test] fn test_successful_payment_method_reward() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method": "reward", "payment_method_data": "reward", "payment_method_type": "evoucher" } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert_eq!( payments_request .unwrap() .payment_method_data .unwrap() .payment_method_data, Some(PaymentMethodData::Reward) ); } #[test] fn test_payment_method_data_with_payment_method_billing() { let payments_request = r#" { "amount": 6540, "currency": "USD", "payment_method_data": { "billing": { "address": { "line1": "1467", "line2": "Harrison Street", "city": "San Fransico", "state": "California", "zip": "94122", "country": "US", "first_name": "Narayan", "last_name": "Bhat" } } } } "#; let payments_request = serde_json::from_str::<PaymentsRequest>(payments_request); assert!(payments_request.is_ok()); assert!(payments_request .unwrap() .payment_method_data .unwrap() .billing .is_some()); } } #[cfg(test)] mod payments_response_api_contract { #![allow(clippy::unwrap_used)] use super::*; #[derive(Debug, serde::Serialize)] struct TestPaymentsResponse { #[serde(serialize_with = "serialize_payment_method_data_response")] payment_method_data: Option<PaymentMethodDataResponseWithBilling>, } #[test] fn test_reward_payment_response() { let payment_method_response_with_billing = PaymentMethodDataResponseWithBilling { payment_method_data: Some(PaymentMethodDataResponse::Reward {}), billing: None, }; let payments_response = TestPaymentsResponse { payment_method_data: Some(payment_method_response_with_billing), }; let expected_response = r#"{"payment_method_data":"reward"}"#; let stringified_payments_response = payments_response.encode_to_string_of_json(); assert_eq!(stringified_payments_response.unwrap(), expected_response); } } /// Set of tests to extract billing details from payment method data /// These are required for backwards compatibility #[cfg(test)] mod billing_from_payment_method_data { #![allow(clippy::unwrap_used)] use common_enums::CountryAlpha2; use masking::ExposeOptionInterface; use super::*; const TEST_COUNTRY: CountryAlpha2 = CountryAlpha2::US; const TEST_FIRST_NAME: &str = "John"; const TEST_LAST_NAME: &str = "Wheat Dough"; const TEST_FULL_NAME: &str = "John Wheat Dough"; const TEST_FIRST_NAME_SINGLE: &str = "John"; #[test] fn test_wallet_payment_method_data_paypal() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let paypal_wallet_payment_method_data = PaymentMethodData::Wallet(WalletData::PaypalRedirect(PaypalRedirection { email: Some(test_email.clone()), })); let billing_address = paypal_wallet_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert!(billing_address.address.is_none()); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_redirect_payment_method_data_eps() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankRedirectBilling { billing_name: Some(test_first_name.clone()), email: Some(test_email.clone()), }; let eps_bank_redirect_payment_method_data = PaymentMethodData::BankRedirect(BankRedirectData::Eps { billing_details: Some(bank_redirect_billing), bank_name: None, country: Some(TEST_COUNTRY), }); let billing_address = eps_bank_redirect_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.country.unwrap(), TEST_COUNTRY); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_paylater_payment_method_data_klarna() { let test_email: Email = Email::try_from("example@example.com".to_string()).unwrap(); let klarna_paylater_payment_method_data = PaymentMethodData::PayLater(PayLaterData::KlarnaRedirect { billing_email: Some(test_email.clone()), billing_country: Some(TEST_COUNTRY), }); let billing_address = klarna_paylater_payment_method_data .get_billing_address() .unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!( billing_address.address.unwrap().country.unwrap(), TEST_COUNTRY ); assert!(billing_address.phone.is_none()); } #[test] fn test_bank_debit_payment_method_data_ach() { let test_email = Email::try_from("example@example.com".to_string()).unwrap(); let test_first_name = Secret::new(String::from("Chaser")); let bank_redirect_billing = BankDebitBilling { name: Some(test_first_name.clone()), address: None, email: Some(test_email.clone()), }; let ach_bank_debit_payment_method_data = PaymentMethodData::BankDebit(BankDebitData::AchBankDebit { billing_details: Some(bank_redirect_billing), account_number: Secret::new("1234".to_string()), routing_number: Secret::new("1235".to_string()), card_holder_name: None, bank_account_holder_name: None, bank_name: None, bank_type: None, bank_holder_type: None, }); let billing_address = ach_bank_debit_payment_method_data .get_billing_address() .unwrap(); let address_details = billing_address.address.unwrap(); assert_eq!(billing_address.email.unwrap(), test_email); assert_eq!(address_details.first_name.unwrap(), test_first_name); assert!(billing_address.phone.is_none()); } #[test] fn test_card_payment_method_data() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FIRST_NAME_SINGLE.into())), ..Default::default() }); let billing_address = card_payment_method_data.get_billing_address(); let billing_address = billing_address.unwrap(); assert_eq!( billing_address.address.unwrap().first_name.expose_option(), Some(TEST_FIRST_NAME_SINGLE.into()) ); } #[test] fn test_card_payment_method_data_empty() { let card_payment_method_data = PaymentMethodData::Card(Card::default()); let billing_address = card_payment_method_data.get_billing_address(); assert!(billing_address.is_none()); } #[test] fn test_card_payment_method_data_full_name() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new(TEST_FULL_NAME.into())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address().unwrap(); let billing_address = billing_details.address.unwrap(); assert_eq!( billing_address.first_name.expose_option(), Some(TEST_FIRST_NAME.into()) ); assert_eq!( billing_address.last_name.expose_option(), Some(TEST_LAST_NAME.into()) ); } #[test] fn test_card_payment_method_data_empty_string() { let card_payment_method_data = PaymentMethodData::Card(Card { card_holder_name: Some(Secret::new("".to_string())), ..Default::default() }); let billing_details = card_payment_method_data.get_billing_address(); assert!(billing_details.is_none()); } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct PaymentRevenueRecoveryMetadata { /// Total number of billing connector + recovery retries for a payment intent. #[schema(value_type = u16,example = "1")] pub total_retry_count: u16, /// Flag for the payment connector's call pub payment_connector_transmission: PaymentConnectorTransmission, /// Billing Connector Id to update the invoices #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Payment Connector Id to retry the payments #[schema(value_type = String, example = "mca_1234567890")] pub active_attempt_payment_connector_id: id_type::MerchantConnectorAccountId, /// Billing Connector Payment Details #[schema(value_type = BillingConnectorPaymentDetails)] pub billing_connector_payment_details: BillingConnectorPaymentDetails, /// Payment Method Type #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// PaymentMethod Subtype #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Connector, example = "stripe")] pub connector: common_enums::connector_enums::Connector, } #[cfg(feature = "v2")] impl PaymentRevenueRecoveryMetadata { pub fn set_payment_transmission_field_for_api_request( &mut self, payment_connector_transmission: PaymentConnectorTransmission, ) { self.payment_connector_transmission = payment_connector_transmission; } pub fn get_payment_token_for_api_request(&self) -> ProcessorPaymentToken { ProcessorPaymentToken { processor_payment_token: self .billing_connector_payment_details .payment_processor_token .clone(), merchant_connector_id: Some(self.active_attempt_payment_connector_id.clone()), } } pub fn get_merchant_connector_id_for_api_request(&self) -> id_type::MerchantConnectorAccountId { self.active_attempt_payment_connector_id.clone() } } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[cfg(feature = "v2")] pub struct BillingConnectorPaymentDetails { /// Payment Processor Token to process the Revenue Recovery Payment pub payment_processor_token: String, /// Billing Connector's Customer Id pub connector_customer_id: String, } // Serialize is required because the api event requires Serialize to be implemented #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[cfg(feature = "v2")] pub struct PaymentsAttemptRecordRequest { /// The amount details for the payment attempt. pub amount_details: PaymentAttemptAmountDetails, #[schema(value_type = AttemptStatus, example = "charged")] pub status: enums::AttemptStatus, /// The billing details of the payment attempt. This address will be used for invoicing. pub billing: Option<Address>, /// The shipping address for the payment attempt. pub shipping: Option<Address>, /// Error details provided by the billing processor. pub error: Option<RecordAttemptErrorDetails>, /// A description for the payment attempt. #[schema(example = "It's my first payment request", value_type = Option<String>)] pub description: Option<common_utils::types::Description>, /// A unique identifier for a payment provided by the connector. pub connector_transaction_id: Option<common_utils::types::ConnectorTransactionId>, /// The payment method type used for payment attempt. #[schema(value_type = PaymentMethod, example = "bank_transfer")] pub payment_method_type: api_enums::PaymentMethod, /// The name of the payment connector through which the payment attempt was made. #[schema(value_type = Option<Connector>, example = "stripe")] pub connector: Option<common_enums::connector_enums::Connector>, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub billing_connector_id: id_type::MerchantConnectorAccountId, /// Billing connector id to update the invoices. #[schema(value_type = String, example = "mca_1234567890")] pub payment_merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// The payment method subtype to be used for the payment. This should match with the `payment_method_data` provided #[schema(value_type = PaymentMethodType, example = "apple_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// The payment instrument data to be used for the payment attempt. pub payment_method_data: Option<PaymentMethodDataRequest>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Additional data that might be required by hyperswitch based on the requested features by the merchants. pub feature_metadata: Option<PaymentAttemptFeatureMetadata>, /// The time at which payment attempt was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub transaction_created_at: Option<PrimitiveDateTime>, /// payment method token at payment processor end. #[schema(value_type = String, example = "1234567890")] pub processor_payment_method_token: String, /// customer id at payment connector for which mandate is attached. #[schema(value_type = String, example = "cust_12345")] pub connector_customer_id: String, } /// Error details for the payment #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct RecordAttemptErrorDetails { /// error code sent by billing connector. pub code: String, /// error message sent by billing connector. pub message: String, /// This field can be returned for both approved and refused Mastercard payments. /// This code provides additional information about the type of transaction or the reason why the payment failed. /// If the payment failed, the network advice code gives guidance on if and when you can retry the payment. pub network_advice_code: Option<String>, /// For card errors resulting from a card issuer decline, a brand specific 2, 3, or 4 digit code which indicates the reason the authorization failed. pub network_decline_code: Option<String>, /// A string indicating how to proceed with an network error if payment gateway provide one. This is used to understand the network error code better. pub network_error_message: Option<String>, }
79,544
1,953
hyperswitch
crates/api_models/src/locker_migration.rs
.rs
#[derive(Debug, Clone, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct MigrateCardResponse { pub status_message: String, pub status_code: String, pub customers_moved: usize, pub cards_moved: usize, }
57
1,954
hyperswitch
crates/api_models/src/webhooks.rs
.rs
use common_utils::custom_serde; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; #[cfg(feature = "payouts")] use crate::payouts; use crate::{disputes, enums as api_enums, mandates, payments, refunds}; #[derive(Clone, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, Copy)] #[serde(rename_all = "snake_case")] pub enum IncomingWebhookEvent { /// Authorization + Capture success PaymentIntentFailure, /// Authorization + Capture failure PaymentIntentSuccess, PaymentIntentProcessing, PaymentIntentPartiallyFunded, PaymentIntentCancelled, PaymentIntentCancelFailure, PaymentIntentAuthorizationSuccess, PaymentIntentAuthorizationFailure, PaymentIntentCaptureSuccess, PaymentIntentCaptureFailure, PaymentActionRequired, EventNotSupported, SourceChargeable, SourceTransactionCreated, RefundFailure, RefundSuccess, DisputeOpened, DisputeExpired, DisputeAccepted, DisputeCancelled, DisputeChallenged, // dispute has been successfully challenged by the merchant DisputeWon, // dispute has been unsuccessfully challenged DisputeLost, MandateActive, MandateRevoked, EndpointVerification, ExternalAuthenticationARes, FrmApproved, FrmRejected, #[cfg(feature = "payouts")] PayoutSuccess, #[cfg(feature = "payouts")] PayoutFailure, #[cfg(feature = "payouts")] PayoutProcessing, #[cfg(feature = "payouts")] PayoutCancelled, #[cfg(feature = "payouts")] PayoutCreated, #[cfg(feature = "payouts")] PayoutExpired, #[cfg(feature = "payouts")] PayoutReversed, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryPaymentFailure, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryPaymentSuccess, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryPaymentPending, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] RecoveryInvoiceCancel, } pub enum WebhookFlow { Payment, #[cfg(feature = "payouts")] Payout, Refund, Dispute, Subscription, ReturnResponse, BankTransfer, Mandate, ExternalAuthentication, FraudCheck, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] Recovery, } #[derive(Clone, Debug, Eq, PartialEq, Serialize, Deserialize)] /// This enum tells about the affect a webhook had on an object pub enum WebhookResponseTracker { #[cfg(feature = "v1")] Payment { payment_id: common_utils::id_type::PaymentId, status: common_enums::IntentStatus, }, #[cfg(feature = "v2")] Payment { payment_id: common_utils::id_type::GlobalPaymentId, status: common_enums::IntentStatus, }, #[cfg(feature = "payouts")] Payout { payout_id: String, status: common_enums::PayoutStatus, }, #[cfg(feature = "v1")] Refund { payment_id: common_utils::id_type::PaymentId, refund_id: String, status: common_enums::RefundStatus, }, #[cfg(feature = "v2")] Refund { payment_id: common_utils::id_type::GlobalPaymentId, refund_id: String, status: common_enums::RefundStatus, }, #[cfg(feature = "v1")] Dispute { dispute_id: String, payment_id: common_utils::id_type::PaymentId, status: common_enums::DisputeStatus, }, #[cfg(feature = "v2")] Dispute { dispute_id: String, payment_id: common_utils::id_type::GlobalPaymentId, status: common_enums::DisputeStatus, }, Mandate { mandate_id: String, status: common_enums::MandateStatus, }, NoEffect, Relay { relay_id: common_utils::id_type::RelayId, status: common_enums::RelayStatus, }, } impl WebhookResponseTracker { #[cfg(feature = "v1")] pub fn get_payment_id(&self) -> Option<common_utils::id_type::PaymentId> { match self { Self::Payment { payment_id, .. } | Self::Refund { payment_id, .. } | Self::Dispute { payment_id, .. } => Some(payment_id.to_owned()), Self::NoEffect | Self::Mandate { .. } => None, #[cfg(feature = "payouts")] Self::Payout { .. } => None, Self::Relay { .. } => None, } } #[cfg(feature = "v2")] pub fn get_payment_id(&self) -> Option<common_utils::id_type::GlobalPaymentId> { match self { Self::Payment { payment_id, .. } | Self::Refund { payment_id, .. } | Self::Dispute { payment_id, .. } => Some(payment_id.to_owned()), Self::NoEffect | Self::Mandate { .. } => None, #[cfg(feature = "payouts")] Self::Payout { .. } => None, Self::Relay { .. } => None, } } } impl From<IncomingWebhookEvent> for WebhookFlow { fn from(evt: IncomingWebhookEvent) -> Self { match evt { IncomingWebhookEvent::PaymentIntentFailure | IncomingWebhookEvent::PaymentIntentSuccess | IncomingWebhookEvent::PaymentIntentProcessing | IncomingWebhookEvent::PaymentActionRequired | IncomingWebhookEvent::PaymentIntentPartiallyFunded | IncomingWebhookEvent::PaymentIntentCancelled | IncomingWebhookEvent::PaymentIntentCancelFailure | IncomingWebhookEvent::PaymentIntentAuthorizationSuccess | IncomingWebhookEvent::PaymentIntentAuthorizationFailure | IncomingWebhookEvent::PaymentIntentCaptureSuccess | IncomingWebhookEvent::PaymentIntentCaptureFailure => Self::Payment, IncomingWebhookEvent::EventNotSupported => Self::ReturnResponse, IncomingWebhookEvent::RefundSuccess | IncomingWebhookEvent::RefundFailure => { Self::Refund } IncomingWebhookEvent::MandateActive | IncomingWebhookEvent::MandateRevoked => { Self::Mandate } IncomingWebhookEvent::DisputeOpened | IncomingWebhookEvent::DisputeAccepted | IncomingWebhookEvent::DisputeExpired | IncomingWebhookEvent::DisputeCancelled | IncomingWebhookEvent::DisputeChallenged | IncomingWebhookEvent::DisputeWon | IncomingWebhookEvent::DisputeLost => Self::Dispute, IncomingWebhookEvent::EndpointVerification => Self::ReturnResponse, IncomingWebhookEvent::SourceChargeable | IncomingWebhookEvent::SourceTransactionCreated => Self::BankTransfer, IncomingWebhookEvent::ExternalAuthenticationARes => Self::ExternalAuthentication, IncomingWebhookEvent::FrmApproved | IncomingWebhookEvent::FrmRejected => { Self::FraudCheck } #[cfg(feature = "payouts")] IncomingWebhookEvent::PayoutSuccess | IncomingWebhookEvent::PayoutFailure | IncomingWebhookEvent::PayoutProcessing | IncomingWebhookEvent::PayoutCancelled | IncomingWebhookEvent::PayoutCreated | IncomingWebhookEvent::PayoutExpired | IncomingWebhookEvent::PayoutReversed => Self::Payout, #[cfg(all(feature = "revenue_recovery", feature = "v2"))] IncomingWebhookEvent::RecoveryInvoiceCancel | IncomingWebhookEvent::RecoveryPaymentFailure | IncomingWebhookEvent::RecoveryPaymentPending | IncomingWebhookEvent::RecoveryPaymentSuccess => Self::Recovery, } } } pub type MerchantWebhookConfig = std::collections::HashSet<IncomingWebhookEvent>; #[derive(Clone)] pub enum RefundIdType { RefundId(String), ConnectorRefundId(String), } #[derive(Clone)] pub enum MandateIdType { MandateId(String), ConnectorMandateId(String), } #[derive(Clone)] pub enum AuthenticationIdType { AuthenticationId(String), ConnectorAuthenticationId(String), } #[cfg(feature = "payouts")] #[derive(Clone)] pub enum PayoutIdType { PayoutAttemptId(String), ConnectorPayoutId(String), } #[derive(Clone)] pub enum ObjectReferenceId { PaymentId(payments::PaymentIdType), RefundId(RefundIdType), MandateId(MandateIdType), ExternalAuthenticationID(AuthenticationIdType), #[cfg(feature = "payouts")] PayoutId(PayoutIdType), #[cfg(all(feature = "revenue_recovery", feature = "v2"))] InvoiceId(InvoiceIdType), } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] #[derive(Clone)] pub enum InvoiceIdType { ConnectorInvoiceId(String), } #[cfg(all(feature = "revenue_recovery", feature = "v2"))] impl ObjectReferenceId { pub fn get_connector_transaction_id_as_string( self, ) -> Result<String, common_utils::errors::ValidationError> { match self { Self::PaymentId( payments::PaymentIdType::ConnectorTransactionId(id) ) => Ok(id), Self::PaymentId(_)=>Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "ConnectorTransactionId variant of PaymentId is required but received otherr variant", }, ), Self::RefundId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received RefundId", }, ), Self::MandateId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received MandateId", }, ), Self::ExternalAuthenticationID(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received ExternalAuthenticationID", }, ), #[cfg(feature = "payouts")] Self::PayoutId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received PayoutId", }, ), Self::InvoiceId(_) => Err( common_utils::errors::ValidationError::IncorrectValueProvided { field_name: "PaymentId is required but received InvoiceId", }, ) } } } pub struct IncomingWebhookDetails { pub object_reference_id: ObjectReferenceId, pub resource_object: Vec<u8>, } #[derive(Debug, Serialize, ToSchema)] pub struct OutgoingWebhook { /// The merchant id of the merchant #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The unique event id for each webhook pub event_id: String, /// The type of event this webhook corresponds to. #[schema(value_type = EventType)] pub event_type: api_enums::EventType, /// This is specific to the flow, for ex: it will be `PaymentsResponse` for payments flow pub content: OutgoingWebhookContent, /// The time at which webhook was sent #[serde(default, with = "custom_serde::iso8601")] pub timestamp: PrimitiveDateTime, } #[derive(Debug, Clone, Serialize, ToSchema)] #[serde(tag = "type", content = "object", rename_all = "snake_case")] #[cfg(feature = "v1")] pub enum OutgoingWebhookContent { #[schema(value_type = PaymentsResponse, title = "PaymentsResponse")] PaymentDetails(Box<payments::PaymentsResponse>), #[schema(value_type = RefundResponse, title = "RefundResponse")] RefundDetails(Box<refunds::RefundResponse>), #[schema(value_type = DisputeResponse, title = "DisputeResponse")] DisputeDetails(Box<disputes::DisputeResponse>), #[schema(value_type = MandateResponse, title = "MandateResponse")] MandateDetails(Box<mandates::MandateResponse>), #[cfg(feature = "payouts")] #[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")] PayoutDetails(Box<payouts::PayoutCreateResponse>), } #[derive(Debug, Serialize, ToSchema)] #[serde(tag = "type", content = "object", rename_all = "snake_case")] #[cfg(feature = "v2")] pub enum OutgoingWebhookContent { #[schema(value_type = PaymentsResponse, title = "PaymentsResponse")] PaymentDetails(Box<payments::PaymentsResponse>), #[schema(value_type = RefundResponse, title = "RefundResponse")] RefundDetails(Box<refunds::RefundResponse>), #[schema(value_type = DisputeResponse, title = "DisputeResponse")] DisputeDetails(Box<disputes::DisputeResponse>), #[schema(value_type = MandateResponse, title = "MandateResponse")] MandateDetails(Box<mandates::MandateResponse>), #[cfg(feature = "payouts")] #[schema(value_type = PayoutCreateResponse, title = "PayoutCreateResponse")] PayoutDetails(Box<payouts::PayoutCreateResponse>), } #[derive(Debug, Clone, Serialize)] pub struct ConnectorWebhookSecrets { pub secret: Vec<u8>, pub additional_secret: Option<masking::Secret<String>>, } #[cfg(all(feature = "v2", feature = "revenue_recovery"))] impl IncomingWebhookEvent { pub fn is_recovery_transaction_event(&self) -> bool { matches!( self, Self::RecoveryPaymentFailure | Self::RecoveryPaymentSuccess | Self::RecoveryPaymentPending ) } }
3,113
1,955
hyperswitch
crates/api_models/src/mandates.rs
.rs
use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::{enums as api_enums, payments}; #[derive(Default, Debug, Deserialize, Serialize)] pub struct MandateId { pub mandate_id: String, } #[derive(Default, Debug, Deserialize, Serialize, ToSchema)] pub struct MandateRevokedResponse { /// The identifier for mandate pub mandate_id: String, /// The status for mandates #[schema(value_type = MandateStatus)] pub status: api_enums::MandateStatus, /// If there was an error while calling the connectors the code is received here #[schema(example = "E0001")] pub error_code: Option<String>, /// If there was an error while calling the connector the error message is received here #[schema(example = "Failed while verifying the card")] pub error_message: Option<String>, } #[derive(Default, Debug, Deserialize, Serialize, ToSchema, Clone)] pub struct MandateResponse { /// The identifier for mandate pub mandate_id: String, /// The status for mandates #[schema(value_type = MandateStatus)] pub status: api_enums::MandateStatus, /// The identifier for payment method pub payment_method_id: String, /// The payment method pub payment_method: String, /// The payment method type pub payment_method_type: Option<String>, /// The card details for mandate pub card: Option<MandateCardDetails>, /// Details about the customer’s acceptance #[schema(value_type = Option<CustomerAcceptance>)] pub customer_acceptance: Option<payments::CustomerAcceptance>, } #[derive(Default, Debug, Deserialize, Serialize, ToSchema, Clone)] pub struct MandateCardDetails { /// The last 4 digits of card pub last4_digits: Option<String>, /// The expiry month of card #[schema(value_type = Option<String>)] pub card_exp_month: Option<Secret<String>>, /// The expiry year of card #[schema(value_type = Option<String>)] pub card_exp_year: Option<Secret<String>>, /// The card holder name #[schema(value_type = Option<String>)] pub card_holder_name: Option<Secret<String>>, /// The token from card locker #[schema(value_type = Option<String>)] pub card_token: Option<Secret<String>>, /// The card scheme network for the particular card pub scheme: Option<String>, /// The country code in in which the card was issued pub issuer_country: Option<String>, #[schema(value_type = Option<String>)] /// A unique identifier alias to identify a particular card pub card_fingerprint: Option<Secret<String>>, /// The first 6 digits of card pub card_isin: Option<String>, /// The bank that issued the card pub card_issuer: Option<String>, /// The network that facilitates payment card transactions #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// The type of the payment card pub card_type: Option<String>, /// The nick_name of the card holder #[schema(value_type = Option<String>)] pub nick_name: Option<Secret<String>>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MandateListConstraints { /// limit on the number of objects to return pub limit: Option<i64>, /// offset on the number of objects to return pub offset: Option<i64>, /// status of the mandate pub mandate_status: Option<api_enums::MandateStatus>, /// connector linked to mandate pub connector: Option<String>, /// The time at which mandate is created #[schema(example = "2022-09-10T10:11:12Z")] pub created_time: Option<PrimitiveDateTime>, /// Time less than the mandate created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(rename = "created_time.lt")] pub created_time_lt: Option<PrimitiveDateTime>, /// Time greater than the mandate created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(rename = "created_time.gt")] pub created_time_gt: Option<PrimitiveDateTime>, /// Time less than or equals to the mandate created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(rename = "created_time.lte")] pub created_time_lte: Option<PrimitiveDateTime>, /// Time greater than or equals to the mandate created time #[schema(example = "2022-09-10T10:11:12Z")] #[serde(rename = "created_time.gte")] pub created_time_gte: Option<PrimitiveDateTime>, } /// Details required for recurring payment #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum RecurringDetails { MandateId(String), PaymentMethodId(String), ProcessorPaymentToken(ProcessorPaymentToken), /// Network transaction ID and Card Details for MIT payments when payment_method_data /// is not stored in the application NetworkTransactionIdAndCardDetails(NetworkTransactionIdAndCardDetails), } /// Processor payment token for MIT payments where payment_method_data is not available #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct ProcessorPaymentToken { pub processor_payment_token: String, #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct NetworkTransactionIdAndCardDetails { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: cards::CardNumber, /// The card's expiry month #[schema(value_type = String, example = "24")] pub card_exp_month: Secret<String>, /// The card's expiry year #[schema(value_type = String, example = "24")] pub card_exp_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, /// The name of the issuer of card #[schema(example = "chase")] pub card_issuer: Option<String>, /// The card network for the card #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: Option<api_enums::CardNetwork>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, #[schema(example = "JP_AMEX")] pub bank_code: Option<String>, /// The card holder's nick name #[schema(value_type = Option<String>, example = "John Test")] pub nick_name: Option<Secret<String>>, /// The network transaction ID provided by the card network during a CIT (Customer Initiated Transaction), /// where `setup_future_usage` is set to `off_session`. #[schema(value_type = String)] pub network_transaction_id: Secret<String>, } impl RecurringDetails { pub fn is_network_transaction_id_and_card_details_flow(self) -> bool { matches!(self, Self::NetworkTransactionIdAndCardDetails(_)) } }
1,729
1,956
hyperswitch
crates/api_models/src/recon.rs
.rs
use common_utils::{id_type, pii}; use masking::Secret; use crate::enums; #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct ReconUpdateMerchantRequest { pub recon_status: enums::ReconStatus, pub user_email: pii::Email, } #[derive(Debug, serde::Serialize)] pub struct ReconTokenResponse { pub token: Secret<String>, } #[derive(Debug, serde::Serialize)] pub struct ReconStatusResponse { pub recon_status: enums::ReconStatus, } #[derive(serde::Serialize, Debug)] pub struct VerifyTokenResponse { pub merchant_id: id_type::MerchantId, pub user_email: pii::Email, #[serde(skip_serializing_if = "Option::is_none")] pub acl: Option<String>, }
165
1,957
hyperswitch
crates/api_models/src/routing.rs
.rs
use std::fmt::Debug; use common_utils::{errors::ParsingError, ext_traits::ValueExt, pii}; pub use euclid::{ dssa::types::EuclidAnalysable, frontend::{ ast, dir::{DirKeyKind, EuclidDirFilter}, }, }; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::enums::{RoutableConnectors, TransactionType}; #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum ConnectorSelection { Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), } impl ConnectorSelection { pub fn get_connector_list(&self) -> Vec<RoutableConnectorChoice> { match self { Self::Priority(list) => list.clone(), Self::VolumeSplit(splits) => { splits.iter().map(|split| split.connector.clone()).collect() } } } } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingConfigRequest { pub name: String, pub description: String, pub algorithm: RoutingAlgorithm, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingConfigRequest { pub name: Option<String>, pub description: Option<String>, pub algorithm: Option<RoutingAlgorithm>, #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, } #[derive(Debug, serde::Serialize, ToSchema)] pub struct ProfileDefaultRoutingConfig { #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, pub connectors: Vec<RoutableConnectorChoice>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingRetrieveQuery { pub limit: Option<u16>, pub offset: Option<u8>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingRetrieveLinkQuery { pub profile_id: Option<common_utils::id_type::ProfileId>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct RoutingRetrieveLinkQueryWrapper { pub routing_query: RoutingRetrieveQuery, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] /// Response of the retrieved routing configs for a merchant account pub struct RoutingRetrieveResponse { pub algorithm: Option<MerchantRoutingAlgorithm>, } #[derive(Debug, serde::Serialize, ToSchema)] #[serde(untagged)] pub enum LinkedRoutingConfigRetrieveResponse { MerchantAccountBased(RoutingRetrieveResponse), ProfileBased(Vec<RoutingDictionaryRecord>), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] /// Routing Algorithm specific to merchants pub struct MerchantRoutingAlgorithm { #[schema(value_type = String)] pub id: common_utils::id_type::RoutingId, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, pub name: String, pub description: String, pub algorithm: RoutingAlgorithm, pub created_at: i64, pub modified_at: i64, pub algorithm_for: TransactionType, } impl EuclidDirFilter for ConnectorSelection { const ALLOWED: &'static [DirKeyKind] = &[ DirKeyKind::PaymentMethod, DirKeyKind::CardBin, DirKeyKind::CardType, DirKeyKind::CardNetwork, DirKeyKind::PayLaterType, DirKeyKind::WalletType, DirKeyKind::UpiType, DirKeyKind::BankRedirectType, DirKeyKind::BankDebitType, DirKeyKind::CryptoType, DirKeyKind::MetaData, DirKeyKind::PaymentAmount, DirKeyKind::PaymentCurrency, DirKeyKind::AuthenticationType, DirKeyKind::MandateAcceptanceType, DirKeyKind::MandateType, DirKeyKind::PaymentType, DirKeyKind::SetupFutureUsage, DirKeyKind::CaptureMethod, DirKeyKind::BillingCountry, DirKeyKind::BusinessCountry, DirKeyKind::BusinessLabel, DirKeyKind::MetaData, DirKeyKind::RewardType, DirKeyKind::VoucherType, DirKeyKind::CardRedirectType, DirKeyKind::BankTransferType, DirKeyKind::RealTimePaymentType, ]; } impl EuclidAnalysable for ConnectorSelection { fn get_dir_value_for_analysis( &self, rule_name: String, ) -> Vec<(euclid::frontend::dir::DirValue, euclid::types::Metadata)> { self.get_connector_list() .into_iter() .map(|connector_choice| { let connector_name = connector_choice.connector.to_string(); let mca_id = connector_choice.merchant_connector_id.clone(); ( euclid::frontend::dir::DirValue::Connector(Box::new(connector_choice.into())), std::collections::HashMap::from_iter([( "CONNECTOR_SELECTION".to_string(), serde_json::json!({ "rule_name": rule_name, "connector_name": connector_name, "mca_id": mca_id, }), )]), ) }) .collect() } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq)] pub struct ConnectorVolumeSplit { pub connector: RoutableConnectorChoice, pub split: u8, } /// Routable Connector chosen for a payment #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(from = "RoutableChoiceSerde", into = "RoutableChoiceSerde")] pub struct RoutableConnectorChoice { #[serde(skip)] pub choice_kind: RoutableChoiceKind, pub connector: RoutableConnectors, #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema, PartialEq)] pub enum RoutableChoiceKind { OnlyConnector, FullStruct, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(untagged)] pub enum RoutableChoiceSerde { OnlyConnector(Box<RoutableConnectors>), FullStruct { connector: RoutableConnectors, merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, }, } impl std::fmt::Display for RoutableConnectorChoice { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let base = self.connector.to_string(); if let Some(mca_id) = &self.merchant_connector_id { return write!(f, "{}:{}", base, mca_id.get_string_repr()); } write!(f, "{}", base) } } impl From<RoutableConnectorChoice> for ast::ConnectorChoice { fn from(value: RoutableConnectorChoice) -> Self { Self { connector: value.connector, } } } impl PartialEq for RoutableConnectorChoice { fn eq(&self, other: &Self) -> bool { self.connector.eq(&other.connector) && self.merchant_connector_id.eq(&other.merchant_connector_id) } } impl Eq for RoutableConnectorChoice {} impl From<RoutableChoiceSerde> for RoutableConnectorChoice { fn from(value: RoutableChoiceSerde) -> Self { match value { RoutableChoiceSerde::OnlyConnector(connector) => Self { choice_kind: RoutableChoiceKind::OnlyConnector, connector: *connector, merchant_connector_id: None, }, RoutableChoiceSerde::FullStruct { connector, merchant_connector_id, } => Self { choice_kind: RoutableChoiceKind::FullStruct, connector, merchant_connector_id, }, } } } impl From<RoutableConnectorChoice> for RoutableChoiceSerde { fn from(value: RoutableConnectorChoice) -> Self { match value.choice_kind { RoutableChoiceKind::OnlyConnector => Self::OnlyConnector(Box::new(value.connector)), RoutableChoiceKind::FullStruct => Self::FullStruct { connector: value.connector, merchant_connector_id: value.merchant_connector_id, }, } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct RoutableConnectorChoiceWithStatus { pub routable_connector_choice: RoutableConnectorChoice, pub status: bool, } impl RoutableConnectorChoiceWithStatus { pub fn new(routable_connector_choice: RoutableConnectorChoice, status: bool) -> Self { Self { routable_connector_choice, status, } } } #[derive(Debug, Copy, Clone, serde::Serialize, serde::Deserialize, strum::Display, ToSchema)] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum RoutingAlgorithmKind { Single, Priority, VolumeSplit, Advanced, Dynamic, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingPayloadWrapper { pub updated_config: Vec<RoutableConnectorChoice>, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde( tag = "type", content = "data", rename_all = "snake_case", try_from = "RoutingAlgorithmSerde" )] /// Routing Algorithm kind pub enum RoutingAlgorithm { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), #[schema(value_type=ProgramConnectorSelection)] Advanced(ast::Program<ConnectorSelection>), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum RoutingAlgorithmSerde { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), Advanced(ast::Program<ConnectorSelection>), } impl TryFrom<RoutingAlgorithmSerde> for RoutingAlgorithm { type Error = error_stack::Report<ParsingError>; fn try_from(value: RoutingAlgorithmSerde) -> Result<Self, Self::Error> { match &value { RoutingAlgorithmSerde::Priority(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Priority Algorithm", ))? } RoutingAlgorithmSerde::VolumeSplit(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Volume split Algorithm", ))? } _ => {} }; Ok(match value { RoutingAlgorithmSerde::Single(i) => Self::Single(i), RoutingAlgorithmSerde::Priority(i) => Self::Priority(i), RoutingAlgorithmSerde::VolumeSplit(i) => Self::VolumeSplit(i), RoutingAlgorithmSerde::Advanced(i) => Self::Advanced(i), }) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq)] #[serde( tag = "type", content = "data", rename_all = "snake_case", try_from = "StraightThroughAlgorithmSerde", into = "StraightThroughAlgorithmSerde" )] pub enum StraightThroughAlgorithm { #[schema(title = "Single")] Single(Box<RoutableConnectorChoice>), #[schema(title = "Priority")] Priority(Vec<RoutableConnectorChoice>), #[schema(title = "VolumeSplit")] VolumeSplit(Vec<ConnectorVolumeSplit>), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(tag = "type", content = "data", rename_all = "snake_case")] pub enum StraightThroughAlgorithmInner { Single(Box<RoutableConnectorChoice>), Priority(Vec<RoutableConnectorChoice>), VolumeSplit(Vec<ConnectorVolumeSplit>), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum StraightThroughAlgorithmSerde { Direct(StraightThroughAlgorithmInner), Nested { algorithm: StraightThroughAlgorithmInner, }, } impl TryFrom<StraightThroughAlgorithmSerde> for StraightThroughAlgorithm { type Error = error_stack::Report<ParsingError>; fn try_from(value: StraightThroughAlgorithmSerde) -> Result<Self, Self::Error> { let inner = match value { StraightThroughAlgorithmSerde::Direct(algorithm) => algorithm, StraightThroughAlgorithmSerde::Nested { algorithm } => algorithm, }; match &inner { StraightThroughAlgorithmInner::Priority(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Priority Algorithm", ))? } StraightThroughAlgorithmInner::VolumeSplit(i) if i.is_empty() => { Err(ParsingError::StructParseFailure( "Connectors list can't be empty for Volume split Algorithm", ))? } _ => {} }; Ok(match inner { StraightThroughAlgorithmInner::Single(single) => Self::Single(single), StraightThroughAlgorithmInner::Priority(plist) => Self::Priority(plist), StraightThroughAlgorithmInner::VolumeSplit(vsplit) => Self::VolumeSplit(vsplit), }) } } impl From<StraightThroughAlgorithm> for StraightThroughAlgorithmSerde { fn from(value: StraightThroughAlgorithm) -> Self { let inner = match value { StraightThroughAlgorithm::Single(conn) => StraightThroughAlgorithmInner::Single(conn), StraightThroughAlgorithm::Priority(plist) => { StraightThroughAlgorithmInner::Priority(plist) } StraightThroughAlgorithm::VolumeSplit(vsplit) => { StraightThroughAlgorithmInner::VolumeSplit(vsplit) } }; Self::Nested { algorithm: inner } } } impl From<StraightThroughAlgorithm> for RoutingAlgorithm { fn from(value: StraightThroughAlgorithm) -> Self { match value { StraightThroughAlgorithm::Single(conn) => Self::Single(conn), StraightThroughAlgorithm::Priority(conns) => Self::Priority(conns), StraightThroughAlgorithm::VolumeSplit(splits) => Self::VolumeSplit(splits), } } } impl RoutingAlgorithm { pub fn get_kind(&self) -> RoutingAlgorithmKind { match self { Self::Single(_) => RoutingAlgorithmKind::Single, Self::Priority(_) => RoutingAlgorithmKind::Priority, Self::VolumeSplit(_) => RoutingAlgorithmKind::VolumeSplit, Self::Advanced(_) => RoutingAlgorithmKind::Advanced, } } } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingAlgorithmRef { pub algorithm_id: Option<common_utils::id_type::RoutingId>, pub timestamp: i64, pub config_algo_id: Option<String>, pub surcharge_config_algo_id: Option<String>, } impl RoutingAlgorithmRef { pub fn update_algorithm_id(&mut self, new_id: common_utils::id_type::RoutingId) { self.algorithm_id = Some(new_id); self.timestamp = common_utils::date_time::now_unix_timestamp(); } pub fn update_conditional_config_id(&mut self, ids: String) { self.config_algo_id = Some(ids); self.timestamp = common_utils::date_time::now_unix_timestamp(); } pub fn update_surcharge_config_id(&mut self, ids: String) { self.surcharge_config_algo_id = Some(ids); self.timestamp = common_utils::date_time::now_unix_timestamp(); } pub fn parse_routing_algorithm( value: Option<pii::SecretSerdeValue>, ) -> Result<Option<Self>, error_stack::Report<ParsingError>> { value .map(|val| val.parse_value::<Self>("RoutingAlgorithmRef")) .transpose() } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingDictionaryRecord { #[schema(value_type = String)] pub id: common_utils::id_type::RoutingId, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, pub name: String, pub kind: RoutingAlgorithmKind, pub description: String, pub created_at: i64, pub modified_at: i64, pub algorithm_for: Option<TransactionType>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct RoutingDictionary { #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, pub active_id: Option<String>, pub records: Vec<RoutingDictionaryRecord>, } #[derive(serde::Serialize, serde::Deserialize, Debug, ToSchema)] #[serde(untagged)] pub enum RoutingKind { Config(RoutingDictionary), RoutingAlgorithm(Vec<RoutingDictionaryRecord>), } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct RoutingAlgorithmId { #[schema(value_type = String)] pub routing_algorithm_id: common_utils::id_type::RoutingId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingLinkWrapper { pub profile_id: common_utils::id_type::ProfileId, pub algorithm_id: RoutingAlgorithmId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DynamicAlgorithmWithTimestamp<T> { pub algorithm_id: Option<T>, pub timestamp: i64, } impl<T> DynamicAlgorithmWithTimestamp<T> { pub fn new(algorithm_id: Option<T>) -> Self { Self { algorithm_id, timestamp: common_utils::date_time::now_unix_timestamp(), } } } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct DynamicRoutingAlgorithmRef { pub success_based_algorithm: Option<SuccessBasedAlgorithm>, pub dynamic_routing_volume_split: Option<u8>, pub elimination_routing_algorithm: Option<EliminationRoutingAlgorithm>, pub contract_based_routing: Option<ContractRoutingAlgorithm>, } pub trait DynamicRoutingAlgoAccessor { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>; fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures; } impl DynamicRoutingAlgoAccessor for SuccessBasedAlgorithm { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> { self.algorithm_id_with_timestamp } fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures { &mut self.enabled_feature } } impl DynamicRoutingAlgoAccessor for EliminationRoutingAlgorithm { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> { self.algorithm_id_with_timestamp } fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures { &mut self.enabled_feature } } impl DynamicRoutingAlgoAccessor for ContractRoutingAlgorithm { fn get_algorithm_id_with_timestamp( self, ) -> DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId> { self.algorithm_id_with_timestamp } fn get_enabled_features(&mut self) -> &mut DynamicRoutingFeatures { &mut self.enabled_feature } } impl EliminationRoutingAlgorithm { pub fn new( algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp< common_utils::id_type::RoutingId, >, ) -> Self { Self { algorithm_id_with_timestamp, enabled_feature: DynamicRoutingFeatures::None, } } } impl SuccessBasedAlgorithm { pub fn new( algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp< common_utils::id_type::RoutingId, >, ) -> Self { Self { algorithm_id_with_timestamp, enabled_feature: DynamicRoutingFeatures::None, } } } impl DynamicRoutingAlgorithmRef { pub fn update(&mut self, new: Self) { if let Some(elimination_routing_algorithm) = new.elimination_routing_algorithm { self.elimination_routing_algorithm = Some(elimination_routing_algorithm) } if let Some(success_based_algorithm) = new.success_based_algorithm { self.success_based_algorithm = Some(success_based_algorithm) } if let Some(contract_based_routing) = new.contract_based_routing { self.contract_based_routing = Some(contract_based_routing) } } pub fn update_enabled_features( &mut self, algo_type: DynamicRoutingType, feature_to_enable: DynamicRoutingFeatures, ) { match algo_type { DynamicRoutingType::SuccessRateBasedRouting => { self.success_based_algorithm .as_mut() .map(|algo| algo.enabled_feature = feature_to_enable); } DynamicRoutingType::EliminationRouting => { self.elimination_routing_algorithm .as_mut() .map(|algo| algo.enabled_feature = feature_to_enable); } DynamicRoutingType::ContractBasedRouting => { self.contract_based_routing .as_mut() .map(|algo| algo.enabled_feature = feature_to_enable); } } } pub fn update_volume_split(&mut self, volume: Option<u8>) { self.dynamic_routing_volume_split = volume } } #[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize)] pub struct RoutingVolumeSplit { pub routing_type: RoutingType, pub split: u8, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct RoutingVolumeSplitWrapper { pub routing_info: RoutingVolumeSplit, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, Eq, PartialEq)] #[serde(rename_all = "snake_case")] pub enum RoutingType { #[default] Static, Dynamic, } impl RoutingType { pub fn is_dynamic_routing(self) -> bool { self == Self::Dynamic } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SuccessBasedAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] pub enabled_feature: DynamicRoutingFeatures, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ContractRoutingAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] pub enabled_feature: DynamicRoutingFeatures, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct EliminationRoutingAlgorithm { pub algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp<common_utils::id_type::RoutingId>, #[serde(default)] pub enabled_feature: DynamicRoutingFeatures, } impl EliminationRoutingAlgorithm { pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) { self.enabled_feature = feature_to_enable } } impl SuccessBasedAlgorithm { pub fn update_enabled_features(&mut self, feature_to_enable: DynamicRoutingFeatures) { self.enabled_feature = feature_to_enable } } impl DynamicRoutingAlgorithmRef { pub fn update_algorithm_id( &mut self, new_id: common_utils::id_type::RoutingId, enabled_feature: DynamicRoutingFeatures, dynamic_routing_type: DynamicRoutingType, ) { match dynamic_routing_type { DynamicRoutingType::SuccessRateBasedRouting => { self.success_based_algorithm = Some(SuccessBasedAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } DynamicRoutingType::EliminationRouting => { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } DynamicRoutingType::ContractBasedRouting => { self.contract_based_routing = Some(ContractRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(Some(new_id)), enabled_feature, }) } }; } pub fn disable_algorithm_id(&mut self, dynamic_routing_type: DynamicRoutingType) { match dynamic_routing_type { DynamicRoutingType::SuccessRateBasedRouting => { if let Some(success_based_algo) = &self.success_based_algorithm { self.success_based_algorithm = Some(SuccessBasedAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: success_based_algo.enabled_feature, }); } } DynamicRoutingType::EliminationRouting => { if let Some(elimination_based_algo) = &self.elimination_routing_algorithm { self.elimination_routing_algorithm = Some(EliminationRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: elimination_based_algo.enabled_feature, }); } } DynamicRoutingType::ContractBasedRouting => { if let Some(contract_based_algo) = &self.contract_based_routing { self.contract_based_routing = Some(ContractRoutingAlgorithm { algorithm_id_with_timestamp: DynamicAlgorithmWithTimestamp::new(None), enabled_feature: contract_based_algo.enabled_feature, }); } } } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ToggleDynamicRoutingQuery { pub enable: DynamicRoutingFeatures, } #[derive(Debug, Clone, Copy, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DynamicRoutingVolumeSplitQuery { pub split: u8, } #[derive( Debug, Default, Clone, Copy, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema, )] #[serde(rename_all = "snake_case")] pub enum DynamicRoutingFeatures { Metrics, DynamicConnectorSelection, #[default] None, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct DynamicRoutingUpdateConfigQuery { #[schema(value_type = String)] pub algorithm_id: common_utils::id_type::RoutingId, #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] pub struct ToggleDynamicRoutingWrapper { pub profile_id: common_utils::id_type::ProfileId, pub feature_to_enable: DynamicRoutingFeatures, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct ToggleDynamicRoutingPath { #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct EliminationRoutingConfig { pub params: Option<Vec<DynamicRoutingConfigParams>>, pub elimination_analyser_config: Option<EliminationAnalyserConfig>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct EliminationAnalyserConfig { pub bucket_size: Option<u64>, pub bucket_leak_interval_in_secs: Option<u64>, } impl Default for EliminationRoutingConfig { fn default() -> Self { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), elimination_analyser_config: Some(EliminationAnalyserConfig { bucket_size: Some(5), bucket_leak_interval_in_secs: Some(2), }), } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct SuccessBasedRoutingConfig { pub params: Option<Vec<DynamicRoutingConfigParams>>, pub config: Option<SuccessBasedRoutingConfigBody>, } impl Default for SuccessBasedRoutingConfig { fn default() -> Self { Self { params: Some(vec![DynamicRoutingConfigParams::PaymentMethod]), config: Some(SuccessBasedRoutingConfigBody { min_aggregates_size: Some(2), default_success_rate: Some(100.0), max_aggregates_size: Some(3), current_block_threshold: Some(CurrentBlockThreshold { duration_in_mins: Some(5), max_total_count: Some(2), }), specificity_level: SuccessRateSpecificityLevel::default(), }), } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema, strum::Display)] pub enum DynamicRoutingConfigParams { PaymentMethod, PaymentMethodType, AuthenticationType, Currency, Country, CardNetwork, CardBin, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct SuccessBasedRoutingConfigBody { pub min_aggregates_size: Option<u32>, pub default_success_rate: Option<f64>, pub max_aggregates_size: Option<u32>, pub current_block_threshold: Option<CurrentBlockThreshold>, #[serde(default)] pub specificity_level: SuccessRateSpecificityLevel, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] pub struct CurrentBlockThreshold { pub duration_in_mins: Option<u64>, pub max_total_count: Option<u64>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Default, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum SuccessRateSpecificityLevel { #[default] Merchant, Global, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SuccessBasedRoutingPayloadWrapper { pub updated_config: SuccessBasedRoutingConfig, pub algorithm_id: common_utils::id_type::RoutingId, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ContractBasedRoutingPayloadWrapper { pub updated_config: ContractBasedRoutingConfig, pub algorithm_id: common_utils::id_type::RoutingId, pub profile_id: common_utils::id_type::ProfileId, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct ContractBasedRoutingSetupPayloadWrapper { pub config: Option<ContractBasedRoutingConfig>, pub profile_id: common_utils::id_type::ProfileId, pub features_to_enable: DynamicRoutingFeatures, } #[derive( Debug, Clone, Copy, strum::Display, serde::Serialize, serde::Deserialize, PartialEq, Eq, )] pub enum DynamicRoutingType { SuccessRateBasedRouting, EliminationRouting, ContractBasedRouting, } impl SuccessBasedRoutingConfig { pub fn update(&mut self, new: Self) { if let Some(params) = new.params { self.params = Some(params) } if let Some(new_config) = new.config { self.config.as_mut().map(|config| config.update(new_config)); } } } impl SuccessBasedRoutingConfigBody { pub fn update(&mut self, new: Self) { if let Some(min_aggregates_size) = new.min_aggregates_size { self.min_aggregates_size = Some(min_aggregates_size) } if let Some(default_success_rate) = new.default_success_rate { self.default_success_rate = Some(default_success_rate) } if let Some(max_aggregates_size) = new.max_aggregates_size { self.max_aggregates_size = Some(max_aggregates_size) } if let Some(current_block_threshold) = new.current_block_threshold { self.current_block_threshold .as_mut() .map(|threshold| threshold.update(current_block_threshold)); } self.specificity_level = new.specificity_level } } impl CurrentBlockThreshold { pub fn update(&mut self, new: Self) { if let Some(max_total_count) = new.max_total_count { self.max_total_count = Some(max_total_count) } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub struct ContractBasedRoutingConfig { pub config: Option<ContractBasedRoutingConfigBody>, pub label_info: Option<Vec<LabelInformation>>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub struct ContractBasedRoutingConfigBody { pub constants: Option<Vec<f64>>, pub time_scale: Option<ContractBasedTimeScale>, } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub struct LabelInformation { pub label: String, pub target_count: u64, pub target_time: u64, #[schema(value_type = String)] pub mca_id: common_utils::id_type::MerchantConnectorAccountId, } impl LabelInformation { pub fn update_target_time(&mut self, new: &Self) { self.target_time = new.target_time; } pub fn update_target_count(&mut self, new: &Self) { self.target_count = new.target_count; } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ContractBasedTimeScale { Day, Month, } impl Default for ContractBasedRoutingConfig { fn default() -> Self { Self { config: Some(ContractBasedRoutingConfigBody { constants: Some(vec![0.7, 0.35]), time_scale: Some(ContractBasedTimeScale::Day), }), label_info: None, } } } impl ContractBasedRoutingConfig { pub fn update(&mut self, new: Self) { if let Some(new_config) = new.config { self.config.as_mut().map(|config| config.update(new_config)); } if let Some(new_label_info) = new.label_info { new_label_info.iter().for_each(|new_label_info| { if let Some(existing_label_infos) = &mut self.label_info { let mut updated = false; for existing_label_info in &mut *existing_label_infos { if existing_label_info.mca_id == new_label_info.mca_id { existing_label_info.update_target_time(new_label_info); existing_label_info.update_target_count(new_label_info); updated = true; } } if !updated { existing_label_infos.push(new_label_info.clone()); } } else { self.label_info = Some(vec![new_label_info.clone()]); } }); } } } impl ContractBasedRoutingConfigBody { pub fn update(&mut self, new: Self) { if let Some(new_cons) = new.constants { self.constants = Some(new_cons) } if let Some(new_time_scale) = new.time_scale { self.time_scale = Some(new_time_scale) } } } #[derive(serde::Serialize, serde::Deserialize, Debug, Clone)] pub struct RoutableConnectorChoiceWithBucketName { pub routable_connector_choice: RoutableConnectorChoice, pub bucket_name: String, } impl RoutableConnectorChoiceWithBucketName { pub fn new(routable_connector_choice: RoutableConnectorChoice, bucket_name: String) -> Self { Self { routable_connector_choice, bucket_name, } } }
7,679
1,958
hyperswitch
crates/api_models/src/pm_auth.rs
.rs
use common_enums::{PaymentMethod, PaymentMethodType}; use common_utils::{ events::{ApiEventMetric, ApiEventsType}, id_type, impl_api_event_type, }; #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct LinkTokenCreateRequest { pub language: Option<String>, // optional language field to be passed pub client_secret: Option<String>, // client secret to be passed in req body pub payment_id: id_type::PaymentId, // payment_id to be passed in req body for redis pm_auth connector name fetch pub payment_method: PaymentMethod, // payment_method to be used for filtering pm_auth connector pub payment_method_type: PaymentMethodType, // payment_method_type to be used for filtering pm_auth connector } #[derive(Debug, Clone, serde::Serialize)] pub struct LinkTokenCreateResponse { pub link_token: String, // link_token received in response pub connector: String, // pm_auth connector name in response } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct ExchangeTokenCreateRequest { pub public_token: String, pub client_secret: Option<String>, pub payment_id: id_type::PaymentId, pub payment_method: PaymentMethod, pub payment_method_type: PaymentMethodType, } #[derive(Debug, Clone, serde::Serialize)] pub struct ExchangeTokenCreateResponse { pub access_token: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodAuthConfig { pub enabled_payment_methods: Vec<PaymentMethodAuthConnectorChoice>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodAuthConnectorChoice { pub payment_method: PaymentMethod, pub payment_method_type: PaymentMethodType, pub connector_name: String, pub mca_id: id_type::MerchantConnectorAccountId, } impl_api_event_type!( Miscellaneous, ( LinkTokenCreateRequest, LinkTokenCreateResponse, ExchangeTokenCreateRequest, ExchangeTokenCreateResponse ) );
454
1,959
hyperswitch
crates/api_models/src/analytics.rs
.rs
use std::collections::HashSet; pub use common_utils::types::TimeRange; use common_utils::{events::ApiEventMetric, pii::EmailStrategy, types::authentication::AuthInfo}; use masking::Secret; use self::{ active_payments::ActivePaymentsMetrics, api_event::{ApiEventDimensions, ApiEventMetrics}, auth_events::{AuthEventDimensions, AuthEventFilters, AuthEventMetrics}, disputes::{DisputeDimensions, DisputeMetrics}, frm::{FrmDimensions, FrmMetrics}, payment_intents::{PaymentIntentDimensions, PaymentIntentMetrics}, payments::{PaymentDimensions, PaymentDistributions, PaymentMetrics}, refunds::{RefundDimensions, RefundDistributions, RefundMetrics}, sdk_events::{SdkEventDimensions, SdkEventMetrics}, }; pub mod active_payments; pub mod api_event; pub mod auth_events; pub mod connector_events; pub mod disputes; pub mod frm; pub mod outgoing_webhook_event; pub mod payment_intents; pub mod payments; pub mod refunds; pub mod sdk_events; pub mod search; #[derive(Debug, serde::Serialize)] pub struct NameDescription { pub name: String, pub desc: String, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetInfoResponse { pub metrics: Vec<NameDescription>, pub download_dimensions: Option<Vec<NameDescription>>, pub dimensions: Vec<NameDescription>, } #[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)] pub struct TimeSeries { pub granularity: Granularity, } #[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)] pub enum Granularity { #[serde(rename = "G_ONEMIN")] OneMin, #[serde(rename = "G_FIVEMIN")] FiveMin, #[serde(rename = "G_FIFTEENMIN")] FifteenMin, #[serde(rename = "G_THIRTYMIN")] ThirtyMin, #[serde(rename = "G_ONEHOUR")] OneHour, #[serde(rename = "G_ONEDAY")] OneDay, } pub trait ForexMetric { fn is_forex_metric(&self) -> bool; } #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct AnalyticsRequest { pub payment_intent: Option<GetPaymentIntentMetricRequest>, pub payment_attempt: Option<GetPaymentMetricRequest>, pub refund: Option<GetRefundMetricRequest>, pub dispute: Option<GetDisputeMetricRequest>, } impl AnalyticsRequest { pub fn requires_forex_functionality(&self) -> bool { self.payment_attempt .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() || self .payment_intent .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() || self .refund .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() || self .dispute .as_ref() .map(|req| req.metrics.iter().any(|metric| metric.is_forex_metric())) .unwrap_or_default() } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<PaymentDimensions>, #[serde(default)] pub filters: payments::PaymentFilters, pub metrics: HashSet<PaymentMetrics>, pub distribution: Option<PaymentDistributionBody>, #[serde(default)] pub delta: bool, } #[derive(Clone, Copy, Debug, serde::Deserialize, serde::Serialize)] pub enum QueryLimit { #[serde(rename = "TOP_5")] Top5, #[serde(rename = "TOP_10")] Top10, } #[allow(clippy::from_over_into)] impl Into<u64> for QueryLimit { fn into(self) -> u64 { match self { Self::Top5 => 5, Self::Top10 => 10, } } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentDistributionBody { pub distribution_for: PaymentDistributions, pub distribution_cardinality: QueryLimit, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct RefundDistributionBody { pub distribution_for: RefundDistributions, pub distribution_cardinality: QueryLimit, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct ReportRequest { pub time_range: TimeRange, pub emails: Option<Vec<Secret<String, EmailStrategy>>>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GenerateReportRequest { pub request: ReportRequest, pub merchant_id: Option<common_utils::id_type::MerchantId>, pub auth: AuthInfo, pub email: Secret<String, EmailStrategy>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentIntentMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<PaymentIntentDimensions>, #[serde(default)] pub filters: payment_intents::PaymentIntentFilters, pub metrics: HashSet<PaymentIntentMetrics>, #[serde(default)] pub delta: bool, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetRefundMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<RefundDimensions>, #[serde(default)] pub filters: refunds::RefundFilters, pub metrics: HashSet<RefundMetrics>, pub distribution: Option<RefundDistributionBody>, #[serde(default)] pub delta: bool, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetFrmMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<FrmDimensions>, #[serde(default)] pub filters: frm::FrmFilters, pub metrics: HashSet<FrmMetrics>, #[serde(default)] pub delta: bool, } impl ApiEventMetric for GetFrmMetricRequest {} #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetSdkEventMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<SdkEventDimensions>, #[serde(default)] pub filters: sdk_events::SdkEventFilters, pub metrics: HashSet<SdkEventMetrics>, #[serde(default)] pub delta: bool, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetAuthEventMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<AuthEventDimensions>, #[serde(default)] pub filters: AuthEventFilters, #[serde(default)] pub metrics: HashSet<AuthEventMetrics>, #[serde(default)] pub delta: bool, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetActivePaymentsMetricRequest { #[serde(default)] pub metrics: HashSet<ActivePaymentsMetrics>, pub time_range: TimeRange, } #[derive(Debug, serde::Serialize)] pub struct AnalyticsMetadata { pub current_time_range: TimeRange, } #[derive(Debug, serde::Serialize)] pub struct PaymentsAnalyticsMetadata { pub total_payment_processed_amount: Option<u64>, pub total_payment_processed_amount_in_usd: Option<u64>, pub total_payment_processed_amount_without_smart_retries: Option<u64>, pub total_payment_processed_amount_without_smart_retries_usd: Option<u64>, pub total_payment_processed_count: Option<u64>, pub total_payment_processed_count_without_smart_retries: Option<u64>, pub total_failure_reasons_count: Option<u64>, pub total_failure_reasons_count_without_smart_retries: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct PaymentIntentsAnalyticsMetadata { pub total_success_rate: Option<f64>, pub total_success_rate_without_smart_retries: Option<f64>, pub total_smart_retried_amount: Option<u64>, pub total_smart_retried_amount_without_smart_retries: Option<u64>, pub total_payment_processed_amount: Option<u64>, pub total_payment_processed_amount_without_smart_retries: Option<u64>, pub total_smart_retried_amount_in_usd: Option<u64>, pub total_smart_retried_amount_without_smart_retries_in_usd: Option<u64>, pub total_payment_processed_amount_in_usd: Option<u64>, pub total_payment_processed_amount_without_smart_retries_in_usd: Option<u64>, pub total_payment_processed_count: Option<u64>, pub total_payment_processed_count_without_smart_retries: Option<u64>, } #[derive(Debug, serde::Serialize)] pub struct RefundsAnalyticsMetadata { pub total_refund_success_rate: Option<f64>, pub total_refund_processed_amount: Option<u64>, pub total_refund_processed_amount_in_usd: Option<u64>, pub total_refund_processed_count: Option<u64>, pub total_refund_reason_count: Option<u64>, pub total_refund_error_message_count: Option<u64>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentFiltersRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<PaymentDimensions>, } #[derive(Debug, Default, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentFiltersResponse { pub query_data: Vec<FilterValue>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct FilterValue { pub dimension: PaymentDimensions, pub values: Vec<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetPaymentIntentFiltersRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<PaymentIntentDimensions>, } #[derive(Debug, Default, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentIntentFiltersResponse { pub query_data: Vec<PaymentIntentFilterValue>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentIntentFilterValue { pub dimension: PaymentIntentDimensions, pub values: Vec<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetRefundFilterRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<RefundDimensions>, } #[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct RefundFiltersResponse { pub query_data: Vec<RefundFilterValue>, } #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct RefundFilterValue { pub dimension: RefundDimensions, pub values: Vec<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetFrmFilterRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<FrmDimensions>, } impl ApiEventMetric for GetFrmFilterRequest {} #[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct FrmFiltersResponse { pub query_data: Vec<FrmFilterValue>, } impl ApiEventMetric for FrmFiltersResponse {} #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct FrmFilterValue { pub dimension: FrmDimensions, pub values: Vec<String>, } impl ApiEventMetric for FrmFilterValue {} #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetSdkEventFiltersRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<SdkEventDimensions>, } #[derive(Debug, Default, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct SdkEventFiltersResponse { pub query_data: Vec<SdkEventFilterValue>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct SdkEventFilterValue { pub dimension: SdkEventDimensions, pub values: Vec<String>, } #[derive(Debug, serde::Serialize)] pub struct DisputesAnalyticsMetadata { pub total_disputed_amount: Option<u64>, pub total_dispute_lost_amount: Option<u64>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct MetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [AnalyticsMetadata; 1], } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentsMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [PaymentsAnalyticsMetadata; 1], } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct PaymentIntentsMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [PaymentIntentsAnalyticsMetadata; 1], } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct RefundsMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [RefundsAnalyticsMetadata; 1], } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct DisputesMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [DisputesAnalyticsMetadata; 1], } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetApiEventFiltersRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<ApiEventDimensions>, } #[derive(Debug, Default, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct ApiEventFiltersResponse { pub query_data: Vec<ApiEventFilterValue>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct ApiEventFilterValue { pub dimension: ApiEventDimensions, pub values: Vec<String>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetApiEventMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<ApiEventDimensions>, #[serde(default)] pub filters: api_event::ApiEventFilters, pub metrics: HashSet<ApiEventMetrics>, #[serde(default)] pub delta: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetDisputeFilterRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<DisputeDimensions>, } #[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct DisputeFiltersResponse { pub query_data: Vec<DisputeFilterValue>, } #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct DisputeFilterValue { pub dimension: DisputeDimensions, pub values: Vec<String>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetDisputeMetricRequest { pub time_series: Option<TimeSeries>, pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<DisputeDimensions>, #[serde(default)] pub filters: disputes::DisputeFilters, pub metrics: HashSet<DisputeMetrics>, #[serde(default)] pub delta: bool, } #[derive(Clone, Debug, Default, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct SankeyResponse { pub count: i64, pub status: String, pub refunds_status: Option<String>, pub dispute_status: Option<String>, pub first_attempt: i64, } #[derive(Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct GetAuthEventFilterRequest { pub time_range: TimeRange, #[serde(default)] pub group_by_names: Vec<AuthEventDimensions>, } #[derive(Debug, Default, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AuthEventFiltersResponse { pub query_data: Vec<AuthEventFilterValue>, } #[derive(Debug, serde::Serialize, Eq, PartialEq)] #[serde(rename_all = "camelCase")] pub struct AuthEventFilterValue { pub dimension: AuthEventDimensions, pub values: Vec<String>, } #[derive(Debug, serde::Serialize)] #[serde(rename_all = "camelCase")] pub struct AuthEventMetricsResponse<T> { pub query_data: Vec<T>, pub meta_data: [AuthEventsAnalyticsMetadata; 1], } #[derive(Debug, serde::Serialize)] pub struct AuthEventsAnalyticsMetadata { pub total_error_message_count: Option<u64>, }
3,968
1,960
hyperswitch
crates/api_models/src/surcharge_decision_configs.rs
.rs
use common_utils::{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH, events, types::{MinorUnit, Percentage}, }; use euclid::frontend::{ ast::Program, dir::{DirKeyKind, EuclidDirFilter}, }; use serde::{Deserialize, Serialize}; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case")] pub struct SurchargeDetailsOutput { pub surcharge: SurchargeOutput, pub tax_on_surcharge: Option<Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>>, } #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] #[serde(rename_all = "snake_case", tag = "type", content = "value")] pub enum SurchargeOutput { Fixed { amount: MinorUnit }, Rate(Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>), } #[derive(Debug, Default, Clone, Serialize, Deserialize)] pub struct SurchargeDecisionConfigs { pub surcharge_details: Option<SurchargeDetailsOutput>, } impl EuclidDirFilter for SurchargeDecisionConfigs { const ALLOWED: &'static [DirKeyKind] = &[ DirKeyKind::PaymentMethod, DirKeyKind::MetaData, DirKeyKind::PaymentAmount, DirKeyKind::PaymentCurrency, DirKeyKind::BillingCountry, DirKeyKind::CardNetwork, DirKeyKind::PayLaterType, DirKeyKind::WalletType, DirKeyKind::BankTransferType, DirKeyKind::BankRedirectType, DirKeyKind::BankDebitType, DirKeyKind::CryptoType, DirKeyKind::RealTimePaymentType, ]; } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct SurchargeDecisionManagerRecord { pub name: String, pub merchant_surcharge_configs: MerchantSurchargeConfigs, pub algorithm: Program<SurchargeDecisionConfigs>, pub created_at: i64, pub modified_at: i64, } impl events::ApiEventMetric for SurchargeDecisionManagerRecord { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct SurchargeDecisionConfigReq { pub name: Option<String>, pub merchant_surcharge_configs: MerchantSurchargeConfigs, pub algorithm: Option<Program<SurchargeDecisionConfigs>>, } impl events::ApiEventMetric for SurchargeDecisionConfigReq { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct MerchantSurchargeConfigs { pub show_surcharge_breakup_screen: Option<bool>, } pub type SurchargeDecisionManagerResponse = SurchargeDecisionManagerRecord;
622
1,961
hyperswitch
crates/api_models/src/process_tracker.rs
.rs
#[cfg(feature = "v2")] pub mod revenue_recovery;
13
1,962
hyperswitch
crates/api_models/src/ephemeral_key.rs
.rs
use common_utils::id_type; #[cfg(feature = "v2")] use masking::Secret; use serde; use utoipa::ToSchema; #[cfg(feature = "v1")] /// Information required to create an ephemeral key. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct EphemeralKeyCreateRequest { /// Customer ID for which an ephemeral key must be created #[schema( min_length = 1, max_length = 64, value_type = String, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44" )] pub customer_id: id_type::CustomerId, } #[cfg(feature = "v2")] #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, Eq, ToSchema)] #[serde(rename_all = "snake_case")] pub enum ResourceId { #[schema(value_type = String)] Customer(id_type::GlobalCustomerId), } #[cfg(feature = "v2")] /// Information required to create a client secret. #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ClientSecretCreateRequest { /// Resource ID for which a client secret must be created pub resource_id: ResourceId, } #[cfg(feature = "v2")] /// client_secret for the resource_id mentioned #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, ToSchema)] pub struct ClientSecretResponse { /// Client Secret id #[schema(value_type = String, max_length = 32, min_length = 1)] pub id: id_type::ClientSecretId, /// resource_id to which this client secret belongs to #[schema(value_type = ResourceId)] pub resource_id: ResourceId, /// time at which this client secret was created pub created_at: time::PrimitiveDateTime, /// time at which this client secret would expire pub expires: time::PrimitiveDateTime, #[schema(value_type=String)] /// client secret pub secret: Secret<String>, } #[cfg(feature = "v1")] impl common_utils::events::ApiEventMetric for EphemeralKeyCreateRequest { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } #[cfg(feature = "v1")] impl common_utils::events::ApiEventMetric for EphemeralKeyCreateResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for ClientSecretCreateRequest { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } #[cfg(feature = "v2")] impl common_utils::events::ApiEventMetric for ClientSecretResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Miscellaneous) } } #[cfg(feature = "v1")] /// ephemeral_key for the customer_id mentioned #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, Eq, PartialEq, ToSchema)] pub struct EphemeralKeyCreateResponse { /// customer_id to which this ephemeral key belongs to #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// time at which this ephemeral key was created pub created_at: i64, /// time at which this ephemeral key would expire pub expires: i64, /// ephemeral key pub secret: String, }
869
1,963
hyperswitch
crates/api_models/src/customers.rs
.rs
use common_utils::{crypto, custom_serde, id_type, pii, types::Description}; use masking::Secret; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; use crate::payments; /// The customer details #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerRequest { /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")] #[serde(skip)] pub merchant_id: id_type::MerchantId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(value_type = Option<String>, max_length = 255, example = "JonTest@test.com")] pub email: Option<pii::Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The address for the customer #[schema(value_type = Option<AddressDetails>)] pub address: Option<payments::AddressDetails>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 /// characters long. Metadata is useful for storing additional, structured information on an /// object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerListRequest { /// Offset #[schema(example = 32)] pub offset: Option<u32>, /// Limit #[schema(example = 32)] pub limit: Option<u16>, } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl CustomerRequest { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { Some( self.customer_id .to_owned() .unwrap_or_else(common_utils::generate_customer_id_of_default_length), ) } pub fn get_address(&self) -> Option<payments::AddressDetails> { self.address.clone() } pub fn get_optional_email(&self) -> Option<pii::Email> { self.email.clone() } } /// The customer details #[cfg(all(feature = "v2", feature = "customer_v2"))] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerRequest { /// The merchant identifier for the customer object. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_reference_id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = String, example = "Jon Test")] pub name: Secret<String>, /// The customer's email address #[schema(value_type = String, max_length = 255, example = "JonTest@test.com")] pub email: pii::Email, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The default billing address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_billing_address: Option<payments::AddressDetails>, /// The default shipping address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_shipping_address: Option<payments::AddressDetails>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 /// characters long. Metadata is useful for storing additional, structured information on an /// object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, } #[cfg(all(feature = "v2", feature = "customer_v2"))] impl CustomerRequest { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { self.merchant_reference_id.clone() } pub fn get_default_customer_billing_address(&self) -> Option<payments::AddressDetails> { self.default_billing_address.clone() } pub fn get_default_customer_shipping_address(&self) -> Option<payments::AddressDetails> { self.default_shipping_address.clone() } pub fn get_optional_email(&self) -> Option<pii::Email> { Some(self.email.clone()) } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[derive(Debug, Clone, Serialize, ToSchema)] pub struct CustomerResponse { /// The identifier for the customer object #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: crypto::OptionalEncryptableName, /// The customer's email address #[schema(value_type = Option<String>,max_length = 255, example = "JonTest@test.com")] pub email: crypto::OptionalEncryptableEmail, /// The customer's phone number #[schema(value_type = Option<String>,max_length = 255, example = "9123456789")] pub phone: crypto::OptionalEncryptablePhone, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The address for the customer #[schema(value_type = Option<AddressDetails>)] pub address: Option<payments::AddressDetails>, /// A timestamp (ISO 8601 code) that determines when the customer was created #[schema(value_type = PrimitiveDateTime,example = "2023-01-18T11:04:09.922Z")] #[serde(with = "custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 /// characters long. Metadata is useful for storing additional, structured information on an /// object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The identifier for the default payment method. #[schema(max_length = 64, example = "pm_djh2837dwduh890123")] pub default_payment_method_id: Option<String>, } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl CustomerResponse { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { Some(self.customer_id.clone()) } } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[derive(Debug, Clone, Serialize, ToSchema)] pub struct CustomerResponse { /// Unique identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub id: id_type::GlobalCustomerId, /// The identifier for the customer object #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_reference_id: Option<id_type::CustomerId>, /// Connector specific customer reference ids #[schema(value_type = Option<Object>, example = json!({"mca_hwySG2NtpzX0qr7toOy8": "cus_Rnm2pDKGyQi506"}))] pub connector_customer_ids: Option<common_types::customers::ConnectorCustomerMap>, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: crypto::OptionalEncryptableName, /// The customer's email address #[schema(value_type = Option<String> ,max_length = 255, example = "JonTest@test.com")] pub email: crypto::OptionalEncryptableEmail, /// The customer's phone number #[schema(value_type = Option<String>,max_length = 255, example = "9123456789")] pub phone: crypto::OptionalEncryptablePhone, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The default billing address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_billing_address: Option<payments::AddressDetails>, /// The default shipping address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_shipping_address: Option<payments::AddressDetails>, /// A timestamp (ISO 8601 code) that determines when the customer was created #[schema(value_type = PrimitiveDateTime,example = "2023-01-18T11:04:09.922Z")] #[serde(with = "custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 /// characters long. Metadata is useful for storing additional, structured information on an /// object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The identifier for the default payment method. #[schema(value_type = Option<String>, max_length = 64, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(all(feature = "v2", feature = "customer_v2"))] impl CustomerResponse { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { self.merchant_reference_id.clone() } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[derive(Debug, Deserialize, Serialize, ToSchema)] pub struct CustomerDeleteResponse { /// The identifier for the customer object #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// Whether customer was deleted or not #[schema(example = false)] pub customer_deleted: bool, /// Whether address was deleted or not #[schema(example = false)] pub address_deleted: bool, /// Whether payment methods deleted or not #[schema(example = false)] pub payment_methods_deleted: bool, } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[derive(Debug, Deserialize, Serialize, ToSchema)] pub struct CustomerDeleteResponse { /// Unique identifier for the customer #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub id: id_type::GlobalCustomerId, /// The identifier for the customer object #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_reference_id: Option<id_type::CustomerId>, /// Whether customer was deleted or not #[schema(example = false)] pub customer_deleted: bool, /// Whether address was deleted or not #[schema(example = false)] pub address_deleted: bool, /// Whether payment methods deleted or not #[schema(example = false)] pub payment_methods_deleted: bool, } /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] pub struct CustomerUpdateRequest { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44")] #[serde(skip)] pub merchant_id: id_type::MerchantId, /// The customer's name #[schema(max_length = 255, value_type = Option<String>, example = "Jon Test")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(value_type = Option<String>, max_length = 255, example = "JonTest@test.com")] pub email: Option<pii::Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The address for the customer #[schema(value_type = Option<AddressDetails>)] pub address: Option<payments::AddressDetails>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 /// characters long. Metadata is useful for storing additional, structured information on an /// object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl CustomerUpdateRequest { pub fn get_address(&self) -> Option<payments::AddressDetails> { self.address.clone() } } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[derive(Debug, Default, Clone, Deserialize, Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct CustomerUpdateRequest { /// The merchant identifier for the customer object. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_reference_id: Option<id_type::CustomerId>, /// The customer's name #[schema(max_length = 255, value_type = String, example = "Jon Test")] pub name: Option<Secret<String>>, /// The customer's email address #[schema(value_type = String, max_length = 255, example = "JonTest@test.com")] pub email: Option<pii::Email>, /// The customer's phone number #[schema(value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// An arbitrary string that you can attach to a customer object. #[schema(max_length = 255, example = "First Customer", value_type = Option<String>)] pub description: Option<Description>, /// The country code for the customer phone number #[schema(max_length = 255, example = "+65")] pub phone_country_code: Option<String>, /// The default billing address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_billing_address: Option<payments::AddressDetails>, /// The default shipping address for the customer #[schema(value_type = Option<AddressDetails>)] pub default_shipping_address: Option<payments::AddressDetails>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 /// characters long. Metadata is useful for storing additional, structured information on an /// object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The unique identifier of the payment method #[schema(value_type = Option<String>, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub default_payment_method_id: Option<id_type::GlobalPaymentMethodId>, } #[cfg(all(feature = "v2", feature = "customer_v2"))] impl CustomerUpdateRequest { pub fn get_merchant_reference_id(&self) -> Option<id_type::CustomerId> { self.merchant_reference_id.clone() } pub fn get_default_customer_billing_address(&self) -> Option<payments::AddressDetails> { self.default_billing_address.clone() } pub fn get_default_customer_shipping_address(&self) -> Option<payments::AddressDetails> { self.default_shipping_address.clone() } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] #[derive(Debug, Serialize)] pub struct CustomerUpdateRequestInternal { pub customer_id: id_type::CustomerId, pub request: CustomerUpdateRequest, } #[cfg(all(feature = "v2", feature = "customer_v2"))] #[derive(Debug, Serialize)] pub struct CustomerUpdateRequestInternal { pub id: id_type::GlobalCustomerId, pub request: CustomerUpdateRequest, }
4,640
1,964
hyperswitch
crates/api_models/src/consts.rs
.rs
/// Max payment intent fulfillment expiry pub const MAX_ORDER_FULFILLMENT_EXPIRY: i64 = 1800; /// Min payment intent fulfillment expiry pub const MIN_ORDER_FULFILLMENT_EXPIRY: i64 = 60;
56
1,965
hyperswitch
crates/api_models/src/refunds.rs
.rs
use std::collections::HashMap; pub use common_utils::types::MinorUnit; use common_utils::{pii, types::TimeRange}; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use super::payments::AmountFilter; use crate::{ admin::{self, MerchantConnectorInfo}, enums, }; #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundRequest { /// The payment id against which refund is to be initiated #[schema( max_length = 30, min_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: common_utils::id_type::PaymentId, /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. If this is not passed by the merchant, this field shall be auto generated and provided in the API response. It is recommended to generate uuid(v4) as the refund_id. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4" )] pub refund_id: Option<String>, /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = Option<String>)] pub merchant_id: Option<common_utils::id_type::MerchantId>, /// Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the full payment amount #[schema(value_type = Option<i64> , minimum = 100, example = 6540)] pub amount: Option<MinorUnit>, /// Reason for the refund. Often useful for displaying to users and your customer support executive. In case the payment went through Stripe, this field needs to be passed with one of these enums: `duplicate`, `fraudulent`, or `requested_by_customer` #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// To indicate whether to refund needs to be instant or scheduled. Default value is instant #[schema(default = "Instant", example = "Instant")] pub refund_type: Option<RefundType>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Merchant connector details used to make payments. #[schema(value_type = Option<MerchantConnectorDetailsWrap>)] pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, /// Charge specific fields for controlling the revert of funds from either platform or connected account #[schema(value_type = Option<SplitRefund>)] pub split_refunds: Option<common_types::refunds::SplitRefund>, } #[cfg(feature = "v2")] #[derive(Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundsCreateRequest { /// The payment id against which refund is initiated #[schema( max_length = 30, min_length = 30, example = "pay_mbabizu24mvu3mela5njyhpit4", value_type = String, )] pub payment_id: common_utils::id_type::GlobalPaymentId, /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4", value_type = Option<String>, )] pub merchant_reference_id: Option<common_utils::id_type::RefundReferenceId>, /// Total amount for which the refund is to be initiated. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., If not provided, this will default to the amount_captured of the payment #[schema(value_type = Option<i64> , minimum = 100, example = 6540)] pub amount: Option<MinorUnit>, /// Reason for the refund. Often useful for displaying to users and your customer support executive. #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// To indicate whether to refund needs to be instant or scheduled. Default value is instant #[schema(default = "Instant", example = "Instant")] pub refund_type: Option<RefundType>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Default, Debug, Clone, Deserialize)] pub struct RefundsRetrieveBody { pub force_sync: Option<bool>, } #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] pub struct RefundsRetrieveRequest { /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refund initiated against the same payment. If the identifiers is not defined by the merchant, this filed shall be auto generated and provide in the API response. It is recommended to generate uuid(v4) as the refund_id. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4" )] pub refund_id: String, /// `force_sync` with the connector to get refund details /// (defaults to false) pub force_sync: Option<bool>, /// Merchant connector details used to make payments. pub merchant_connector_details: Option<admin::MerchantConnectorDetailsWrap>, } #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundUpdateRequest { #[serde(skip)] pub refund_id: String, /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive #[schema(max_length = 255, example = "Customer returned the product")] pub reason: Option<String>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[derive(Default, Debug, ToSchema, Clone, Deserialize, Serialize)] #[serde(deny_unknown_fields)] pub struct RefundManualUpdateRequest { #[serde(skip)] pub refund_id: String, /// Merchant ID #[schema(value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The status for refund pub status: Option<RefundStatus>, /// The code for the error pub error_code: Option<String>, /// The error message pub error_message: Option<String>, } /// To indicate whether to refund needs to be instant or scheduled #[derive( Default, Debug, Clone, Copy, ToSchema, Deserialize, Serialize, Eq, PartialEq, strum::Display, )] #[serde(rename_all = "snake_case")] pub enum RefundType { #[default] Scheduled, Instant, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundResponse { /// Unique Identifier for the refund pub refund_id: String, /// The payment id against which refund is initiated #[schema(value_type = String)] pub payment_id: common_utils::id_type::PaymentId, /// The refund amount, which should be less than or equal to the total payment amount. Amount for the payment in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc #[schema(value_type = i64 , minimum = 100, example = 6540)] pub amount: MinorUnit, /// The three-letter ISO currency code pub currency: String, /// The status for refund pub status: RefundStatus, /// An arbitrary string attached to the object. Often useful for displaying to users and your customer support executive pub reason: Option<String>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, /// The error message pub error_message: Option<String>, /// The code for the error pub error_code: Option<String>, /// Error code unified across the connectors is received here if there was an error while calling connector pub unified_code: Option<String>, /// Error message unified across the connectors is received here if there was an error while calling connector pub unified_message: Option<String>, /// The timestamp at which refund is created #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created_at: Option<PrimitiveDateTime>, /// The timestamp at which refund is updated #[serde(with = "common_utils::custom_serde::iso8601::option")] pub updated_at: Option<PrimitiveDateTime>, /// The connector used for the refund and the corresponding payment #[schema(example = "stripe")] pub connector: String, /// The id of business profile for this refund #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// The merchant_connector_id of the processor through which this payment went through #[schema(value_type = Option<String>)] pub merchant_connector_id: Option<common_utils::id_type::MerchantConnectorAccountId>, /// Charge specific fields for controlling the revert of funds from either platform or connected account #[schema(value_type = Option<SplitRefund>,)] pub split_refunds: Option<common_types::refunds::SplitRefund>, /// Error code received from the issuer in case of failed refunds pub issuer_error_code: Option<String>, /// Error message received from the issuer in case of failed refunds pub issuer_error_message: Option<String>, } #[cfg(feature = "v1")] impl RefundResponse { pub fn get_refund_id_as_string(&self) -> String { self.refund_id.clone() } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundResponse { /// Global Refund Id for the refund #[schema(value_type = String)] pub id: common_utils::id_type::GlobalRefundId, /// The payment id against which refund is initiated #[schema(value_type = String)] pub payment_id: common_utils::id_type::GlobalPaymentId, /// Unique Identifier for the Refund. This is to ensure idempotency for multiple partial refunds initiated against the same payment. #[schema( max_length = 30, min_length = 30, example = "ref_mbabizu24mvu3mela5njyhpit4", value_type = Option<String>, )] pub merchant_reference_id: Option<common_utils::id_type::RefundReferenceId>, /// The refund amount #[schema(value_type = i64 , minimum = 100, example = 6540)] pub amount: MinorUnit, /// The three-letter ISO currency code #[schema(value_type = Currency)] pub currency: common_enums::Currency, /// The status for refund pub status: RefundStatus, /// An arbitrary string attached to the object pub reason: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object #[schema(value_type = Option<Object>)] pub metadata: Option<pii::SecretSerdeValue>, /// The error details for the refund pub error_details: Option<RefundErrorDetails>, /// The timestamp at which refund is created #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: PrimitiveDateTime, /// The timestamp at which refund is updated #[serde(with = "common_utils::custom_serde::iso8601")] pub updated_at: PrimitiveDateTime, /// The connector used for the refund and the corresponding payment #[schema(example = "stripe", value_type = Connector)] pub connector: enums::Connector, /// The id of business profile for this refund #[schema(value_type = String)] pub profile_id: common_utils::id_type::ProfileId, /// The merchant_connector_id of the processor through which this payment went through #[schema(value_type = String)] pub merchant_connector_id: common_utils::id_type::MerchantConnectorAccountId, /// The reference id of the connector for the refund pub connector_refund_reference_id: Option<String>, } #[cfg(feature = "v2")] impl RefundResponse { pub fn get_refund_id_as_string(&self) -> String { self.id.get_string_repr().to_owned() } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundErrorDetails { pub code: String, pub message: String, } #[derive(Debug, Clone, Eq, PartialEq, Deserialize, Serialize, ToSchema)] pub struct RefundListRequest { /// The identifier for the payment #[schema(value_type = Option<String>)] pub payment_id: Option<common_utils::id_type::PaymentId>, /// The identifier for the refund pub refund_id: Option<String>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// Limit on the number of objects to return pub limit: Option<i64>, /// The starting point within a list of objects pub offset: Option<i64>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc) #[serde(flatten)] pub time_range: Option<TimeRange>, /// The amount to filter reufnds list. Amount takes two option fields start_amount and end_amount from which objects can be filtered as per required scenarios (less_than, greater_than, equal_to and range) pub amount_filter: Option<AmountFilter>, /// The list of connectors to filter refunds list pub connector: Option<Vec<String>>, /// The list of merchant connector ids to filter the refunds list for selected label #[schema(value_type = Option<Vec<String>>)] pub merchant_connector_id: Option<Vec<common_utils::id_type::MerchantConnectorAccountId>>, /// The list of currencies to filter refunds list #[schema(value_type = Option<Vec<Currency>>)] pub currency: Option<Vec<enums::Currency>>, /// The list of refund statuses to filter refunds list #[schema(value_type = Option<Vec<RefundStatus>>)] pub refund_status: Option<Vec<enums::RefundStatus>>, } #[derive(Debug, Clone, Eq, PartialEq, Serialize, ToSchema)] pub struct RefundListResponse { /// The number of refunds included in the list pub count: usize, /// The total number of refunds in the list pub total_count: i64, /// The List of refund response object pub data: Vec<RefundResponse>, } #[derive(Clone, Debug, Serialize, Deserialize, Eq, PartialEq, ToSchema)] pub struct RefundListMetaData { /// The list of available connector filters pub connector: Vec<String>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<enums::Currency>, /// The list of available refund status filters #[schema(value_type = Vec<RefundStatus>)] pub refund_status: Vec<enums::RefundStatus>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct RefundListFilters { /// The map of available connector filters, where the key is the connector name and the value is a list of MerchantConnectorInfo instances pub connector: HashMap<String, Vec<MerchantConnectorInfo>>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<enums::Currency>, /// The list of available refund status filters #[schema(value_type = Vec<RefundStatus>)] pub refund_status: Vec<enums::RefundStatus>, } #[derive(Clone, Debug, serde::Serialize)] pub struct RefundAggregateResponse { /// The list of refund status with their count pub status_with_count: HashMap<enums::RefundStatus, i64>, } /// The status for refunds #[derive( Debug, Eq, Clone, Copy, PartialEq, Default, Deserialize, Serialize, ToSchema, strum::Display, strum::EnumIter, )] #[serde(rename_all = "snake_case")] pub enum RefundStatus { Succeeded, Failed, #[default] Pending, Review, } impl From<enums::RefundStatus> for RefundStatus { fn from(status: enums::RefundStatus) -> Self { match status { enums::RefundStatus::Failure | enums::RefundStatus::TransactionFailure => Self::Failed, enums::RefundStatus::ManualReview => Self::Review, enums::RefundStatus::Pending => Self::Pending, enums::RefundStatus::Success => Self::Succeeded, } } } impl From<RefundStatus> for enums::RefundStatus { fn from(status: RefundStatus) -> Self { match status { RefundStatus::Failed => Self::Failure, RefundStatus::Review => Self::ManualReview, RefundStatus::Pending => Self::Pending, RefundStatus::Succeeded => Self::Success, } } }
4,171
1,966
hyperswitch
crates/api_models/src/gsm.rs
.rs
use common_enums::ErrorCategory; use utoipa::ToSchema; use crate::enums::Connector; #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmCreateRequest { /// The connector through which payment has gone through pub connector: Connector, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, /// message received from the connector pub message: String, /// status provided by the router pub status: String, /// optional error provided by the router pub router_error: Option<String>, /// decision to be taken for auto retries flow pub decision: GsmDecision, /// indicates if step_up retry is possible pub step_up_possible: bool, /// error code unified across the connectors pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, /// category in which error belongs to pub error_category: Option<ErrorCategory>, /// indicates if retry with pan is possible pub clear_pan_possible: bool, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmRetrieveRequest { /// The connector through which payment has gone through pub connector: Connector, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, /// message received from the connector pub message: String, } #[derive( Default, Clone, Copy, Debug, strum::Display, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::EnumString, ToSchema, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum GsmDecision { Retry, Requeue, #[default] DoDefault, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmUpdateRequest { /// The connector through which payment has gone through pub connector: String, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, /// message received from the connector pub message: String, /// status provided by the router pub status: Option<String>, /// optional error provided by the router pub router_error: Option<String>, /// decision to be taken for auto retries flow pub decision: Option<GsmDecision>, /// indicates if step_up retry is possible pub step_up_possible: Option<bool>, /// error code unified across the connectors pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, /// category in which error belongs to pub error_category: Option<ErrorCategory>, /// indicates if retry with pan is possible pub clear_pan_possible: Option<bool>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GsmDeleteRequest { /// The connector through which payment has gone through pub connector: String, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, /// message received from the connector pub message: String, } #[derive(Debug, serde::Serialize, ToSchema)] pub struct GsmDeleteResponse { pub gsm_rule_delete: bool, /// The connector through which payment has gone through pub connector: String, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, } #[derive(serde::Serialize, Debug, ToSchema)] pub struct GsmResponse { /// The connector through which payment has gone through pub connector: String, /// The flow in which the code and message occurred for a connector pub flow: String, /// The sub_flow in which the code and message occurred for a connector pub sub_flow: String, /// code received from the connector pub code: String, /// message received from the connector pub message: String, /// status provided by the router pub status: String, /// optional error provided by the router pub router_error: Option<String>, /// decision to be taken for auto retries flow pub decision: String, /// indicates if step_up retry is possible pub step_up_possible: bool, /// error code unified across the connectors pub unified_code: Option<String>, /// error message unified across the connectors pub unified_message: Option<String>, /// category in which error belongs to pub error_category: Option<ErrorCategory>, /// indicates if retry with pan is possible pub clear_pan_possible: bool, }
1,198
1,967
hyperswitch
crates/api_models/src/conditional_configs.rs
.rs
use common_utils::events; use euclid::frontend::ast::Program; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DecisionManagerRecord { pub name: String, pub program: Program<common_types::payments::ConditionalConfigs>, pub created_at: i64, pub modified_at: i64, } impl events::ApiEventMetric for DecisionManagerRecord { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(deny_unknown_fields)] pub struct ConditionalConfigReq { pub name: Option<String>, pub algorithm: Option<Program<common_types::payments::ConditionalConfigs>>, } #[cfg(feature = "v1")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DecisionManagerRequest { pub name: Option<String>, pub program: Option<Program<common_types::payments::ConditionalConfigs>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(untagged)] pub enum DecisionManager { DecisionManagerv0(ConditionalConfigReq), DecisionManagerv1(DecisionManagerRequest), } impl events::ApiEventMetric for DecisionManager { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } } pub type DecisionManagerResponse = DecisionManagerRecord; #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct DecisionManagerRequest { pub name: String, pub program: Program<common_types::payments::ConditionalConfigs>, } #[cfg(feature = "v2")] impl events::ApiEventMetric for DecisionManagerRequest { fn get_api_event_type(&self) -> Option<events::ApiEventsType> { Some(events::ApiEventsType::Routing) } }
421
1,968
hyperswitch
crates/api_models/src/admin.rs
.rs
use std::collections::{HashMap, HashSet}; use common_types::primitive_wrappers; use common_utils::{ consts, crypto::Encryptable, errors::{self, CustomResult}, ext_traits::Encode, id_type, link_utils, pii, }; #[cfg(feature = "v1")] use common_utils::{crypto::OptionalEncryptableName, ext_traits::ValueExt}; #[cfg(feature = "v2")] use masking::ExposeInterface; use masking::{PeekInterface, Secret}; use serde::{Deserialize, Serialize}; use url; use utoipa::ToSchema; use super::payments::AddressDetails; #[cfg(feature = "v1")] use crate::routing; use crate::{ consts::{MAX_ORDER_FULFILLMENT_EXPIRY, MIN_ORDER_FULFILLMENT_EXPIRY}, enums as api_enums, payment_methods, }; #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] pub struct MerchantAccountListRequest { pub organization_id: id_type::OrganizationId, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MerchantAccountCreate { /// The identifier for the Merchant Account #[schema(value_type = String, max_length = 64, min_length = 1, example = "y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_id: id_type::MerchantId, /// Name of the Merchant Account #[schema(value_type= Option<String>,example = "NewAge Retailer")] pub merchant_name: Option<Secret<String>>, /// Details about the merchant, can contain phone and emails of primary and secondary contact person pub merchant_details: Option<MerchantDetails>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<url::Url>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// The routing algorithm to be used for routing payments to desired connectors #[serde(skip)] #[schema(deprecated)] pub routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used for routing payouts to desired connectors #[cfg(feature = "payouts")] #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. #[schema(default = false, example = false)] pub sub_merchants_enabled: Option<bool>, /// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf", value_type = Option<String>)] pub parent_merchant_id: Option<id_type::MerchantId>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = false, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled. #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Metadata is useful for storing additional, unstructured information on an object #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<MerchantAccountMetadata>, /// API key that will be used for client side API access. A publishable key has to be always paired with a `client_secret`. /// A `client_secret` can be obtained by creating a payment with `confirm` set to false #[schema(example = "AH3423bkjbkjdsfbkj")] pub publishable_key: Option<String>, /// An identifier for the vault used to store payment method information. #[schema(example = "locker_abc123")] pub locker_id: Option<String>, /// Details about the primary business unit of the merchant account #[schema(value_type = Option<PrimaryBusinessDetails>)] pub primary_business_details: Option<Vec<PrimaryBusinessDetails>>, /// The frm routing algorithm to be used for routing payments to desired FRM's #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The id of the organization to which the merchant belongs to, if not passed an organization is created #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub organization_id: Option<id_type::OrganizationId>, /// Default payment method collect link config #[schema(value_type = Option<BusinessCollectLinkConfig>)] pub pm_collect_link_config: Option<BusinessCollectLinkConfig>, /// Product Type of this merchant account #[schema(value_type = Option<MerchantProductType>, example = "Orchestration")] pub product_type: Option<api_enums::MerchantProductType>, } #[cfg(feature = "v1")] impl MerchantAccountCreate { pub fn get_merchant_reference_id(&self) -> id_type::MerchantId { self.merchant_id.clone() } pub fn get_payment_response_hash_key(&self) -> Option<String> { self.payment_response_hash_key.clone().or(Some( common_utils::crypto::generate_cryptographically_secure_random_string(64), )) } pub fn get_primary_details_as_value( &self, ) -> CustomResult<serde_json::Value, errors::ParsingError> { self.primary_business_details .clone() .unwrap_or_default() .encode_to_value() } pub fn get_pm_link_config_as_value( &self, ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { self.pm_collect_link_config .as_ref() .map(|pm_collect_link_config| pm_collect_link_config.encode_to_value()) .transpose() } pub fn get_merchant_details_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.merchant_details .as_ref() .map(|merchant_details| merchant_details.encode_to_value().map(Secret::new)) .transpose() } pub fn get_metadata_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.metadata .as_ref() .map(|metadata| metadata.encode_to_value().map(Secret::new)) .transpose() } pub fn parse_routing_algorithm(&self) -> CustomResult<(), errors::ParsingError> { match self.routing_algorithm { Some(ref routing_algorithm) => { let _: routing::RoutingAlgorithm = routing_algorithm.clone().parse_value("RoutingAlgorithm")?; Ok(()) } None => Ok(()), } } // Get the enable payment response hash as a boolean, where the default value is true pub fn get_enable_payment_response_hash(&self) -> bool { self.enable_payment_response_hash.unwrap_or(true) } } #[cfg(feature = "v2")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] #[schema(as = MerchantAccountCreate)] pub struct MerchantAccountCreateWithoutOrgId { /// Name of the Merchant Account, This will be used as a prefix to generate the id #[schema(value_type= String, max_length = 64, example = "NewAge Retailer")] pub merchant_name: Secret<common_utils::new_type::MerchantName>, /// Details about the merchant, contains phone and emails of primary and secondary contact person. pub merchant_details: Option<MerchantDetails>, /// Metadata is useful for storing additional, unstructured information about the merchant account. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, #[schema(value_type = Option<MerchantProductType>)] pub product_type: Option<api_enums::MerchantProductType>, } // In v2 the struct used in the API is MerchantAccountCreateWithoutOrgId // The following struct is only used internally, so we can reuse the common // part of `create_merchant_account` without duplicating its code for v2 #[cfg(feature = "v2")] #[derive(Clone, Debug, Serialize, ToSchema)] pub struct MerchantAccountCreate { pub merchant_name: Secret<common_utils::new_type::MerchantName>, pub merchant_details: Option<MerchantDetails>, pub metadata: Option<pii::SecretSerdeValue>, pub organization_id: id_type::OrganizationId, /// Product Type of this merchant account #[schema(value_type = Option<MerchantProductType>)] pub product_type: Option<api_enums::MerchantProductType>, } #[cfg(feature = "v2")] impl MerchantAccountCreate { pub fn get_merchant_reference_id(&self) -> id_type::MerchantId { id_type::MerchantId::from_merchant_name(self.merchant_name.clone().expose()) } pub fn get_merchant_details_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.merchant_details .as_ref() .map(|merchant_details| merchant_details.encode_to_value().map(Secret::new)) .transpose() } pub fn get_metadata_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.metadata .as_ref() .map(|metadata| metadata.encode_to_value().map(Secret::new)) .transpose() } pub fn get_primary_details_as_value( &self, ) -> CustomResult<serde_json::Value, errors::ParsingError> { Vec::<PrimaryBusinessDetails>::new().encode_to_value() } } #[derive(Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct CardTestingGuardConfig { /// Determines if Card IP Blocking is enabled for profile pub card_ip_blocking_status: CardTestingGuardStatus, /// Determines the unsuccessful payment threshold for Card IP Blocking for profile pub card_ip_blocking_threshold: i32, /// Determines if Guest User Card Blocking is enabled for profile pub guest_user_card_blocking_status: CardTestingGuardStatus, /// Determines the unsuccessful payment threshold for Guest User Card Blocking for profile pub guest_user_card_blocking_threshold: i32, /// Determines if Customer Id Blocking is enabled for profile pub customer_id_blocking_status: CardTestingGuardStatus, /// Determines the unsuccessful payment threshold for Customer Id Blocking for profile pub customer_id_blocking_threshold: i32, /// Determines Redis Expiry for Card Testing Guard for profile pub card_testing_guard_expiry: i32, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum CardTestingGuardStatus { Enabled, Disabled, } #[derive(Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct AuthenticationConnectorDetails { /// List of authentication connectors #[schema(value_type = Vec<AuthenticationConnectors>)] pub authentication_connectors: Vec<common_enums::AuthenticationConnectors>, /// URL of the (customer service) website that will be shown to the shopper in case of technical errors during the 3D Secure 2 process. pub three_ds_requestor_url: String, /// Merchant app declaring their URL within the CReq message so that the Authentication app can call the Merchant app after OOB authentication has occurred. pub three_ds_requestor_app_url: Option<String>, } #[derive(Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct MerchantAccountMetadata { pub compatible_connector: Option<api_enums::Connector>, #[serde(flatten)] pub data: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MerchantAccountUpdate { /// The identifier for the Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// Name of the Merchant Account #[schema(example = "NewAge Retailer")] pub merchant_name: Option<String>, /// Details about the merchant pub merchant_details: Option<MerchantDetails>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<url::Url>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// The routing algorithm to be used for routing payments to desired connectors #[serde(skip)] #[schema(deprecated)] pub routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. #[schema(default = false, example = false)] pub sub_merchants_enabled: Option<bool>, /// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf", value_type = Option<String>)] pub parent_merchant_id: Option<id_type::MerchantId>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = false, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// API key that will be used for server side API access #[schema(example = "AH3423bkjbkjdsfbkj")] pub publishable_key: Option<String>, /// An identifier for the vault used to store payment method information. #[schema(example = "locker_abc123")] pub locker_id: Option<String>, /// Details about the primary business unit of the merchant account pub primary_business_details: Option<Vec<PrimaryBusinessDetails>>, /// The frm routing algorithm to be used for routing payments to desired FRM's #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The default profile that must be used for creating merchant accounts and payments #[schema(max_length = 64, value_type = Option<String>)] pub default_profile: Option<id_type::ProfileId>, /// Default payment method collect link config #[schema(value_type = Option<BusinessCollectLinkConfig>)] pub pm_collect_link_config: Option<BusinessCollectLinkConfig>, } #[cfg(feature = "v1")] impl MerchantAccountUpdate { pub fn get_primary_details_as_value( &self, ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { self.primary_business_details .as_ref() .map(|primary_business_details| primary_business_details.encode_to_value()) .transpose() } pub fn get_pm_link_config_as_value( &self, ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { self.pm_collect_link_config .as_ref() .map(|pm_collect_link_config| pm_collect_link_config.encode_to_value()) .transpose() } pub fn get_merchant_details_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.merchant_details .as_ref() .map(|merchant_details| merchant_details.encode_to_value().map(Secret::new)) .transpose() } pub fn get_metadata_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.metadata .as_ref() .map(|metadata| metadata.encode_to_value().map(Secret::new)) .transpose() } pub fn get_webhook_details_as_value( &self, ) -> CustomResult<Option<serde_json::Value>, errors::ParsingError> { self.webhook_details .as_ref() .map(|webhook_details| webhook_details.encode_to_value()) .transpose() } pub fn parse_routing_algorithm(&self) -> CustomResult<(), errors::ParsingError> { match self.routing_algorithm { Some(ref routing_algorithm) => { let _: routing::RoutingAlgorithm = routing_algorithm.clone().parse_value("RoutingAlgorithm")?; Ok(()) } None => Ok(()), } } // Get the enable payment response hash as a boolean, where the default value is true pub fn get_enable_payment_response_hash(&self) -> bool { self.enable_payment_response_hash.unwrap_or(true) } } #[cfg(feature = "v2")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MerchantAccountUpdate { /// Name of the Merchant Account #[schema(example = "NewAge Retailer")] pub merchant_name: Option<String>, /// Details about the merchant pub merchant_details: Option<MerchantDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, } #[cfg(feature = "v2")] impl MerchantAccountUpdate { pub fn get_merchant_details_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.merchant_details .as_ref() .map(|merchant_details| merchant_details.encode_to_value().map(Secret::new)) .transpose() } pub fn get_metadata_as_secret( &self, ) -> CustomResult<Option<pii::SecretSerdeValue>, errors::ParsingError> { self.metadata .as_ref() .map(|metadata| metadata.encode_to_value().map(Secret::new)) .transpose() } } #[cfg(feature = "v1")] #[derive(Clone, Debug, ToSchema, Serialize)] pub struct MerchantAccountResponse { /// The identifier for the Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// Name of the Merchant Account #[schema(value_type = Option<String>,example = "NewAge Retailer")] pub merchant_name: OptionalEncryptableName, /// The URL to redirect after completion of the payment #[schema(max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<String>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = false, example = true)] pub enable_payment_response_hash: bool, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf")] pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: bool, /// Details about the merchant #[schema(value_type = Option<MerchantDetails>)] pub merchant_details: Option<Encryptable<pii::SecretSerdeValue>>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[serde(skip)] #[schema(deprecated)] pub routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// A boolean value to indicate if the merchant is a sub-merchant under a master or a parent merchant. By default, its value is false. #[schema(default = false, example = false)] pub sub_merchants_enabled: Option<bool>, /// Refers to the Parent Merchant ID if the merchant being created is a sub-merchant #[schema(max_length = 255, example = "xkkdf909012sdjki2dkh5sdf", value_type = Option<String>)] pub parent_merchant_id: Option<id_type::MerchantId>, /// API key that will be used for server side API access #[schema(example = "AH3423bkjbkjdsfbkj")] pub publishable_key: Option<String>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// An identifier for the vault used to store payment method information. #[schema(example = "locker_abc123")] pub locker_id: Option<String>, /// Details about the primary business unit of the merchant account #[schema(value_type = Vec<PrimaryBusinessDetails>)] pub primary_business_details: Vec<PrimaryBusinessDetails>, /// The frm routing algorithm to be used to process the incoming request from merchant to outgoing payment FRM. #[schema(value_type = Option<RoutingAlgorithm>, max_length = 255, example = r#"{"type": "single", "data": "stripe" }"#)] pub frm_routing_algorithm: Option<serde_json::Value>, /// The organization id merchant is associated with #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub organization_id: id_type::OrganizationId, /// A boolean value to indicate if the merchant has recon service is enabled or not, by default value is false pub is_recon_enabled: bool, /// The default profile that must be used for creating merchant accounts and payments #[schema(max_length = 64, value_type = Option<String>)] pub default_profile: Option<id_type::ProfileId>, /// Used to indicate the status of the recon module for a merchant account #[schema(value_type = ReconStatus, example = "not_requested")] pub recon_status: api_enums::ReconStatus, /// Default payment method collect link config #[schema(value_type = Option<BusinessCollectLinkConfig>)] pub pm_collect_link_config: Option<BusinessCollectLinkConfig>, /// Product Type of this merchant account #[schema(value_type = Option<MerchantProductType>, example = "Orchestration")] pub product_type: Option<api_enums::MerchantProductType>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, ToSchema, Serialize)] pub struct MerchantAccountResponse { /// The identifier for the Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub id: id_type::MerchantId, /// Name of the Merchant Account #[schema(value_type = String,example = "NewAge Retailer")] pub merchant_name: Secret<String>, /// Details about the merchant #[schema(value_type = Option<MerchantDetails>)] pub merchant_details: Option<Encryptable<pii::SecretSerdeValue>>, /// API key that will be used for server side API access #[schema(example = "AH3423bkjbkjdsfbkj")] pub publishable_key: String, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// The id of the organization which the merchant is associated with #[schema(value_type = String, max_length = 64, min_length = 1, example = "org_q98uSGAYbjEwqs0mJwnz")] pub organization_id: id_type::OrganizationId, /// Used to indicate the status of the recon module for a merchant account #[schema(value_type = ReconStatus, example = "not_requested")] pub recon_status: api_enums::ReconStatus, /// Product Type of this merchant account #[schema(value_type = Option<MerchantProductType>, example = "Orchestration")] pub product_type: Option<api_enums::MerchantProductType>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct MerchantDetails { /// The merchant's primary contact name #[schema(value_type = Option<String>, max_length = 255, example = "John Doe")] pub primary_contact_person: Option<Secret<String>>, /// The merchant's primary phone number #[schema(value_type = Option<String>, max_length = 255, example = "999999999")] pub primary_phone: Option<Secret<String>>, /// The merchant's primary email address #[schema(value_type = Option<String>, max_length = 255, example = "johndoe@test.com")] pub primary_email: Option<pii::Email>, /// The merchant's secondary contact name #[schema(value_type = Option<String>, max_length= 255, example = "John Doe2")] pub secondary_contact_person: Option<Secret<String>>, /// The merchant's secondary phone number #[schema(value_type = Option<String>, max_length = 255, example = "999999988")] pub secondary_phone: Option<Secret<String>>, /// The merchant's secondary email address #[schema(value_type = Option<String>, max_length = 255, example = "johndoe2@test.com")] pub secondary_email: Option<pii::Email>, /// The business website of the merchant #[schema(max_length = 255, example = "www.example.com")] pub website: Option<String>, /// A brief description about merchant's business #[schema( max_length = 255, example = "Online Retail with a wide selection of organic products for North America" )] pub about_business: Option<String>, /// The merchant's address details pub address: Option<AddressDetails>, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize, PartialEq)] #[serde(deny_unknown_fields)] pub struct PrimaryBusinessDetails { #[schema(value_type = CountryAlpha2)] pub country: api_enums::CountryAlpha2, #[schema(example = "food")] pub business: String, } #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct WebhookDetails { ///The version for Webhook #[schema(max_length = 255, max_length = 255, example = "1.0.2")] pub webhook_version: Option<String>, ///The user name for Webhook login #[schema(max_length = 255, max_length = 255, example = "ekart_retail")] pub webhook_username: Option<String>, ///The password for Webhook login #[schema(value_type = Option<String>, max_length = 255, example = "ekart@123")] pub webhook_password: Option<Secret<String>>, ///The url for the webhook endpoint #[schema(value_type = Option<String>, example = "www.ekart.com/webhooks")] pub webhook_url: Option<Secret<String>>, /// If this property is true, a webhook message is posted whenever a new payment is created #[schema(example = true)] pub payment_created_enabled: Option<bool>, /// If this property is true, a webhook message is posted whenever a payment is successful #[schema(example = true)] pub payment_succeeded_enabled: Option<bool>, /// If this property is true, a webhook message is posted whenever a payment fails #[schema(example = true)] pub payment_failed_enabled: Option<bool>, } #[derive(Debug, Serialize, ToSchema)] pub struct MerchantAccountDeleteResponse { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// If the connector is deleted or not #[schema(example = false)] pub deleted: bool, } #[derive(Default, Debug, Deserialize, Serialize)] pub struct MerchantId { pub merchant_id: id_type::MerchantId, } #[cfg(feature = "v1")] #[derive(Debug, Deserialize, ToSchema, Serialize)] pub struct MerchantConnectorId { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } #[cfg(feature = "v2")] #[derive(Debug, Deserialize, ToSchema, Serialize)] pub struct MerchantConnectorId { #[schema(value_type = String)] pub id: id_type::MerchantConnectorAccountId, } #[cfg(feature = "v2")] /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorCreate { /// Type of the Connector for the financial use case. Could range from Payments to Accounting to Banking. #[schema(value_type = ConnectorType, example = "payment_processor")] pub connector_type: api_enums::ConnectorType, /// Name of the Connector #[schema(value_type = Connector, example = "stripe")] pub connector_name: api_enums::Connector, /// This is an unique label you can generate and pass in order to identify this connector account on your Hyperswitch dashboard and reports, If not passed then if will take `connector_name`_`profile_name`. Eg: if your profile label is `default`, connector label can be `stripe_default` #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = String)] pub profile_id: id_type::ProfileId, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: Option<pii::SecretSerdeValue>, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(value_type = PaymentMethodsEnabled)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, /// Webhook details of this merchant connector #[schema(example = json!({ "connector_webhook_details": { "merchant_secret": "1234567890987654321" } }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// pm_auth_config will relate MCA records to their respective chosen auth services, based on payment_method and pmt #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = Option<ConnectorStatus>, example = "inactive")] // By default the ConnectorStatus is Active pub status: Option<api_enums::ConnectorStatus>, /// In case the merchant needs to store any additional sensitive data #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials #[schema(value_type = Option<ConnectorWalletDetails>)] pub connector_wallets_details: Option<ConnectorWalletDetails>, /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<MerchantConnectorAccountFeatureMetadata>)] pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v2")] impl MerchantConnectorCreate { pub fn get_transaction_type(&self) -> api_enums::TransactionType { match self.connector_type { #[cfg(feature = "payouts")] api_enums::ConnectorType::PayoutProcessor => api_enums::TransactionType::Payout, _ => api_enums::TransactionType::Payment, } } pub fn get_frm_config_as_secret(&self) -> Option<Vec<Secret<serde_json::Value>>> { match self.frm_configs.as_ref() { Some(frm_value) => { let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value .iter() .map(|config| config.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() .ok()?; Some(configs_for_frm_value) } None => None, } } pub fn get_connector_label(&self, profile_name: String) -> String { match self.connector_label.clone() { Some(connector_label) => connector_label, None => format!("{}_{}", self.connector_name, profile_name), } } } #[cfg(feature = "v1")] /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] 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>, } #[cfg(feature = "v1")] impl MerchantConnectorCreate { pub fn get_transaction_type(&self) -> api_enums::TransactionType { match self.connector_type { #[cfg(feature = "payouts")] api_enums::ConnectorType::PayoutProcessor => api_enums::TransactionType::Payout, _ => api_enums::TransactionType::Payment, } } pub fn get_frm_config_as_secret(&self) -> Option<Vec<Secret<serde_json::Value>>> { match self.frm_configs.as_ref() { Some(frm_value) => { let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value .iter() .map(|config| config.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() .ok()?; Some(configs_for_frm_value) } None => None, } } } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum AdditionalMerchantData { OpenBankingRecipientData(MerchantRecipientData), } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] /// Feature metadata for merchant connector account pub struct MerchantConnectorAccountFeatureMetadata { /// Revenue recovery metadata for merchant connector account pub revenue_recovery: Option<RevenueRecoveryMetadata>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] /// Revenue recovery metadata for merchant connector account pub struct RevenueRecoveryMetadata { /// The maximum number of retries allowed for an invoice. This limit is set by the merchant for each `billing connector`. Once this limit is reached, no further retries will be attempted. #[schema(value_type = u16, example = "15")] pub max_retry_count: u16, /// Maximum number of `billing connector` retries before revenue recovery can start executing retries. #[schema(value_type = u16, example = "10")] pub billing_connector_retry_threshold: u16, /// Billing account reference id is payment gateway id at billing connector end. /// Merchants need to provide a mapping between these merchant connector account and the corresponding account reference IDs for each `billing connector`. #[schema(value_type = u16, example = r#"{ "mca_vDSg5z6AxnisHq5dbJ6g": "stripe_123", "mca_vDSg5z6AumisHqh4x5m1": "adyen_123" }"#)] pub billing_account_reference: HashMap<id_type::MerchantConnectorAccountId, String>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MerchantAccountData { Iban { #[schema(value_type= String)] iban: Secret<String>, name: String, #[schema(value_type= Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, Bacs { #[schema(value_type= String)] account_number: Secret<String>, #[schema(value_type= String)] sort_code: Secret<String>, name: String, #[schema(value_type= Option<String>)] #[serde(skip_serializing_if = "Option::is_none")] connector_recipient_id: Option<Secret<String>>, }, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum MerchantRecipientData { #[schema(value_type= Option<String>)] ConnectorRecipientId(Secret<String>), #[schema(value_type= Option<String>)] WalletId(Secret<String>), AccountData(MerchantAccountData), } // Different patterns of authentication. #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize)] #[serde(tag = "auth_type")] pub enum ConnectorAuthType { TemporaryAuth, HeaderKey { api_key: Secret<String>, }, BodyKey { api_key: Secret<String>, key1: Secret<String>, }, SignatureKey { api_key: Secret<String>, key1: Secret<String>, api_secret: Secret<String>, }, MultiAuthKey { api_key: Secret<String>, key1: Secret<String>, api_secret: Secret<String>, key2: Secret<String>, }, CurrencyAuthKey { auth_key_map: HashMap<common_enums::Currency, pii::SecretSerdeValue>, }, CertificateAuth { certificate: Secret<String>, private_key: Secret<String>, }, #[default] NoKey, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorWebhookDetails { #[schema(value_type = String, example = "12345678900987654321")] pub merchant_secret: Secret<String>, #[schema(value_type = String, example = "12345678900987654321")] pub additional_secret: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)] pub struct MerchantConnectorInfo { pub connector_label: String, #[schema(value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, } impl MerchantConnectorInfo { pub fn new( connector_label: String, merchant_connector_id: id_type::MerchantConnectorAccountId, ) -> Self { Self { connector_label, merchant_connector_id, } } } /// Response of creating a new Merchant Connector for the merchant account." #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorResponse { /// 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: common_enums::connector_enums::Connector, /// A unique label to identify the connector account created under a profile #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Unique ID of the merchant connector account #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub id: id_type::MerchantConnectorAccountId, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = String)] pub profile_id: id_type::ProfileId, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: pii::SecretSerdeValue, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(value_type = Vec<PaymentMethodsEnabled>)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, /// Webhook details of this merchant connector #[schema(example = json!({ "connector_webhook_details": { "merchant_secret": "1234567890987654321" } }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// identifier for the verified domains of a particular connector account pub applepay_verified_domains: Option<Vec<String>>, /// pm_auth_config will relate MCA records to their respective chosen auth services, based on payment_method and pmt #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: api_enums::ConnectorStatus, #[schema(value_type = Option<AdditionalMerchantData>)] pub additional_merchant_data: Option<AdditionalMerchantData>, /// The connector_wallets_details is used to store wallet details such as certificates and wallet credentials #[schema(value_type = Option<ConnectorWalletDetails>)] pub connector_wallets_details: Option<ConnectorWalletDetails>, /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<MerchantConnectorAccountFeatureMetadata>)] pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v2")] impl MerchantConnectorResponse { pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo { MerchantConnectorInfo { connector_label: connector_label.to_string(), merchant_connector_id: self.id.clone(), } } } /// Response of creating a new Merchant Connector for the merchant account." #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorResponse { /// 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: String, /// A unique label to identify the connector account created under a profile #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Unique ID of the merchant connector account #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = String)] pub profile_id: id_type::ProfileId, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: 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 #[schema(example = "travel")] 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>, /// identifier for the verified domains of a particular connector account pub applepay_verified_domains: Option<Vec<String>>, #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: api_enums::ConnectorStatus, #[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>, } #[cfg(feature = "v1")] impl MerchantConnectorResponse { pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo { MerchantConnectorInfo { connector_label: connector_label.to_string(), merchant_connector_id: self.merchant_connector_id.clone(), } } } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorListResponse { /// 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: String, /// A unique label to identify the connector account created under a profile #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Unique ID of the merchant connector account #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = String)] pub profile_id: id_type::ProfileId, /// An object containing the 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>>, /// 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 #[schema(example = "travel")] 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>, /// identifier for the verified domains of a particular connector account pub applepay_verified_domains: Option<Vec<String>>, #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: api_enums::ConnectorStatus, } #[cfg(feature = "v1")] impl MerchantConnectorListResponse { pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo { MerchantConnectorInfo { connector_label: connector_label.to_string(), merchant_connector_id: self.merchant_connector_id.clone(), } } pub fn get_connector_name(&self) -> String { self.connector_name.clone() } } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorListResponse { /// 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: common_enums::connector_enums::Connector, /// A unique label to identify the connector account created under a profile #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// Unique ID of the merchant connector account #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub id: id_type::MerchantConnectorAccountId, /// Identifier for the profile, if not provided default will be chosen from merchant account #[schema(max_length = 64, value_type = String)] pub profile_id: id_type::ProfileId, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(value_type = Vec<PaymentMethodsEnabled>)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, /// 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>>, /// identifier for the verified domains of a particular connector account pub applepay_verified_domains: Option<Vec<String>>, #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: api_enums::ConnectorStatus, } #[cfg(feature = "v2")] impl MerchantConnectorListResponse { pub fn to_merchant_connector_info(&self, connector_label: &String) -> MerchantConnectorInfo { MerchantConnectorInfo { connector_label: connector_label.to_string(), merchant_connector_id: self.id.clone(), } } pub fn get_connector_name(&self) -> common_enums::connector_enums::Connector { self.connector_name } } /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorUpdate { /// 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, /// 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>, /// 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>>, /// pm_auth_config will relate MCA records to their respective chosen auth services, based on payment_method and pmt #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = 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>, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct ConnectorWalletDetails { /// This field contains the Apple Pay certificates and credentials for iOS and Web Apple Pay flow #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub apple_pay_combined: Option<pii::SecretSerdeValue>, /// This field is for our legacy Apple Pay flow that contains the Apple Pay certificates and credentials for only iOS Apple Pay flow #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub apple_pay: Option<pii::SecretSerdeValue>, /// This field contains the Samsung Pay certificates and credentials #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub samsung_pay: Option<pii::SecretSerdeValue>, /// This field contains the Paze certificates and credentials #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub paze: Option<pii::SecretSerdeValue>, /// This field contains the Google Pay certificates and credentials #[serde(skip_serializing_if = "Option::is_none")] #[schema(value_type = Option<Object>)] pub google_pay: Option<pii::SecretSerdeValue>, } /// Create a new Merchant Connector for the merchant account. The connector could be a payment processor / facilitator / acquirer or specialized services like Fraud / Accounting etc." #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct MerchantConnectorUpdate { /// 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, /// This is an unique label you can generate and pass in order to identify this connector account on your Hyperswitch dashboard and reports, If not passed then if will take `connector_name`_`profile_name`. Eg: if your profile label is `default`, connector label can be `stripe_default` #[schema(example = "stripe_US_travel")] pub connector_label: Option<String>, /// An object containing the required details/credentials for a Connector account. #[schema(value_type = Option<MerchantConnectorDetails>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: Option<pii::SecretSerdeValue>, /// An object containing the details about the payment methods that need to be enabled under this merchant connector account #[schema(value_type = Option<Vec<PaymentMethodsEnabled>>)] pub payment_methods_enabled: Option<Vec<common_types::payment_methods::PaymentMethodsEnabled>>, /// Webhook details of this merchant connector #[schema(example = json!({ "connector_webhook_details": { "merchant_secret": "1234567890987654321" } }))] pub connector_webhook_details: Option<MerchantConnectorWebhookDetails>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,max_length = 255,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A boolean value to indicate if the connector is disabled. By default, its value is false. #[schema(default = false, example = false)] pub disabled: Option<bool>, /// Contains the frm configs for the merchant connector #[schema(example = json!(consts::FRM_CONFIGS_EG))] pub frm_configs: Option<Vec<FrmConfigs>>, /// pm_auth_config will relate MCA records to their respective chosen auth services, based on payment_method and pmt #[schema(value_type = Option<Object>)] pub pm_auth_config: Option<pii::SecretSerdeValue>, #[schema(value_type = ConnectorStatus, example = "inactive")] pub status: Option<api_enums::ConnectorStatus>, /// The identifier for the Merchant Account #[schema(value_type = String, max_length = 64, min_length = 1, example = "y3oqhf46pyzuxjbcn2giaqnb44")] pub merchant_id: id_type::MerchantId, /// 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 pub connector_wallets_details: Option<ConnectorWalletDetails>, /// Additional data that might be required by hyperswitch, to enable some specific features. #[schema(value_type = Option<MerchantConnectorAccountFeatureMetadata>)] pub feature_metadata: Option<MerchantConnectorAccountFeatureMetadata>, } #[cfg(feature = "v2")] impl MerchantConnectorUpdate { pub fn get_frm_config_as_secret(&self) -> Option<Vec<Secret<serde_json::Value>>> { match self.frm_configs.as_ref() { Some(frm_value) => { let configs_for_frm_value: Vec<Secret<serde_json::Value>> = frm_value .iter() .map(|config| config.encode_to_value().map(Secret::new)) .collect::<Result<Vec<_>, _>>() .ok()?; Some(configs_for_frm_value) } None => None, } } } ///Details of FrmConfigs are mentioned here... it should be passed in payment connector create api call, and stored in merchant_connector_table #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct FrmConfigs { ///this is the connector that can be used for the payment #[schema(value_type = ConnectorType, example = "payment_processor")] pub gateway: Option<api_enums::Connector>, ///payment methods that can be used in the payment pub payment_methods: Vec<FrmPaymentMethod>, } ///Details of FrmPaymentMethod are mentioned here... it should be passed in payment connector create api call, and stored in merchant_connector_table #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct FrmPaymentMethod { ///payment methods(card, wallet, etc) that can be used in the payment #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: Option<common_enums::PaymentMethod>, ///payment method types(credit, debit) that can be used in the payment. This field is deprecated. It has not been removed to provide backward compatibility. pub payment_method_types: Option<Vec<FrmPaymentMethodType>>, ///frm flow type to be used, can be pre/post #[schema(value_type = Option<FrmPreferredFlowTypes>)] pub flow: Option<api_enums::FrmPreferredFlowTypes>, } ///Details of FrmPaymentMethodType are mentioned here... it should be passed in payment connector create api call, and stored in merchant_connector_table #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct FrmPaymentMethodType { ///payment method types(credit, debit) that can be used in the payment #[schema(value_type = PaymentMethodType)] pub payment_method_type: Option<common_enums::PaymentMethodType>, ///card networks(like visa mastercard) types that can be used in the payment #[schema(value_type = CardNetwork)] pub card_networks: Option<Vec<common_enums::CardNetwork>>, ///frm flow type to be used, can be pre/post #[schema(value_type = FrmPreferredFlowTypes)] pub flow: api_enums::FrmPreferredFlowTypes, ///action that the frm would take, in case fraud is detected #[schema(value_type = FrmAction)] pub action: api_enums::FrmAction, } /// Details of all the payment methods enabled for the connector for the given merchant account #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodsEnabled { /// Type of payment method. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: common_enums::PaymentMethod, /// Subtype of payment method #[schema(value_type = Option<Vec<RequestPaymentMethodTypes>>,example = json!(["credit"]))] pub payment_method_types: Option<Vec<payment_methods::RequestPaymentMethodTypes>>, } impl PaymentMethodsEnabled { /// Get payment_method #[cfg(feature = "v1")] pub fn get_payment_method(&self) -> Option<common_enums::PaymentMethod> { Some(self.payment_method) } /// Get payment_method_types #[cfg(feature = "v1")] pub fn get_payment_method_type( &self, ) -> Option<&Vec<payment_methods::RequestPaymentMethodTypes>> { self.payment_method_types.as_ref() } } #[derive(PartialEq, Eq, Hash, Debug, Clone, serde::Serialize, Deserialize, ToSchema)] #[serde( deny_unknown_fields, tag = "type", content = "list", rename_all = "snake_case" )] pub enum AcceptedCurrencies { #[schema(value_type = Vec<Currency>)] EnableOnly(Vec<api_enums::Currency>), #[schema(value_type = Vec<Currency>)] DisableOnly(Vec<api_enums::Currency>), AllAccepted, } #[derive(PartialEq, Eq, Hash, Debug, Clone, serde::Serialize, Deserialize, ToSchema)] #[serde( deny_unknown_fields, tag = "type", content = "list", rename_all = "snake_case" )] /// Object to filter the customer countries for which the payment method is displayed pub enum AcceptedCountries { #[schema(value_type = Vec<CountryAlpha2>)] EnableOnly(Vec<api_enums::CountryAlpha2>), #[schema(value_type = Vec<CountryAlpha2>)] DisableOnly(Vec<api_enums::CountryAlpha2>), AllAccepted, } #[cfg(feature = "v1")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct MerchantConnectorDeleteResponse { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// Unique ID of the connector #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub merchant_connector_id: id_type::MerchantConnectorAccountId, /// If the connector is deleted or not #[schema(example = false)] pub deleted: bool, } #[cfg(feature = "v2")] #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct MerchantConnectorDeleteResponse { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// Unique ID of the connector #[schema(example = "mca_5apGeP94tMts6rg3U3kR", value_type = String)] pub id: id_type::MerchantConnectorAccountId, /// If the connector is deleted or not #[schema(example = false)] pub deleted: bool, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ToggleKVResponse { /// The identifier for the Merchant Account #[schema(max_length = 255, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// Status of KV for the specific merchant #[schema(example = true)] pub kv_enabled: bool, } #[derive(Debug, Clone, Eq, PartialEq, Serialize, Deserialize, ToSchema)] pub struct MerchantKeyTransferRequest { /// Offset for merchant account #[schema(example = 32)] pub from: u32, /// Limit for merchant account #[schema(example = 32)] pub limit: u32, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct TransferKeyResponse { /// The identifier for the Merchant Account #[schema(example = 32)] pub total_transferred: usize, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ToggleKVRequest { #[serde(skip_deserializing)] #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, /// Status of KV for the specific merchant #[schema(example = true)] pub kv_enabled: bool, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ToggleAllKVRequest { /// Status of KV for the specific merchant #[schema(example = true)] pub kv_enabled: bool, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct ToggleAllKVResponse { ///Total number of updated merchants #[schema(example = 20)] pub total_updated: usize, /// Status of KV for the specific merchant #[schema(example = true)] pub kv_enabled: bool, } /// Merchant connector details used to make payments. #[derive(Debug, Clone, Default, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct MerchantConnectorDetailsWrap { /// Creds Identifier is to uniquely identify the credentials. Do not send any sensitive info, like encoded_data in this field. And do not send the string "null". pub creds_identifier: String, /// Merchant connector details type type. Base64 Encode the credentials and send it in this type and send as a string. #[schema(value_type = Option<MerchantConnectorDetails>, example = r#"{ "connector_account_details": { "auth_type": "HeaderKey", "api_key":"sk_test_xxxxxexamplexxxxxx12345" }, "metadata": { "user_defined_field_1": "sample_1", "user_defined_field_2": "sample_2", }, }"#)] pub encoded_data: Option<Secret<String>>, } #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] pub struct MerchantConnectorDetails { /// Account details of the Connector. You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "auth_type": "HeaderKey","api_key": "Basic MyVerySecretApiKey" }))] pub connector_account_details: pii::SecretSerdeValue, /// 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>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Deserialize, ToSchema, Default, Serialize)] #[serde(deny_unknown_fields)] pub struct ProfileCreate { /// The name of profile #[schema(max_length = 64)] pub profile_name: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<url::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// The routing algorithm to be used for routing payments to desired connectors #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "stripe"}))] pub routing_algorithm: Option<serde_json::Value>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(example = 900)] pub intent_fulfillment_time: Option<u32>, /// The frm routing algorithm to be used for routing payments to desired FRM's #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<u32>, /// Default Payment Link config for all payment links created under this profile pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, /// Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. #[serde(default)] pub is_tax_connector_enabled: bool, /// Indicates if network tokenization is enabled or not. #[serde(default)] pub is_network_tokenization_enabled: bool, /// Indicates if is_auto_retries_enabled is enabled or not. pub is_auto_retries_enabled: Option<bool>, /// Maximum number of auto retries allowed for a payment pub max_auto_retries_enabled: Option<u8>, /// Bool indicating if extended authentication must be requested for all payments #[schema(value_type = Option<bool>)] pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, /// Indicates if click to pay is enabled or not. #[serde(default)] pub is_click_to_pay_enabled: bool, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: Option<bool>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[nutype::nutype( validate(greater_or_equal = MIN_ORDER_FULFILLMENT_EXPIRY, less_or_equal = MAX_ORDER_FULFILLMENT_EXPIRY), derive(Clone, Copy, Debug, Deserialize, Serialize) )] pub struct OrderFulfillmentTime(i64); #[cfg(feature = "v2")] #[derive(Clone, Debug, Deserialize, ToSchema, Default, Serialize)] #[serde(deny_unknown_fields)] pub struct ProfileCreate { /// The name of profile #[schema(max_length = 64)] pub profile_name: String, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<common_utils::types::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(value_type = Option<u32>, example = 900)] pub order_fulfillment_time: Option<OrderFulfillmentTime>, /// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment #[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")] pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<u32>, /// Default Payment Link config for all payment links created under this profile pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, /// Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. #[serde(default)] pub is_tax_connector_enabled: bool, /// Indicates if network tokenization is enabled or not. #[serde(default)] pub is_network_tokenization_enabled: bool, /// Indicates if click to pay is enabled or not. #[schema(default = false, example = false)] #[serde(default)] pub is_click_to_pay_enabled: bool, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: Option<bool>, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, ToSchema, Serialize)] pub struct ProfileResponse { /// The identifier for Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// The identifier for profile. This must be used for creating merchant accounts, payments and payouts #[schema(max_length = 64, value_type = String, example = "pro_abcdefghijklmnopqrstuvwxyz")] pub profile_id: id_type::ProfileId, /// Name of the profile #[schema(max_length = 64)] pub profile_name: String, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<String>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: bool, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: bool, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// The routing algorithm to be used for routing payments to desired connectors #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "stripe"}))] pub routing_algorithm: Option<serde_json::Value>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(example = 900)] pub intent_fulfillment_time: Option<i64>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<i64>, /// Default Payment Link config for all payment links created under this profile #[schema(value_type = Option<BusinessPaymentLinkConfig>)] pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// Merchant's config to support extended card info feature pub extended_card_info_config: Option<ExtendedCardInfoConfig>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<MaskedHeaders>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. pub is_tax_connector_enabled: bool, /// Indicates if network tokenization is enabled or not. #[schema(default = false, example = false)] pub is_network_tokenization_enabled: bool, /// Indicates if is_auto_retries_enabled is enabled or not. #[schema(default = false, example = false)] pub is_auto_retries_enabled: bool, /// Maximum number of auto retries allowed for a payment pub max_auto_retries_enabled: Option<i16>, /// Bool indicating if extended authentication must be requested for all payments #[schema(value_type = Option<bool>)] pub always_request_extended_authorization: Option<primitive_wrappers::AlwaysRequestExtendedAuthorization>, /// Indicates if click to pay is enabled or not. #[schema(default = false, example = false)] pub is_click_to_pay_enabled: bool, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: bool, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: bool, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, ToSchema, Serialize)] pub struct ProfileResponse { /// The identifier for Merchant Account #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: id_type::MerchantId, /// The identifier for profile. This must be used for creating merchant accounts, payments and payouts #[schema(max_length = 64, value_type = String, example = "pro_abcdefghijklmnopqrstuvwxyz")] pub id: id_type::ProfileId, /// Name of the profile #[schema(max_length = 64)] pub profile_name: String, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<common_utils::types::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: bool, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: bool, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<i64>, /// Default Payment Link config for all payment links created under this profile #[schema(value_type = Option<BusinessPaymentLinkConfig>)] pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// Merchant's config to support extended card info feature pub extended_card_info_config: Option<ExtendedCardInfoConfig>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<MaskedHeaders>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(value_type = Option<u32>, example = 900)] pub order_fulfillment_time: Option<OrderFulfillmentTime>, /// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment #[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")] pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. pub is_tax_connector_enabled: bool, /// Indicates if network tokenization is enabled or not. #[schema(default = false, example = false)] pub is_network_tokenization_enabled: bool, /// Indicates if CVV should be collected during payment or not. #[schema(value_type = Option<bool>)] pub should_collect_cvv_during_payment: Option<primitive_wrappers::ShouldCollectCvvDuringPayment>, /// Indicates if click to pay is enabled or not. #[schema(default = false, example = false)] pub is_click_to_pay_enabled: bool, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: bool, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[cfg(feature = "v1")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct ProfileUpdate { /// The name of profile #[schema(max_length = 64)] pub profile_name: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<url::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// The routing algorithm to be used for routing payments to desired connectors #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "stripe"}))] pub routing_algorithm: Option<serde_json::Value>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(example = 900)] pub intent_fulfillment_time: Option<u32>, /// The frm routing algorithm to be used for routing payments to desired FRM's #[schema(value_type = Option<Object>,example = json!({"type": "single", "data": "signifyd"}))] pub frm_routing_algorithm: Option<serde_json::Value>, /// The routing algorithm to be used to process the incoming request from merchant to outgoing payment processor or payment method. The default is 'Custom' #[cfg(feature = "payouts")] #[schema(value_type = Option<RoutingAlgorithm>,example = json!({"type": "single", "data": "wise"}))] pub payout_routing_algorithm: Option<serde_json::Value>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<u32>, /// Default Payment Link config for all payment links created under this profile pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, /// Merchant's config to support extended card info feature pub extended_card_info_config: Option<ExtendedCardInfoConfig>, // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. pub is_tax_connector_enabled: Option<bool>, /// Indicates if dynamic routing is enabled or not. #[serde(default)] pub dynamic_routing_algorithm: Option<serde_json::Value>, /// Indicates if network tokenization is enabled or not. pub is_network_tokenization_enabled: Option<bool>, /// Indicates if is_auto_retries_enabled is enabled or not. pub is_auto_retries_enabled: Option<bool>, /// Maximum number of auto retries allowed for a payment pub max_auto_retries_enabled: Option<u8>, /// Indicates if click to pay is enabled or not. #[schema(default = false, example = false)] pub is_click_to_pay_enabled: Option<bool>, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: Option<bool>, /// Indicates if 3ds challenge is forced pub force_3ds_challenge: Option<bool>, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[cfg(feature = "v2")] #[derive(Clone, Debug, Deserialize, ToSchema, Serialize)] #[serde(deny_unknown_fields)] pub struct ProfileUpdate { /// The name of profile #[schema(max_length = 64)] pub profile_name: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, max_length = 255, example = "https://www.example.com/success")] pub return_url: Option<common_utils::types::Url>, /// A boolean value to indicate if payment response hash needs to be enabled #[schema(default = true, example = true)] pub enable_payment_response_hash: Option<bool>, /// Refers to the hash key used for calculating the signature for webhooks and redirect response. If the value is not provided, a value is automatically generated. pub payment_response_hash_key: Option<String>, /// A boolean value to indicate if redirect to merchant with http post needs to be enabled #[schema(default = false, example = true)] pub redirect_to_merchant_with_http_post: Option<bool>, /// Webhook related details pub webhook_details: Option<WebhookDetails>, /// Metadata is useful for storing additional, unstructured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "city": "NY", "unit": "245" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Will be used to determine the time till which your payment will be active once the payment session starts #[schema(value_type = Option<u32>, example = 900)] pub order_fulfillment_time: Option<OrderFulfillmentTime>, /// Whether the order fulfillment time is calculated from the origin or the time of creating the payment, or confirming the payment #[schema(value_type = Option<OrderFulfillmentTimeOrigin>, example = "create")] pub order_fulfillment_time_origin: Option<api_enums::OrderFulfillmentTimeOrigin>, /// Verified Apple Pay domains for a particular profile pub applepay_verified_domains: Option<Vec<String>>, /// Client Secret Default expiry for all payments created under this profile #[schema(example = 900)] pub session_expiry: Option<u32>, /// Default Payment Link config for all payment links created under this profile pub payment_link_config: Option<BusinessPaymentLinkConfig>, /// External 3DS authentication details pub authentication_connector_details: Option<AuthenticationConnectorDetails>, /// Merchant's config to support extended card info feature pub extended_card_info_config: Option<ExtendedCardInfoConfig>, // Whether to use the billing details passed when creating the intent as payment method billing pub use_billing_as_payment_method_billing: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_shipping_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector only if it is required field for connector (Eg. Apple Pay, Google Pay etc) #[schema(default = false, example = false)] pub collect_billing_details_from_wallet_connector_if_required: Option<bool>, /// A boolean value to indicate if customer shipping details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_shipping_details_from_wallet_connector: Option<bool>, /// A boolean value to indicate if customer billing details needs to be collected from wallet /// connector irrespective of connector required fields (Eg. Apple pay, Google pay etc) #[schema(default = false, example = false)] pub always_collect_billing_details_from_wallet_connector: Option<bool>, /// Indicates if the MIT (merchant initiated transaction) payments can be made connector /// agnostic, i.e., MITs may be processed through different connector than CIT (customer /// initiated transaction) based on the routing rules. /// If set to `false`, MIT will go through the same connector as the CIT. pub is_connector_agnostic_mit_enabled: Option<bool>, /// Default payout link config #[schema(value_type = Option<BusinessPayoutLinkConfig>)] pub payout_link_config: Option<BusinessPayoutLinkConfig>, /// These key-value pairs are sent as additional custom headers in the outgoing webhook request. It is recommended not to use more than four key-value pairs. #[schema(value_type = Option<Object>, example = r#"{ "key1": "value-1", "key2": "value-2" }"#)] pub outgoing_webhook_custom_http_headers: Option<HashMap<String, String>>, /// Merchant Connector id to be stored for tax_calculator connector #[schema(value_type = Option<String>)] pub tax_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Indicates if tax_calculator connector is enabled or not. /// If set to `true` tax_connector_id will be checked. pub is_tax_connector_enabled: Option<bool>, /// Indicates if network tokenization is enabled or not. pub is_network_tokenization_enabled: Option<bool>, /// Indicates if click to pay is enabled or not. #[schema(default = false, example = false)] pub is_click_to_pay_enabled: Option<bool>, /// Product authentication ids #[schema(value_type = Option<Object>, example = r#"{ "click_to_pay": "mca_ushduqwhdohwd", "netcetera": "mca_kwqhudqwd" }"#)] pub authentication_product_ids: Option<common_types::payments::AuthenticationConnectorAccountMap>, /// Card Testing Guard Configs pub card_testing_guard_config: Option<CardTestingGuardConfig>, ///Indicates if clear pan retries is enabled or not. pub is_clear_pan_retries_enabled: Option<bool>, /// Indicates if debit routing is enabled or not #[schema(value_type = Option<bool>)] pub is_debit_routing_enabled: Option<bool>, //Merchant country for the profile #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub merchant_business_country: Option<api_enums::CountryAlpha2>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BusinessCollectLinkConfig { #[serde(flatten)] pub config: BusinessGenericLinkConfig, /// List of payment methods shown on collect UI #[schema(value_type = Vec<EnabledPaymentMethod>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs", "sepa"]}]"#)] pub enabled_payment_methods: Vec<link_utils::EnabledPaymentMethod>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BusinessPayoutLinkConfig { #[serde(flatten)] pub config: BusinessGenericLinkConfig, /// Form layout of the payout link #[schema(value_type = Option<UIWidgetFormLayout>, max_length = 255, example = "tabs")] pub form_layout: Option<api_enums::UIWidgetFormLayout>, /// Allows for removing any validations / pre-requisites which are necessary in a production environment #[schema(value_type = Option<bool>, default = false)] pub payout_test_mode: Option<bool>, } #[derive(Clone, Debug, serde::Serialize)] pub struct MaskedHeaders(HashMap<String, String>); impl MaskedHeaders { fn mask_value(value: &str) -> String { let value_len = value.len(); let masked_value = if value_len <= 4 { "*".repeat(value_len) } else { value .char_indices() .map(|(index, ch)| { if index < 2 || index >= value_len - 2 { // Show the first two and last two characters, mask the rest with '*' ch } else { // Mask the remaining characters '*' } }) .collect::<String>() }; masked_value } pub fn from_headers(headers: HashMap<String, Secret<String>>) -> Self { let masked_headers = headers .into_iter() .map(|(key, value)| (key, Self::mask_value(value.peek()))) .collect(); Self(masked_headers) } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BusinessGenericLinkConfig { /// Custom domain name to be used for hosting the link pub domain_name: Option<String>, /// A list of allowed domains (glob patterns) where this link can be embedded / opened from pub allowed_domains: HashSet<String>, #[serde(flatten)] #[schema(value_type = GenericLinkUiConfig)] pub ui_config: link_utils::GenericLinkUiConfig, } impl BusinessGenericLinkConfig { pub fn validate(&self) -> Result<(), &str> { // Validate host domain name let host_domain_valid = self .domain_name .clone() .map(|host_domain| link_utils::validate_strict_domain(&host_domain)) .unwrap_or(true); if !host_domain_valid { return Err("Invalid host domain name received in payout_link_config"); } let are_allowed_domains_valid = self .allowed_domains .clone() .iter() .all(|allowed_domain| link_utils::validate_wildcard_domain(allowed_domain)); if !are_allowed_domains_valid { return Err("Invalid allowed domain names received in payout_link_config"); } Ok(()) } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct BusinessPaymentLinkConfig { /// Custom domain name to be used for hosting the link in your own domain pub domain_name: Option<String>, /// Default payment link config for all future payment link #[serde(flatten)] #[schema(value_type = PaymentLinkConfigRequest)] pub default_config: Option<PaymentLinkConfigRequest>, /// list of configs for multi theme setup pub business_specific_configs: Option<HashMap<String, PaymentLinkConfigRequest>>, /// A list of allowed domains (glob patterns) where this link can be embedded / opened from #[schema(value_type = Option<HashSet<String>>)] pub allowed_domains: Option<HashSet<String>>, /// Toggle for HyperSwitch branding visibility pub branding_visibility: Option<bool>, } impl BusinessPaymentLinkConfig { pub fn validate(&self) -> Result<(), &str> { let host_domain_valid = self .domain_name .clone() .map(|host_domain| link_utils::validate_strict_domain(&host_domain)) .unwrap_or(true); if !host_domain_valid { return Err("Invalid host domain name received in payment_link_config"); } let are_allowed_domains_valid = self .allowed_domains .clone() .map(|allowed_domains| { allowed_domains .iter() .all(|allowed_domain| link_utils::validate_wildcard_domain(allowed_domain)) }) .unwrap_or(true); if !are_allowed_domains_valid { return Err("Invalid allowed domain names received in payment_link_config"); } Ok(()) } } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkConfigRequest { /// custom theme for the payment link #[schema(value_type = Option<String>, max_length = 255, example = "#4E6ADD")] pub theme: Option<String>, /// merchant display logo #[schema(value_type = Option<String>, max_length = 255, example = "https://i.pinimg.com/736x/4d/83/5c/4d835ca8aafbbb15f84d07d926fda473.jpg")] pub logo: Option<String>, /// Custom merchant name for payment link #[schema(value_type = Option<String>, max_length = 255, example = "hyperswitch")] pub seller_name: Option<String>, /// Custom layout for sdk #[schema(value_type = Option<String>, max_length = 255, example = "accordion")] pub sdk_layout: Option<String>, /// Display only the sdk for payment link #[schema(default = false, example = true)] pub display_sdk_only: Option<bool>, /// Enable saved payment method option for payment link #[schema(default = false, example = true)] pub enabled_saved_payment_method: Option<bool>, /// Hide card nickname field option for payment link #[schema(default = false, example = true)] pub hide_card_nickname_field: Option<bool>, /// Show card form by default for payment link #[schema(default = true, example = true)] pub show_card_form_by_default: Option<bool>, /// Dynamic details related to merchant to be rendered in payment link pub transaction_details: Option<Vec<PaymentLinkTransactionDetails>>, /// Configurations for the background image for details section pub background_image: Option<PaymentLinkBackgroundImageConfig>, /// Custom layout for details section #[schema(value_type = Option<PaymentLinkDetailsLayout>, example = "layout1")] pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, /// Text for payment link's handle confirm button pub payment_button_text: Option<String>, /// Text for customizing message for card terms pub custom_message_for_card_terms: Option<String>, /// Custom background colour for payment link's handle confirm button pub payment_button_colour: Option<String>, /// Skip the status screen after payment completion pub skip_status_screen: Option<bool>, /// Custom text colour for payment link's handle confirm button pub payment_button_text_colour: Option<String>, /// Custom background colour for the payment link pub background_colour: Option<String>, /// SDK configuration rules pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Payment link configuration rules pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkTransactionDetails { /// Key for the transaction details #[schema(value_type = String, max_length = 255, example = "Policy-Number")] pub key: String, /// Value for the transaction details #[schema(value_type = String, max_length = 255, example = "297472368473924")] pub value: String, /// UI configuration for the transaction details pub ui_configuration: Option<TransactionDetailsUiConfiguration>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct TransactionDetailsUiConfiguration { /// Position of the key-value pair in the UI #[schema(value_type = Option<i8>, example = 5)] pub position: Option<i8>, /// Whether the key should be bold #[schema(default = false, example = true)] pub is_key_bold: Option<bool>, /// Whether the value should be bold #[schema(default = false, example = true)] pub is_value_bold: Option<bool>, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize, PartialEq, ToSchema)] pub struct PaymentLinkBackgroundImageConfig { /// URL of the image #[schema(value_type = String, example = "https://hyperswitch.io/favicon.ico")] pub url: common_utils::types::Url, /// Position of the image in the UI #[schema(value_type = Option<ElementPosition>, example = "top-left")] pub position: Option<api_enums::ElementPosition>, /// Size of the image in the UI #[schema(value_type = Option<ElementSize>, example = "contain")] pub size: Option<api_enums::ElementSize>, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize, PartialEq, ToSchema)] pub struct PaymentLinkConfig { /// custom theme for the payment link pub theme: String, /// merchant display logo pub logo: String, /// Custom merchant name for payment link pub seller_name: String, /// Custom layout for sdk pub sdk_layout: String, /// Display only the sdk for payment link pub display_sdk_only: bool, /// Enable saved payment method option for payment link pub enabled_saved_payment_method: bool, /// Hide card nickname field option for payment link pub hide_card_nickname_field: bool, /// Show card form by default for payment link pub show_card_form_by_default: bool, /// A list of allowed domains (glob patterns) where this link can be embedded / opened from pub allowed_domains: Option<HashSet<String>>, /// Dynamic details related to merchant to be rendered in payment link pub transaction_details: Option<Vec<PaymentLinkTransactionDetails>>, /// Configurations for the background image for details section pub background_image: Option<PaymentLinkBackgroundImageConfig>, /// Custom layout for details section #[schema(value_type = Option<PaymentLinkDetailsLayout>, example = "layout1")] pub details_layout: Option<api_enums::PaymentLinkDetailsLayout>, /// Toggle for HyperSwitch branding visibility pub branding_visibility: Option<bool>, /// Text for payment link's handle confirm button pub payment_button_text: Option<String>, /// Text for customizing message for card terms pub custom_message_for_card_terms: Option<String>, /// Custom background colour for payment link's handle confirm button pub payment_button_colour: Option<String>, /// Skip the status screen after payment completion pub skip_status_screen: Option<bool>, /// Custom text colour for payment link's handle confirm button pub payment_button_text_colour: Option<String>, /// Custom background colour for the payment link pub background_colour: Option<String>, /// SDK configuration rules pub sdk_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Payment link configuration rules pub payment_link_ui_rules: Option<HashMap<String, HashMap<String, String>>>, /// Flag to enable the button only when the payment form is ready for submission pub enable_button_only_on_form_ready: bool, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct ExtendedCardInfoChoice { pub enabled: bool, } impl common_utils::events::ApiEventMetric for ExtendedCardInfoChoice {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, PartialEq, Eq)] pub struct ConnectorAgnosticMitChoice { pub enabled: bool, } impl common_utils::events::ApiEventMetric for ConnectorAgnosticMitChoice {} impl common_utils::events::ApiEventMetric for payment_methods::PaymentMethodMigrate {} #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ExtendedCardInfoConfig { /// Merchant public key #[schema(value_type = String)] pub public_key: Secret<String>, /// TTL for extended card info #[schema(default = 900, maximum = 7200, value_type = u16)] #[serde(default)] pub ttl_in_secs: TtlForExtendedCardInfo, } #[derive(Debug, serde::Serialize, Clone)] pub struct TtlForExtendedCardInfo(u16); impl Default for TtlForExtendedCardInfo { fn default() -> Self { Self(consts::DEFAULT_TTL_FOR_EXTENDED_CARD_INFO) } } impl<'de> Deserialize<'de> for TtlForExtendedCardInfo { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { let value = u16::deserialize(deserializer)?; // Check if value exceeds the maximum allowed if value > consts::MAX_TTL_FOR_EXTENDED_CARD_INFO { Err(serde::de::Error::custom( "ttl_in_secs must be less than or equal to 7200 (2hrs)", )) } else { Ok(Self(value)) } } } impl std::ops::Deref for TtlForExtendedCardInfo { type Target = u16; fn deref(&self) -> &Self::Target { &self.0 } }
30,641
1,969
hyperswitch
crates/api_models/src/lib.rs
.rs
pub mod admin; pub mod analytics; pub mod api_keys; pub mod apple_pay_certificates_migration; pub mod blocklist; pub mod cards_info; pub mod conditional_configs; pub mod connector_enums; pub mod connector_onboarding; pub mod consts; pub mod currency; pub mod customers; pub mod disputes; pub mod enums; pub mod ephemeral_key; #[cfg(feature = "errors")] pub mod errors; pub mod events; pub mod external_service_auth; pub mod feature_matrix; pub mod files; pub mod gsm; pub mod health_check; pub mod locker_migration; pub mod mandates; pub mod organization; pub mod payment_methods; pub mod payments; #[cfg(feature = "payouts")] pub mod payouts; pub mod pm_auth; pub mod poll; pub mod process_tracker; #[cfg(feature = "recon")] pub mod recon; pub mod refunds; pub mod relay; pub mod routing; pub mod surcharge_decision_configs; pub mod user; pub mod user_role; pub mod verifications; pub mod verify_connector; pub mod webhook_events; pub mod webhooks; pub trait ValidateFieldAndGet<Request> { fn validate_field_and_get( &self, request: &Request, ) -> common_utils::errors::CustomResult<Self, common_utils::errors::ValidationError> where Self: Sized; }
277
1,970
hyperswitch
crates/api_models/src/payouts.rs
.rs
use std::collections::HashMap; use cards::CardNumber; use common_utils::{ consts::default_payouts_list_limit, crypto, id_type, link_utils, payout_method_utils, pii::{self, Email}, transformers::ForeignFrom, types::{UnifiedCode, UnifiedMessage}, }; use masking::Secret; use router_derive::FlatStruct; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::{enums as api_enums, payment_methods::RequiredFieldInfo, payments}; #[derive(Debug, Deserialize, Serialize, Clone, ToSchema)] pub enum PayoutRequest { PayoutActionRequest(PayoutActionRequest), PayoutCreateRequest(Box<PayoutCreateRequest>), PayoutRetrieveRequest(PayoutRetrieveRequest), } #[derive( Default, Debug, Deserialize, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] #[serde(deny_unknown_fields)] pub struct PayoutCreateRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts that have been done by a single merchant. This field is auto generated and is returned in the API response, **not required to be included in the Payout Create/Update Request.** #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] pub payout_id: Option<String>, // TODO: #1321 https://github.com/juspay/hyperswitch/issues/1321 /// This is an identifier for the merchant account. This is inferred from the API key provided during the request, **not required to be included in the Payout Create/Update Request.** #[schema(max_length = 255, value_type = Option<String>, example = "merchant_1668273825")] #[remove_in(PayoutsCreateRequest, PayoutUpdateRequest, PayoutConfirmRequest)] pub merchant_id: Option<id_type::MerchantId>, /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = Option<u64>, example = 1000)] #[mandatory_in(PayoutsCreateRequest = u64)] #[remove_in(PayoutsConfirmRequest)] #[serde(default, deserialize_with = "payments::amount::deserialize_option")] pub amount: Option<payments::Amount>, /// The currency of the payout request can be specified here #[schema(value_type = Option<Currency>, example = "USD")] #[mandatory_in(PayoutsCreateRequest = Currency)] #[remove_in(PayoutsConfirmRequest)] pub currency: Option<api_enums::Currency>, /// Specifies routing algorithm for selecting a connector #[schema(value_type = Option<RoutingAlgorithm>, example = json!({ "type": "single", "data": "adyen" }))] pub routing: Option<serde_json::Value>, /// This field allows the merchant to manually select a connector with which the payout can go through. #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, /// This field is used when merchant wants to confirm the payout, thus useful for the payout _Confirm_ request. Ideally merchants should _Create_ a payout, _Update_ it (if required), then _Confirm_ it. #[schema(value_type = Option<bool>, example = true, default = false)] #[remove_in(PayoutConfirmRequest)] pub confirm: Option<bool>, /// The payout_type of the payout request can be specified here, this is a mandatory field to _Confirm_ the payout, i.e., should be passed in _Create_ request, if not then should be updated in the payout _Update_ request, then only it can be confirmed. #[schema(value_type = Option<PayoutType>, example = "card")] pub payout_type: Option<api_enums::PayoutType>, /// The payout method information required for carrying out a payout #[schema(value_type = Option<PayoutMethodData>)] pub payout_method_data: Option<PayoutMethodData>, /// The billing address for the payout #[schema(value_type = Option<Address>, example = json!(r#"{ "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Francisco", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" } }"#))] pub billing: Option<payments::Address>, /// Set to true to confirm the payout without review, no further action required #[schema(value_type = Option<bool>, example = true, default = false)] pub auto_fulfill: Option<bool>, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. _Deprecated: Use customer_id instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Passing this object creates a new customer or attaches an existing customer to the payout #[schema(value_type = Option<CustomerDetails>)] pub customer: Option<payments::CustomerDetails>, /// It's a token used for client side verification. #[schema(value_type = Option<String>, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] #[remove_in(PayoutsCreateRequest)] #[mandatory_in(PayoutConfirmRequest = String)] pub client_secret: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = Option<String>, example = "https://hyperswitch.io")] pub return_url: Option<String>, /// Business country of the merchant for this payout. _Deprecated: Use profile_id instead._ #[schema(deprecated, example = "US", value_type = Option<CountryAlpha2>)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payout. _Deprecated: Use profile_id instead._ #[schema(deprecated, example = "food", value_type = Option<String>)] pub business_label: Option<String>, /// A description of the payout #[schema(example = "It's my first payout request", value_type = Option<String>)] pub description: Option<String>, /// Type of entity to whom the payout is being carried out to, select from the given list of options #[schema(value_type = Option<PayoutEntityType>, example = "Individual")] pub entity_type: Option<api_enums::PayoutEntityType>, /// Specifies whether or not the payout request is recurring #[schema(value_type = Option<bool>, default = false)] pub recurring: Option<bool>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Provide a reference to a stored payout method, used to process the payout. #[schema(example = "187282ab-40ef-47a9-9206-5099ba31e432", value_type = Option<String>)] pub payout_token: Option<String>, /// The business profile to use for this payout, especially if there are multiple business profiles associated with the account, otherwise default business profile associated with the merchant account will be used. #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The send method which will be required for processing payouts, check options for better understanding. #[schema(value_type = Option<PayoutSendPriority>, example = "instant")] pub priority: Option<api_enums::PayoutSendPriority>, /// Whether to get the payout link (if applicable). Merchant need to specify this during the Payout _Create_, this field can not be updated during Payout _Update_. #[schema(default = false, example = true, value_type = Option<bool>)] pub payout_link: Option<bool>, /// Custom payout link config for the particular payout, if payout link is to be generated. #[schema(value_type = Option<PayoutCreatePayoutLinkConfig>)] pub payout_link_config: Option<PayoutCreatePayoutLinkConfig>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds /// (900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Customer's email. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: Option<Email>, /// Customer's name. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")] pub name: Option<Secret<String>>, /// Customer's phone. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: Option<Secret<String>>, /// Customer's phone country code. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, example = "+1")] pub phone_country_code: Option<String>, /// Identifier for payout method pub payout_method_id: Option<String>, } impl PayoutCreateRequest { pub fn get_customer_id(&self) -> Option<&id_type::CustomerId> { self.customer_id .as_ref() .or(self.customer.as_ref().map(|customer| &customer.id)) } } /// Custom payout link config for the particular payout, if payout link is to be generated. #[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)] pub struct PayoutCreatePayoutLinkConfig { /// The unique identifier for the collect link. #[schema(value_type = Option<String>, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub payout_link_id: Option<String>, #[serde(flatten)] #[schema(value_type = Option<GenericLinkUiConfig>)] pub ui_config: Option<link_utils::GenericLinkUiConfig>, /// List of payout methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, /// Form layout of the payout link #[schema(value_type = Option<UIWidgetFormLayout>, max_length = 255, example = "tabs")] pub form_layout: Option<api_enums::UIWidgetFormLayout>, /// `test_mode` allows for opening payout links without any restrictions. This removes /// - domain name validations /// - check for making sure link is accessed within an iframe #[schema(value_type = Option<bool>, example = false)] pub test_mode: Option<bool>, } /// The payout method information required for carrying out a payout #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodData { Card(CardPayout), Bank(Bank), Wallet(Wallet), } impl Default for PayoutMethodData { fn default() -> Self { Self::Card(CardPayout::default()) } } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct CardPayout { /// The card number #[schema(value_type = String, example = "4242424242424242")] pub card_number: CardNumber, /// The card's expiry month #[schema(value_type = String)] pub expiry_month: Secret<String>, /// The card's expiry year #[schema(value_type = String)] pub expiry_year: Secret<String>, /// The card holder's name #[schema(value_type = String, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(untagged)] pub enum Bank { Ach(AchBankTransfer), Bacs(BacsBankTransfer), Sepa(SepaBankTransfer), Pix(PixBankTransfer), } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct AchBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// [9 digits] Routing number - used in USA for identifying a specific bank. #[schema(value_type = String, example = "110000000")] pub bank_routing_number: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct BacsBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// [6 digits] Sort Code - used in UK and Ireland for identifying a bank and it's branches. #[schema(value_type = String, example = "98-76-54")] pub bank_sort_code: Secret<String>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] // The SEPA (Single Euro Payments Area) is a pan-European network that allows you to send and receive payments in euros between two cross-border bank accounts in the eurozone. pub struct SepaBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank country code #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub bank_country_code: Option<api_enums::CountryAlpha2>, /// Bank city #[schema(value_type = Option<String>, example = "California")] pub bank_city: Option<String>, /// International Bank Account Number (iban) - used in many countries for identifying a bank along with it's customer. #[schema(value_type = String, example = "DE89370400440532013000")] pub iban: Secret<String>, /// [8 / 11 digits] Bank Identifier Code (bic) / Swift Code - used in many countries for identifying a bank and it's branches #[schema(value_type = String, example = "HSBCGB2LXXX")] pub bic: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct PixBankTransfer { /// Bank name #[schema(value_type = Option<String>, example = "Deutsche Bank")] pub bank_name: Option<String>, /// Bank branch #[schema(value_type = Option<String>, example = "3707")] pub bank_branch: Option<String>, /// Bank account number is an unique identifier assigned by a bank to a customer. #[schema(value_type = String, example = "000123456")] pub bank_account_number: Secret<String>, /// Unique key for pix customer #[schema(value_type = String, example = "000123456")] pub pix_key: Secret<String>, /// Individual taxpayer identification number #[schema(value_type = Option<String>, example = "000123456")] pub tax_id: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum Wallet { Paypal(Paypal), Venmo(Venmo), } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Paypal { /// Email linked with paypal account #[schema(value_type = String, example = "john.doe@example.com")] pub email: Option<Email>, /// mobile number linked to paypal account #[schema(value_type = String, example = "16608213349")] pub telephone_number: Option<Secret<String>>, /// id of the paypal account #[schema(value_type = String, example = "G83KXTJ5EHCQ2")] pub paypal_id: Option<Secret<String>>, } #[derive(Default, Eq, PartialEq, Clone, Debug, Deserialize, Serialize, ToSchema)] pub struct Venmo { /// mobile number linked to venmo account #[schema(value_type = String, example = "16608213349")] pub telephone_number: Option<Secret<String>>, } #[derive(Debug, ToSchema, Clone, Serialize, router_derive::PolymorphicSchema)] #[serde(deny_unknown_fields)] pub struct PayoutCreateResponse { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: String, // TODO: Update this to PayoutIdType similar to PaymentIdType /// This is an identifier for the merchant account. This is inferred from the API key /// provided during the request #[schema(max_length = 255, value_type = String, example = "merchant_1668273825")] pub merchant_id: id_type::MerchantId, /// The payout amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 1000)] pub amount: common_utils::types::MinorUnit, /// Recipient's currency for the payout request #[schema(value_type = Currency, example = "USD")] pub currency: api_enums::Currency, /// The connector used for the payout #[schema(example = "wise")] pub connector: Option<String>, /// The payout method that is to be used #[schema(value_type = Option<PayoutType>, example = "bank")] pub payout_type: Option<api_enums::PayoutType>, /// The payout method details for the payout #[schema(value_type = Option<PayoutMethodDataResponse>, example = json!(r#"{ "card": { "last4": "2503", "card_type": null, "card_network": null, "card_issuer": null, "card_issuing_country": null, "card_isin": "400000", "card_extended_bin": null, "card_exp_month": "08", "card_exp_year": "25", "card_holder_name": null, "payment_checks": null, "authentication_data": null } }"#))] pub payout_method_data: Option<PayoutMethodDataResponse>, /// The billing address for the payout #[schema(value_type = Option<Address>, example = json!(r#"{ "address": { "line1": "1467", "line2": "Harrison Street", "line3": "Harrison Street", "city": "San Francisco", "state": "CA", "zip": "94122", "country": "US", "first_name": "John", "last_name": "Doe" }, "phone": { "number": "9123456789", "country_code": "+1" } }"#))] pub billing: Option<payments::Address>, /// Set to true to confirm the payout without review, no further action required #[schema(value_type = bool, example = true, default = false)] pub auto_fulfill: bool, /// The identifier for the customer object. If not provided the customer ID will be autogenerated. #[schema(value_type = String, max_length = 255, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Passing this object creates a new customer or attaches an existing customer to the payout #[schema(value_type = Option<CustomerDetailsResponse>)] pub customer: Option<payments::CustomerDetailsResponse>, /// It's a token used for client side verification. #[schema(value_type = String, example = "pay_U42c409qyHwOkWo3vK60_secret_el9ksDkiB8hi6j9N78yo")] pub client_secret: Option<String>, /// The URL to redirect after the completion of the operation #[schema(value_type = String, example = "https://hyperswitch.io")] pub return_url: Option<String>, /// Business country of the merchant for this payout #[schema(example = "US", value_type = CountryAlpha2)] pub business_country: Option<api_enums::CountryAlpha2>, /// Business label of the merchant for this payout #[schema(example = "food", value_type = Option<String>)] pub business_label: Option<String>, /// A description of the payout #[schema(example = "It's my first payout request", value_type = Option<String>)] pub description: Option<String>, /// Type of entity to whom the payout is being carried out to #[schema(value_type = PayoutEntityType, example = "Individual")] pub entity_type: api_enums::PayoutEntityType, /// Specifies whether or not the payout request is recurring #[schema(value_type = bool, default = false)] pub recurring: bool, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = r#"{ "udf1": "some-value", "udf2": "some-value" }"#)] pub metadata: Option<pii::SecretSerdeValue>, /// Unique identifier of the merchant connector account #[schema(value_type = Option<String>, example = "mca_sAD3OZLATetvjLOYhUSy")] pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, /// Current status of the Payout #[schema(value_type = PayoutStatus, example = RequiresConfirmation)] pub status: api_enums::PayoutStatus, /// If there was an error while calling the connector the error message is received here #[schema(value_type = Option<String>, example = "Failed while verifying the card")] pub error_message: Option<String>, /// If there was an error while calling the connectors the code is received here #[schema(value_type = Option<String>, example = "E0001")] pub error_code: Option<String>, /// The business profile that is associated with this payout #[schema(value_type = String)] pub profile_id: id_type::ProfileId, /// Time when the payout was created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// Underlying processor's payout resource ID #[schema(value_type = Option<String>, example = "S3FC9G9M2MVFDXT5")] pub connector_transaction_id: Option<String>, /// Payout's send priority (if applicable) #[schema(value_type = Option<PayoutSendPriority>, example = "instant")] pub priority: Option<api_enums::PayoutSendPriority>, /// List of attempts #[schema(value_type = Option<Vec<PayoutAttemptResponse>>)] #[serde(skip_serializing_if = "Option::is_none")] pub attempts: Option<Vec<PayoutAttemptResponse>>, /// If payout link was requested, this contains the link's ID and the URL to render the payout widget #[schema(value_type = Option<PayoutLinkResponse>)] pub payout_link: Option<PayoutLinkResponse>, /// Customer's email. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, value_type = Option<String>, example = "johntest@test.com")] pub email: crypto::OptionalEncryptableEmail, /// Customer's name. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "John Test")] pub name: crypto::OptionalEncryptableName, /// Customer's phone. _Deprecated: Use customer object instead._ #[schema(deprecated, value_type = Option<String>, max_length = 255, example = "9123456789")] pub phone: crypto::OptionalEncryptablePhone, /// Customer's phone country code. _Deprecated: Use customer object instead._ #[schema(deprecated, max_length = 255, example = "+1")] pub phone_country_code: Option<String>, /// (This field is not live yet) /// Error code unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutCreateResponse)] #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] pub unified_code: Option<UnifiedCode>, /// (This field is not live yet) /// Error message unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutCreateResponse)] #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] pub unified_message: Option<UnifiedMessage>, /// Identifier for payout method pub payout_method_id: Option<String>, } /// The payout method information for response #[derive(Debug, Clone, Deserialize, Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PayoutMethodDataResponse { #[schema(value_type = CardAdditionalData)] Card(Box<payout_method_utils::CardAdditionalData>), #[schema(value_type = BankAdditionalData)] Bank(Box<payout_method_utils::BankAdditionalData>), #[schema(value_type = WalletAdditionalData)] Wallet(Box<payout_method_utils::WalletAdditionalData>), } #[derive( Default, Debug, serde::Serialize, Clone, PartialEq, ToSchema, router_derive::PolymorphicSchema, )] pub struct PayoutAttemptResponse { /// Unique identifier for the attempt pub attempt_id: String, /// The status of the attempt #[schema(value_type = PayoutStatus, example = "failed")] pub status: api_enums::PayoutStatus, /// The payout attempt amount. Amount for the payout in lowest denomination of the currency. (i.e) in cents for USD denomination, in paisa for INR denomination etc., #[schema(value_type = i64, example = 6583)] pub amount: common_utils::types::MinorUnit, /// The currency of the amount of the payout attempt #[schema(value_type = Option<Currency>, example = "USD")] pub currency: Option<api_enums::Currency>, /// The connector used for the payout pub connector: Option<String>, /// Connector's error code in case of failures pub error_code: Option<String>, /// Connector's error message in case of failures pub error_message: Option<String>, /// The payout method that was used #[schema(value_type = Option<PayoutType>, example = "bank")] pub payment_method: Option<api_enums::PayoutType>, /// Payment Method Type #[schema(value_type = Option<PaymentMethodType>, example = "bacs")] pub payout_method_type: Option<api_enums::PaymentMethodType>, /// A unique identifier for a payout provided by the connector pub connector_transaction_id: Option<String>, /// If the payout was cancelled the reason provided here pub cancellation_reason: Option<String>, /// (This field is not live yet) /// Error code unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutAttemptResponse)] #[schema(value_type = Option<String>, max_length = 255, example = "UE_000")] pub unified_code: Option<UnifiedCode>, /// (This field is not live yet) /// Error message unified across the connectors is received here in case of errors while calling the underlying connector #[remove_in(PayoutAttemptResponse)] #[schema(value_type = Option<String>, max_length = 1024, example = "Invalid card details")] pub unified_message: Option<UnifiedMessage>, } #[derive(Default, Debug, Clone, Deserialize, ToSchema)] pub struct PayoutRetrieveBody { pub force_sync: Option<bool>, #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutRetrieveRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: String, /// `force_sync` with the connector to get payout details /// (defaults to false) #[schema(value_type = Option<bool>, default = false, example = true)] pub force_sync: Option<bool>, /// The identifier for the Merchant Account. #[schema(value_type = Option<String>)] pub merchant_id: Option<id_type::MerchantId>, } #[derive( Default, Debug, Deserialize, Serialize, Clone, ToSchema, router_derive::PolymorphicSchema, )] #[generate_schemas(PayoutCancelRequest, PayoutFulfillRequest)] pub struct PayoutActionRequest { /// Unique identifier for the payout. This ensures idempotency for multiple payouts /// that have been done by a single merchant. This field is auto generated and is returned in the API response. #[schema( value_type = String, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] #[serde(skip_deserializing)] pub payout_id: String, } #[derive(Default, Debug, ToSchema, Clone, Deserialize)] pub struct PayoutVendorAccountDetails { pub vendor_details: PayoutVendorDetails, pub individual_details: PayoutIndividualDetails, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutVendorDetails { pub account_type: String, pub business_type: String, pub business_profile_mcc: Option<i32>, pub business_profile_url: Option<String>, pub business_profile_name: Option<Secret<String>>, pub company_address_line1: Option<Secret<String>>, pub company_address_line2: Option<Secret<String>>, pub company_address_postal_code: Option<Secret<String>>, pub company_address_city: Option<Secret<String>>, pub company_address_state: Option<Secret<String>>, pub company_phone: Option<Secret<String>>, pub company_tax_id: Option<Secret<String>>, pub company_owners_provided: Option<bool>, pub capabilities_card_payments: Option<bool>, pub capabilities_transfers: Option<bool>, } #[derive(Default, Debug, Serialize, ToSchema, Clone, Deserialize)] pub struct PayoutIndividualDetails { pub tos_acceptance_date: Option<i64>, pub tos_acceptance_ip: Option<Secret<String>>, pub individual_dob_day: Option<Secret<String>>, pub individual_dob_month: Option<Secret<String>>, pub individual_dob_year: Option<Secret<String>>, pub individual_id_number: Option<Secret<String>>, pub individual_ssn_last_4: Option<Secret<String>>, pub external_account_account_holder_type: Option<String>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutListConstraints { /// The identifier for customer #[schema(value_type = Option<String>, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// A cursor for use in pagination, fetch the next list after some object #[schema(example = "pay_fafa124123")] pub starting_after: Option<String>, /// A cursor for use in pagination, fetch the previous list before some object #[schema(example = "pay_fafa124123")] pub ending_before: Option<String>, /// limit on the number of objects to return #[schema(default = 10, maximum = 100)] #[serde(default = "default_payouts_list_limit")] pub limit: u32, /// The time at which payout is created #[schema(example = "2022-09-10T10:11:12Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<PrimitiveDateTime>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] pub time_range: Option<common_utils::types::TimeRange>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] #[serde(deny_unknown_fields)] pub struct PayoutListFilterConstraints { /// The identifier for payout #[schema( value_type = Option<String>, min_length = 30, max_length = 30, example = "187282ab-40ef-47a9-9206-5099ba31e432" )] pub payout_id: Option<String>, /// The identifier for business profile #[schema(value_type = Option<String>)] pub profile_id: Option<id_type::ProfileId>, /// The identifier for customer #[schema(value_type = Option<String>,example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The limit on the number of objects. The default limit is 10 and max limit is 20 #[serde(default = "default_payouts_list_limit")] pub limit: u32, /// The starting point within a list of objects pub offset: Option<u32>, /// The time range for which objects are needed. TimeRange has two fields start_time and end_time from which objects can be filtered as per required scenarios (created_at, time less than, greater than etc). #[serde(flatten)] #[schema(value_type = Option<TimeRange>)] pub time_range: Option<common_utils::types::TimeRange>, /// The list of connectors to filter payouts list #[schema(value_type = Option<Vec<PayoutConnectors>>, max_length = 255, example = json!(["wise", "adyen"]))] pub connector: Option<Vec<api_enums::PayoutConnectors>>, /// The list of currencies to filter payouts list #[schema(value_type = Currency, example = "USD")] pub currency: Option<Vec<api_enums::Currency>>, /// The list of payout status to filter payouts list #[schema(value_type = Option<Vec<PayoutStatus>>, example = json!(["pending", "failed"]))] pub status: Option<Vec<api_enums::PayoutStatus>>, /// The list of payout methods to filter payouts list #[schema(value_type = Option<Vec<PayoutType>>, example = json!(["bank", "card"]))] pub payout_method: Option<Vec<common_enums::PayoutType>>, /// Type of recipient #[schema(value_type = PayoutEntityType, example = "Individual")] pub entity_type: Option<common_enums::PayoutEntityType>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutListResponse { /// The number of payouts included in the list pub size: usize, /// The list of payouts response objects pub data: Vec<PayoutCreateResponse>, /// The total number of available payouts for given constraints #[serde(skip_serializing_if = "Option::is_none")] pub total_count: Option<i64>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutListFilters { /// The list of available connector filters #[schema(value_type = Vec<PayoutConnectors>)] pub connector: Vec<api_enums::PayoutConnectors>, /// The list of available currency filters #[schema(value_type = Vec<Currency>)] pub currency: Vec<common_enums::Currency>, /// The list of available payout status filters #[schema(value_type = Vec<PayoutStatus>)] pub status: Vec<common_enums::PayoutStatus>, /// The list of available payout method filters #[schema(value_type = Vec<PayoutType>)] pub payout_method: Vec<common_enums::PayoutType>, } #[derive(Clone, Debug, serde::Serialize, ToSchema)] pub struct PayoutLinkResponse { pub payout_link_id: String, #[schema(value_type = String)] pub link: Secret<url::Url>, } #[derive(Clone, Debug, serde::Deserialize, ToSchema, serde::Serialize)] pub struct PayoutLinkInitiateRequest { #[schema(value_type = String)] pub merchant_id: id_type::MerchantId, pub payout_id: String, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutLinkDetails { pub publishable_key: Secret<String>, pub client_secret: Secret<String>, pub payout_link_id: String, pub payout_id: String, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub return_url: Option<url::Url>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub enabled_payment_methods: Vec<link_utils::EnabledPaymentMethod>, pub enabled_payment_methods_with_required_fields: Vec<PayoutEnabledPaymentMethodsInfo>, pub amount: common_utils::types::StringMajorUnit, pub currency: common_enums::Currency, pub locale: String, pub form_layout: Option<common_enums::UIWidgetFormLayout>, pub test_mode: bool, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutEnabledPaymentMethodsInfo { pub payment_method: common_enums::PaymentMethod, pub payment_method_types_info: Vec<PaymentMethodTypeInfo>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentMethodTypeInfo { pub payment_method_type: common_enums::PaymentMethodType, pub required_fields: Option<HashMap<String, RequiredFieldInfo>>, } #[derive(Clone, Debug, serde::Serialize, FlatStruct)] pub struct RequiredFieldsOverrideRequest { pub billing: Option<payments::Address>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PayoutLinkStatusDetails { pub payout_link_id: String, pub payout_id: String, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: PrimitiveDateTime, pub return_url: Option<url::Url>, pub status: api_enums::PayoutStatus, pub error_code: Option<UnifiedCode>, pub error_message: Option<UnifiedMessage>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub test_mode: bool, } impl From<Bank> for payout_method_utils::BankAdditionalData { fn from(bank_data: Bank) -> Self { match bank_data { Bank::Ach(AchBankTransfer { bank_name, bank_country_code, bank_city, bank_account_number, bank_routing_number, }) => Self::Ach(Box::new( payout_method_utils::AchBankTransferAdditionalData { bank_name, bank_country_code, bank_city, bank_account_number: bank_account_number.into(), bank_routing_number: bank_routing_number.into(), }, )), Bank::Bacs(BacsBankTransfer { bank_name, bank_country_code, bank_city, bank_account_number, bank_sort_code, }) => Self::Bacs(Box::new( payout_method_utils::BacsBankTransferAdditionalData { bank_name, bank_country_code, bank_city, bank_account_number: bank_account_number.into(), bank_sort_code: bank_sort_code.into(), }, )), Bank::Sepa(SepaBankTransfer { bank_name, bank_country_code, bank_city, iban, bic, }) => Self::Sepa(Box::new( payout_method_utils::SepaBankTransferAdditionalData { bank_name, bank_country_code, bank_city, iban: iban.into(), bic: bic.map(From::from), }, )), Bank::Pix(PixBankTransfer { bank_name, bank_branch, bank_account_number, pix_key, tax_id, }) => Self::Pix(Box::new( payout_method_utils::PixBankTransferAdditionalData { bank_name, bank_branch, bank_account_number: bank_account_number.into(), pix_key: pix_key.into(), tax_id: tax_id.map(From::from), }, )), } } } impl From<Wallet> for payout_method_utils::WalletAdditionalData { fn from(wallet_data: Wallet) -> Self { match wallet_data { Wallet::Paypal(Paypal { email, telephone_number, paypal_id, }) => Self::Paypal(Box::new(payout_method_utils::PaypalAdditionalData { email: email.map(ForeignFrom::foreign_from), telephone_number: telephone_number.map(From::from), paypal_id: paypal_id.map(From::from), })), Wallet::Venmo(Venmo { telephone_number }) => { Self::Venmo(Box::new(payout_method_utils::VenmoAdditionalData { telephone_number: telephone_number.map(From::from), })) } } } } impl From<payout_method_utils::AdditionalPayoutMethodData> for PayoutMethodDataResponse { fn from(additional_data: payout_method_utils::AdditionalPayoutMethodData) -> Self { match additional_data { payout_method_utils::AdditionalPayoutMethodData::Card(card_data) => { Self::Card(card_data) } payout_method_utils::AdditionalPayoutMethodData::Bank(bank_data) => { Self::Bank(bank_data) } payout_method_utils::AdditionalPayoutMethodData::Wallet(wallet_data) => { Self::Wallet(wallet_data) } } } }
10,210
1,971
hyperswitch
crates/api_models/src/errors.rs
.rs
pub mod actix; pub mod types;
9
1,972
hyperswitch
crates/api_models/src/user_role.rs
.rs
use common_enums::{ParentGroup, PermissionGroup}; use common_utils::pii; use masking::Secret; pub mod role; #[derive(Debug, serde::Serialize)] pub struct AuthorizationInfoResponse(pub Vec<AuthorizationInfo>); #[derive(Debug, serde::Serialize)] #[serde(untagged)] pub enum AuthorizationInfo { Group(GroupInfo), GroupWithTag(ParentInfo), } // TODO: To be deprecated #[derive(Debug, serde::Serialize)] pub struct GroupInfo { pub group: PermissionGroup, pub description: &'static str, } #[derive(Debug, serde::Serialize, Clone)] pub struct ParentInfo { pub name: ParentGroup, pub description: &'static str, pub groups: Vec<PermissionGroup>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UpdateUserRoleRequest { pub email: pii::Email, pub role_id: String, } #[derive(Debug, serde::Serialize)] pub enum UserStatus { Active, InvitationSent, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct DeleteUserRoleRequest { pub email: pii::Email, } #[derive(Debug, serde::Serialize)] pub struct ListUsersInEntityResponse { pub email: pii::Email, pub roles: Vec<role::MinimalRoleInfo>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ListInvitationForUserResponse { pub entity_id: String, pub entity_type: common_enums::EntityType, pub entity_name: Option<Secret<String>>, pub role_id: String, } pub type AcceptInvitationsV2Request = Vec<Entity>; pub type AcceptInvitationsPreAuthRequest = Vec<Entity>; #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct Entity { pub entity_id: String, pub entity_type: common_enums::EntityType, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ListUsersInEntityRequest { pub entity_type: Option<common_enums::EntityType>, }
423
1,973
hyperswitch
crates/api_models/src/feature_matrix.rs
.rs
use std::collections::HashSet; use serde::{Deserialize, Serialize}; use utoipa::ToSchema; #[derive(Default, Debug, Deserialize, Serialize, Clone, ToSchema)] pub struct FeatureMatrixRequest { // List of connectors for which the feature matrix is requested #[schema(value_type = Option<Vec<Connector>>)] pub connectors: Option<Vec<common_enums::connector_enums::Connector>>, } #[derive(Debug, Clone, ToSchema, Serialize)] pub struct CardSpecificFeatures { /// Indicates whether three_ds card payments are supported #[schema(value_type = FeatureStatus)] pub three_ds: common_enums::FeatureStatus, /// Indicates whether non three_ds card payments are supported #[schema(value_type = FeatureStatus)] pub no_three_ds: common_enums::FeatureStatus, /// List of supported card networks #[schema(value_type = Vec<CardNetwork>)] pub supported_card_networks: Vec<common_enums::CardNetwork>, } #[derive(Debug, Clone, ToSchema, Serialize)] #[serde(untagged)] pub enum PaymentMethodSpecificFeatures { /// Card specific features Card(CardSpecificFeatures), } #[derive(Debug, ToSchema, Serialize)] pub struct SupportedPaymentMethod { /// The payment method supported by the connector #[schema(value_type = PaymentMethod)] pub payment_method: common_enums::PaymentMethod, /// The payment method type supported by the connector #[schema(value_type = PaymentMethodType)] pub payment_method_type: common_enums::PaymentMethodType, /// The display name of the payment method type pub payment_method_type_display_name: String, /// Indicates whether the payment method supports mandates via the connector #[schema(value_type = FeatureStatus)] pub mandates: common_enums::FeatureStatus, /// Indicates whether the payment method supports refunds via the connector #[schema(value_type = FeatureStatus)] pub refunds: common_enums::FeatureStatus, /// List of supported capture methods supported by the payment method type #[schema(value_type = Vec<CaptureMethod>)] pub supported_capture_methods: Vec<common_enums::CaptureMethod>, /// Information on the Payment method specific payment features #[serde(flatten)] pub payment_method_specific_features: Option<PaymentMethodSpecificFeatures>, /// List of countries supported by the payment method type via the connector #[schema(value_type = Option<HashSet<CountryAlpha3>>)] pub supported_countries: Option<HashSet<common_enums::CountryAlpha3>>, /// List of currencies supported by the payment method type via the connector #[schema(value_type = Option<HashSet<Currency>>)] pub supported_currencies: Option<HashSet<common_enums::Currency>>, } #[derive(Debug, ToSchema, Serialize)] pub struct ConnectorFeatureMatrixResponse { /// The name of the connector pub name: String, /// The display name of the connector pub display_name: Option<String>, /// The description of the connector pub description: Option<String>, /// The category of the connector #[schema(value_type = Option<PaymentConnectorCategory>, example = "payment_gateway")] pub category: Option<common_enums::PaymentConnectorCategory>, /// The list of payment methods supported by the connector pub supported_payment_methods: Vec<SupportedPaymentMethod>, /// The list of webhook flows supported by the connector #[schema(value_type = Option<Vec<EventClass>>)] pub supported_webhook_flows: Option<Vec<common_enums::EventClass>>, } #[derive(Debug, Serialize, ToSchema)] pub struct FeatureMatrixListResponse { /// The number of connectors included in the response pub connector_count: usize, // The list of payments response objects pub connectors: Vec<ConnectorFeatureMatrixResponse>, } impl common_utils::events::ApiEventMetric for FeatureMatrixListResponse {} impl common_utils::events::ApiEventMetric for FeatureMatrixRequest {}
827
1,974
hyperswitch
crates/api_models/src/connector_enums.rs
.rs
pub use common_enums::connector_enums::Connector;
12
1,975
hyperswitch
crates/api_models/src/events.rs
.rs
pub mod apple_pay_certificates_migration; pub mod connector_onboarding; pub mod customer; pub mod dispute; pub mod external_service_auth; pub mod gsm; mod locker_migration; pub mod payment; #[cfg(feature = "payouts")] pub mod payouts; #[cfg(feature = "recon")] pub mod recon; pub mod refund; #[cfg(feature = "v2")] pub mod revenue_recovery; pub mod routing; pub mod user; pub mod user_role; use common_utils::{ events::{ApiEventMetric, ApiEventsType}, impl_api_event_type, }; use crate::customers::CustomerListRequest; #[allow(unused_imports)] use crate::{ admin::*, analytics::{ api_event::*, auth_events::*, connector_events::ConnectorEventsRequest, outgoing_webhook_event::OutgoingWebhookLogsRequest, sdk_events::*, search::*, *, }, api_keys::*, cards_info::*, disputes::*, files::*, mandates::*, organization::{ OrganizationCreateRequest, OrganizationId, OrganizationResponse, OrganizationUpdateRequest, }, payment_methods::*, payments::*, user::{UserKeyTransferRequest, UserTransferKeyResponse}, verifications::*, }; impl ApiEventMetric for GetPaymentIntentFiltersRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Analytics) } } impl ApiEventMetric for GetPaymentIntentMetricRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Analytics) } } impl ApiEventMetric for PaymentIntentFiltersResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Analytics) } } impl_api_event_type!( Miscellaneous, ( PaymentMethodId, PaymentMethodCreate, PaymentLinkInitiateRequest, RetrievePaymentLinkResponse, MandateListConstraints, CreateFileResponse, MerchantConnectorResponse, MerchantConnectorId, MandateResponse, MandateRevokedResponse, RetrievePaymentLinkRequest, PaymentLinkListConstraints, MandateId, DisputeListGetConstraints, RetrieveApiKeyResponse, ProfileResponse, ProfileUpdate, ProfileCreate, RevokeApiKeyResponse, ToggleKVResponse, ToggleKVRequest, ToggleAllKVRequest, ToggleAllKVResponse, MerchantAccountDeleteResponse, MerchantAccountUpdate, CardInfoResponse, CreateApiKeyResponse, CreateApiKeyRequest, ListApiKeyConstraints, MerchantConnectorDeleteResponse, MerchantConnectorUpdate, MerchantConnectorCreate, MerchantId, CardsInfoRequest, MerchantAccountResponse, MerchantAccountListRequest, MerchantAccountCreate, PaymentsSessionRequest, ApplepayMerchantVerificationRequest, ApplepayMerchantResponse, ApplepayVerifiedDomainsResponse, UpdateApiKeyRequest, GetApiEventFiltersRequest, ApiEventFiltersResponse, GetInfoResponse, GetPaymentMetricRequest, GetRefundMetricRequest, GetActivePaymentsMetricRequest, GetSdkEventMetricRequest, GetAuthEventMetricRequest, GetAuthEventFilterRequest, GetPaymentFiltersRequest, PaymentFiltersResponse, GetRefundFilterRequest, RefundFiltersResponse, AuthEventFiltersResponse, GetSdkEventFiltersRequest, SdkEventFiltersResponse, ApiLogsRequest, GetApiEventMetricRequest, SdkEventsRequest, ReportRequest, ConnectorEventsRequest, OutgoingWebhookLogsRequest, GetGlobalSearchRequest, GetSearchRequest, GetSearchResponse, GetSearchRequestWithIndex, GetDisputeFilterRequest, DisputeFiltersResponse, GetDisputeMetricRequest, SankeyResponse, OrganizationResponse, OrganizationCreateRequest, OrganizationUpdateRequest, OrganizationId, CustomerListRequest ) ); impl_api_event_type!( Keymanager, ( TransferKeyResponse, MerchantKeyTransferRequest, UserKeyTransferRequest, UserTransferKeyResponse ) ); impl<T> ApiEventMetric for MetricsResponse<T> { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Miscellaneous) } } impl<T> ApiEventMetric for PaymentsMetricsResponse<T> { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Miscellaneous) } } impl<T> ApiEventMetric for PaymentIntentsMetricsResponse<T> { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Miscellaneous) } } impl<T> ApiEventMetric for RefundsMetricsResponse<T> { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Miscellaneous) } } impl<T> ApiEventMetric for DisputesMetricsResponse<T> { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Miscellaneous) } } impl<T> ApiEventMetric for AuthEventMetricsResponse<T> { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Miscellaneous) } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl ApiEventMetric for PaymentMethodIntentConfirmInternal { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.id.clone(), payment_method_type: Some(self.request.payment_method_type), payment_method_subtype: Some(self.request.payment_method_subtype), }) } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl ApiEventMetric for PaymentMethodIntentCreate { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethodCreate) } } impl ApiEventMetric for DisputeListFilters { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentMethodSessionRequest {} #[cfg(feature = "v2")] impl ApiEventMetric for PaymentMethodsSessionUpdateRequest {} #[cfg(feature = "v2")] impl ApiEventMetric for PaymentMethodSessionResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethodSession { payment_method_session_id: self.id.clone(), }) } }
1,400
1,976
hyperswitch
crates/api_models/src/payment_methods.rs
.rs
use std::collections::{HashMap, HashSet}; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use std::str::FromStr; use cards::CardNumber; use common_utils::{ consts::SURCHARGE_PERCENTAGE_PRECISION_LENGTH, crypto::OptionalEncryptableName, errors, ext_traits::OptionExt, id_type, link_utils, pii, types::{MinorUnit, Percentage, Surcharge}, }; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use masking::PeekInterface; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use masking::{ExposeInterface, PeekInterface}; use serde::de; use utoipa::{schema, ToSchema}; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] use crate::customers; #[cfg(feature = "payouts")] use crate::payouts; use crate::{ admin, enums as api_enums, payments::{self, BankCodeResponse}, }; #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodCreate { /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>,example = "credit")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The name of the bank/ provider issuing the payment method to the end user #[schema(example = "Citibank")] pub payment_method_issuer: Option<String>, /// A standard code representing the issuer of payment method #[schema(value_type = Option<PaymentMethodIssuerCode>,example = "jp_applepay")] pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, /// Card Details #[schema(example = json!({ "card_number": "4111111145551142", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "John Doe"}))] pub card: Option<CardDetail>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The unique identifier of the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The card network #[schema(example = "Visa")] pub card_network: Option<String>, /// Payment method details from locker #[cfg(feature = "payouts")] #[schema(value_type = Option<Bank>)] pub bank_transfer: Option<payouts::Bank>, /// Payment method details from locker #[cfg(feature = "payouts")] #[schema(value_type = Option<Wallet>)] pub wallet: Option<payouts::Wallet>, /// For Client based calls, SDK will use the client_secret /// in order to call /payment_methods /// Client secret will be generated whenever a new /// payment method is created pub client_secret: Option<String>, /// Payment method data to be passed in case of client /// based flow pub payment_method_data: Option<PaymentMethodCreateData>, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, #[serde(skip_deserializing)] /// The connector mandate details of the payment method, this is added only for cards migration /// api and is skipped during deserialization of the payment method create request as this /// it should not be passed in the request pub connector_mandate_details: Option<PaymentsMandateReference>, #[serde(skip_deserializing)] /// The transaction id of a CIT (customer initiated transaction) associated with the payment method, /// this is added only for cards migration api and is skipped during deserialization of the /// payment method create request as it should not be passed in the request pub network_transaction_id: Option<String>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodCreate { /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = PaymentMethodType,example = "google_pay")] pub payment_method_subtype: api_enums::PaymentMethodType, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, /// Payment method data to be passed pub payment_method_data: PaymentMethodCreateData, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// The tokenization type to be applied #[schema(value_type = Option<PspTokenization>)] pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, /// The network tokenization configuration if applicable #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodIntentCreate { /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodIntentConfirm { /// The unique identifier of the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// Payment method data to be passed pub payment_method_data: PaymentMethodCreateData, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = PaymentMethodType,example = "credit")] pub payment_method_subtype: api_enums::PaymentMethodType, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl PaymentMethodIntentConfirm { pub fn validate_payment_method_data_against_payment_method( payment_method_type: api_enums::PaymentMethod, payment_method_data: PaymentMethodCreateData, ) -> bool { match payment_method_type { api_enums::PaymentMethod::Card => { matches!(payment_method_data, PaymentMethodCreateData::Card(_)) } _ => false, } } } /// This struct is used internally only #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct PaymentMethodIntentConfirmInternal { pub id: id_type::GlobalPaymentMethodId, pub request: PaymentMethodIntentConfirm, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl From<PaymentMethodIntentConfirmInternal> for PaymentMethodIntentConfirm { fn from(item: PaymentMethodIntentConfirmInternal) -> Self { item.request } } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] /// This struct is only used by and internal api to migrate payment method pub struct PaymentMethodMigrate { /// Merchant id pub merchant_id: id_type::MerchantId, /// The type of payment method use for the payment. pub payment_method: Option<api_enums::PaymentMethod>, /// This is a sub-category of payment method. pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The name of the bank/ provider issuing the payment method to the end user pub payment_method_issuer: Option<String>, /// A standard code representing the issuer of payment method pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, /// Card Details pub card: Option<MigrateCardDetail>, /// Network token details pub network_token: Option<MigrateNetworkTokenDetail>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. pub metadata: Option<pii::SecretSerdeValue>, /// The unique identifier of the customer. pub customer_id: Option<id_type::CustomerId>, /// The card network pub card_network: Option<String>, /// Payment method details from locker #[cfg(feature = "payouts")] pub bank_transfer: Option<payouts::Bank>, /// Payment method details from locker #[cfg(feature = "payouts")] pub wallet: Option<payouts::Wallet>, /// Payment method data to be passed in case of client /// based flow pub payment_method_data: Option<PaymentMethodCreateData>, /// The billing details of the payment method pub billing: Option<payments::Address>, /// The connector mandate details of the payment method #[serde(deserialize_with = "deserialize_connector_mandate_details")] pub connector_mandate_details: Option<CommonMandateReference>, // The CIT (customer initiated transaction) transaction id associated with the payment method pub network_transaction_id: Option<String>, } #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodMigrateResponse { //payment method response when payment method entry is created pub payment_method_response: PaymentMethodResponse, //card data migration status pub card_migrated: Option<bool>, //network token data migration status pub network_token_migrated: Option<bool>, //connector mandate details migration status pub connector_mandate_details_migrated: Option<bool>, //network transaction id migration status pub network_transaction_id_migrated: Option<bool>, } #[derive(Debug, Default, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentsMandateReference( pub HashMap<id_type::MerchantConnectorAccountId, PaymentsMandateReferenceRecord>, ); #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PayoutsMandateReference( pub HashMap<id_type::MerchantConnectorAccountId, PayoutsMandateReferenceRecord>, ); #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PayoutsMandateReferenceRecord { pub transfer_method_id: Option<String>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PaymentsMandateReferenceRecord { pub connector_mandate_id: String, pub payment_method_type: Option<common_enums::PaymentMethodType>, pub original_payment_authorized_amount: Option<i64>, pub original_payment_authorized_currency: Option<common_enums::Currency>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct CommonMandateReference { pub payments: Option<PaymentsMandateReference>, pub payouts: Option<PayoutsMandateReference>, } impl From<CommonMandateReference> for PaymentsMandateReference { fn from(common_mandate: CommonMandateReference) -> Self { common_mandate.payments.unwrap_or_default() } } impl From<PaymentsMandateReference> for CommonMandateReference { fn from(payments_reference: PaymentsMandateReference) -> Self { Self { payments: Some(payments_reference), payouts: None, } } } fn deserialize_connector_mandate_details<'de, D>( deserializer: D, ) -> Result<Option<CommonMandateReference>, D::Error> where D: serde::Deserializer<'de>, { let value: Option<serde_json::Value> = <Option<serde_json::Value> as de::Deserialize>::deserialize(deserializer)?; let payments_data = value .clone() .map(|mut mandate_details| { mandate_details .as_object_mut() .map(|obj| obj.remove("payouts")); serde_json::from_value::<PaymentsMandateReference>(mandate_details) }) .transpose() .map_err(|err| { let err_msg = format!("{err:?}"); de::Error::custom(format_args!( "Failed to deserialize PaymentsMandateReference `{}`", err_msg )) })?; let payouts_data = value .clone() .map(|mandate_details| { serde_json::from_value::<Option<CommonMandateReference>>(mandate_details).map( |optional_common_mandate_details| { optional_common_mandate_details .and_then(|common_mandate_details| common_mandate_details.payouts) }, ) }) .transpose() .map_err(|err| { let err_msg = format!("{err:?}"); de::Error::custom(format_args!( "Failed to deserialize CommonMandateReference `{}`", err_msg )) })? .flatten(); Ok(Some(CommonMandateReference { payments: payments_data, payouts: payouts_data, })) } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] impl PaymentMethodCreate { pub fn get_payment_method_create_from_payment_method_migrate( card_number: CardNumber, payment_method_migrate: &PaymentMethodMigrate, ) -> Self { let card_details = payment_method_migrate .card .as_ref() .map(|payment_method_migrate_card| CardDetail { card_number, card_exp_month: payment_method_migrate_card.card_exp_month.clone(), card_exp_year: payment_method_migrate_card.card_exp_year.clone(), card_holder_name: payment_method_migrate_card.card_holder_name.clone(), nick_name: payment_method_migrate_card.nick_name.clone(), card_issuing_country: payment_method_migrate_card.card_issuing_country.clone(), card_network: payment_method_migrate_card.card_network.clone(), card_issuer: payment_method_migrate_card.card_issuer.clone(), card_type: payment_method_migrate_card.card_type.clone(), }); Self { customer_id: payment_method_migrate.customer_id.clone(), payment_method: payment_method_migrate.payment_method, payment_method_type: payment_method_migrate.payment_method_type, payment_method_issuer: payment_method_migrate.payment_method_issuer.clone(), payment_method_issuer_code: payment_method_migrate.payment_method_issuer_code, metadata: payment_method_migrate.metadata.clone(), payment_method_data: payment_method_migrate.payment_method_data.clone(), connector_mandate_details: payment_method_migrate .connector_mandate_details .clone() .map(|common_mandate_reference| { PaymentsMandateReference::from(common_mandate_reference) }), client_secret: None, billing: payment_method_migrate.billing.clone(), card: card_details, card_network: payment_method_migrate.card_network.clone(), #[cfg(feature = "payouts")] bank_transfer: payment_method_migrate.bank_transfer.clone(), #[cfg(feature = "payouts")] wallet: payment_method_migrate.wallet.clone(), network_transaction_id: payment_method_migrate.network_transaction_id.clone(), } } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl PaymentMethodCreate { pub fn validate_payment_method_data_against_payment_method( payment_method_type: api_enums::PaymentMethod, payment_method_data: PaymentMethodCreateData, ) -> bool { match payment_method_type { api_enums::PaymentMethod::Card => { matches!(payment_method_data, PaymentMethodCreateData::Card(_)) } _ => false, } } pub fn get_tokenize_connector_id( &self, ) -> Result<id_type::MerchantConnectorAccountId, error_stack::Report<errors::ValidationError>> { self.psp_tokenization .clone() .get_required_value("psp_tokenization") .map(|psp| psp.connector_id) } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodUpdate { /// Card Details #[schema(example = json!({ "card_number": "4111111145551142", "card_exp_month": "10", "card_exp_year": "25", "card_holder_name": "John Doe"}))] pub card: Option<CardDetailUpdate>, /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")] pub client_secret: Option<String>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodUpdate { /// Payment method details to be updated for the payment_method pub payment_method_data: Option<PaymentMethodUpdateData>, /// The connector token details to be updated for the payment_method pub connector_token_details: Option<ConnectorTokenDetails>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde(rename_all = "snake_case")] #[serde(rename = "payment_method_data")] pub enum PaymentMethodUpdateData { Card(CardDetailUpdate), } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde(rename_all = "snake_case")] #[serde(rename = "payment_method_data")] pub enum PaymentMethodCreateData { Card(CardDetail), } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde(rename_all = "snake_case")] #[serde(rename = "payment_method_data")] pub enum PaymentMethodCreateData { Card(CardDetail), } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CardDetail { /// Card Number #[schema(value_type = String,example = "4111111145551142")] pub card_number: CardNumber, /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: masking::Secret<String>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country pub card_issuing_country: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<String>, } #[derive( Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema, strum::EnumString, strum::Display, Eq, PartialEq, )] #[serde(rename_all = "snake_case")] pub enum CardType { Credit, Debit, } // We cannot use the card struct that we have for payments for the following reason // The card struct used for payments has card_cvc as mandatory // but when vaulting the card, we do not need cvc to be collected from the user // This is because, the vaulted payment method can be used for future transactions in the presence of the customer // when the customer is on_session again, the cvc can be collected from the customer #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CardDetail { /// Card Number #[schema(value_type = String,example = "4111111145551142")] pub card_number: CardNumber, /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: masking::Secret<String>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country #[schema(value_type = CountryAlpha2)] pub card_issuing_country: Option<api_enums::CountryAlpha2>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<CardType>, /// The CVC number for the card /// This is optional in case the card needs to be vaulted #[schema(value_type = String, example = "242")] pub card_cvc: Option<masking::Secret<String>>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MigrateCardDetail { /// Card Number #[schema(value_type = String,example = "4111111145551142")] pub card_number: masking::Secret<String>, /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: masking::Secret<String>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country pub card_issuing_country: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MigrateNetworkTokenData { /// Network Token Number #[schema(value_type = String,example = "4111111145551142")] pub network_token_number: CardNumber, /// Network Token Expiry Month #[schema(value_type = String,example = "10")] pub network_token_exp_month: masking::Secret<String>, /// Network Token Expiry Year #[schema(value_type = String,example = "25")] pub network_token_exp_year: masking::Secret<String>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country pub card_issuing_country: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct MigrateNetworkTokenDetail { /// Network token details pub network_token_data: MigrateNetworkTokenData, /// Network token requestor reference id pub network_token_requestor_ref_id: String, } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CardDetailUpdate { /// Card Expiry Month #[schema(value_type = String,example = "10")] pub card_exp_month: Option<masking::Secret<String>>, /// Card Expiry Year #[schema(value_type = String,example = "25")] pub card_exp_year: Option<masking::Secret<String>>, /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] impl CardDetailUpdate { pub fn apply(&self, card_data_from_locker: Card) -> CardDetail { CardDetail { card_number: card_data_from_locker.card_number, card_exp_month: self .card_exp_month .clone() .unwrap_or(card_data_from_locker.card_exp_month), card_exp_year: self .card_exp_year .clone() .unwrap_or(card_data_from_locker.card_exp_year), card_holder_name: self .card_holder_name .clone() .or(card_data_from_locker.name_on_card), nick_name: self .nick_name .clone() .or(card_data_from_locker.nick_name.map(masking::Secret::new)), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, } } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] pub struct CardDetailUpdate { /// Card Holder Name #[schema(value_type = String,example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>,example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl CardDetailUpdate { pub fn apply(&self, card_data_from_locker: Card) -> CardDetail { CardDetail { card_number: card_data_from_locker.card_number, card_exp_month: card_data_from_locker.card_exp_month, card_exp_year: card_data_from_locker.card_exp_year, card_holder_name: self .card_holder_name .clone() .or(card_data_from_locker.name_on_card), nick_name: self .nick_name .clone() .or(card_data_from_locker.nick_name.map(masking::Secret::new)), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, card_cvc: None, } } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] #[serde(deny_unknown_fields)] #[serde(rename_all = "snake_case")] #[serde(rename = "payment_method_data")] pub enum PaymentMethodResponseData { Card(CardDetailFromLocker), } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodResponse { /// Unique identifier for a merchant #[schema(example = "merchant_1671528864", value_type = String)] pub merchant_id: id_type::MerchantId, /// The unique identifier of the customer. #[schema(value_type = Option<String>, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: Option<id_type::CustomerId>, /// The unique identifier of the Payment method #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")] pub payment_method_id: String, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod, example = "card")] pub payment_method: Option<api_enums::PaymentMethod>, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>, example = "credit")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// Card details from card locker #[schema(example = json!({"last4": "1142","exp_month": "03","exp_year": "2030"}))] pub card: Option<CardDetailFromLocker>, /// Indicates whether the payment method is eligible for recurring payments #[schema(example = true)] pub recurring_enabled: bool, /// Indicates whether the payment method is eligible for installment payments #[schema(example = true)] pub installment_payment_enabled: bool, /// Type of payment experience enabled with the connector #[schema(value_type = Option<Vec<PaymentExperience>>, example = json!(["redirect_to_url"]))] pub payment_experience: Option<Vec<api_enums::PaymentExperience>>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = Option<PrimitiveDateTime>, example = "2023-01-18T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<time::PrimitiveDateTime>, /// Payment method details from locker #[cfg(feature = "payouts")] #[schema(value_type = Option<Bank>)] #[serde(skip_serializing_if = "Option::is_none")] pub bank_transfer: Option<payouts::Bank>, #[schema(value_type = Option<PrimitiveDateTime>, example = "2024-02-24T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_used_at: Option<time::PrimitiveDateTime>, /// For Client based calls pub client_secret: Option<String>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema, Clone)] pub struct ConnectorTokenDetails { /// The unique identifier of the connector account through which the token was generated #[schema(value_type = String, example = "mca_")] pub connector_id: id_type::MerchantConnectorAccountId, #[schema(value_type = TokenizationType)] pub token_type: common_enums::TokenizationType, /// The status of connector token if it is active or inactive #[schema(value_type = ConnectorTokenStatus)] pub status: common_enums::ConnectorTokenStatus, /// The reference id of the connector token /// This is the reference that was passed to connector when creating the token pub connector_token_request_reference_id: Option<String>, pub original_payment_authorized_amount: Option<MinorUnit>, /// The currency of the original payment authorized amount #[schema(value_type = Currency)] pub original_payment_authorized_currency: Option<common_enums::Currency>, /// Metadata associated with the connector token pub metadata: Option<pii::SecretSerdeValue>, /// The value of the connector token. This token can be used to make merchant initiated payments ( MIT ), directly with the connector. pub token: masking::Secret<String>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema, Clone)] pub struct PaymentMethodResponse { /// The unique identifier of the Payment method #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodId, /// Unique identifier for a merchant #[schema(value_type = String, example = "merchant_1671528864")] pub merchant_id: id_type::MerchantId, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: Option<api_enums::PaymentMethod>, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>, example = "credit")] pub payment_method_subtype: Option<api_enums::PaymentMethodType>, /// Indicates whether the payment method is eligible for recurring payments #[schema(example = true)] pub recurring_enabled: bool, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = Option<PrimitiveDateTime>, example = "2023-01-18T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<time::PrimitiveDateTime>, /// A timestamp (ISO 8601 code) that determines when the payment method was last used #[schema(value_type = Option<PrimitiveDateTime>, example = "2024-02-24T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_used_at: Option<time::PrimitiveDateTime>, /// The payment method details related to the payment method pub payment_method_data: Option<PaymentMethodResponseData>, /// The connector token details if available pub connector_tokens: Option<Vec<ConnectorTokenDetails>>, pub network_token: Option<NetworkTokenResponse>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub enum PaymentMethodsData { Card(CardDetailsPaymentMethod), BankDetails(PaymentMethodDataBankCreds), WalletDetails(PaymentMethodDataWalletInfo), } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct CardDetailsPaymentMethod { pub last4_digits: Option<String>, pub issuer_country: Option<String>, pub expiry_month: Option<masking::Secret<String>>, pub expiry_year: Option<masking::Secret<String>>, pub nick_name: Option<masking::Secret<String>>, pub card_holder_name: Option<masking::Secret<String>>, pub card_isin: Option<String>, pub card_issuer: Option<String>, pub card_network: Option<api_enums::CardNetwork>, pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] pub saved_to_locker: bool, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct NetworkTokenDetailsPaymentMethod { pub last4_digits: Option<String>, pub issuer_country: Option<String>, #[schema(value_type = Option<String>)] pub network_token_expiry_month: Option<masking::Secret<String>>, #[schema(value_type = Option<String>)] pub network_token_expiry_year: Option<masking::Secret<String>>, #[schema(value_type = Option<String>)] pub nick_name: Option<masking::Secret<String>>, #[schema(value_type = Option<String>)] pub card_holder_name: Option<masking::Secret<String>>, pub card_isin: Option<String>, pub card_issuer: Option<String>, #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, pub card_type: Option<String>, #[serde(default = "saved_in_locker_default")] pub saved_to_locker: bool, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodDataBankCreds { pub mask: String, pub hash: String, pub account_type: Option<String>, pub account_name: Option<String>, pub payment_method_type: api_enums::PaymentMethodType, pub connector_details: Vec<BankAccountConnectorDetails>, } #[derive(Clone, Debug, Eq, PartialEq, serde::Deserialize, serde::Serialize)] pub struct PaymentMethodDataWalletInfo { /// Last 4 digits of the card number pub last4: String, /// The information of the payment method pub card_network: String, /// The type of payment method #[serde(rename = "type")] pub card_type: Option<String>, } impl From<payments::additional_info::WalletAdditionalDataForCard> for PaymentMethodDataWalletInfo { fn from(item: payments::additional_info::WalletAdditionalDataForCard) -> Self { Self { last4: item.last4, card_network: item.card_network, card_type: item.card_type, } } } impl From<PaymentMethodDataWalletInfo> for payments::additional_info::WalletAdditionalDataForCard { fn from(item: PaymentMethodDataWalletInfo) -> Self { Self { last4: item.last4, card_network: item.card_network, card_type: item.card_type, } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct BankAccountTokenData { pub payment_method_type: api_enums::PaymentMethodType, pub payment_method: api_enums::PaymentMethod, pub connector_details: BankAccountConnectorDetails, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub struct BankAccountConnectorDetails { pub connector: String, pub account_id: masking::Secret<String>, pub mca_id: id_type::MerchantConnectorAccountId, pub access_token: BankAccountAccessCreds, } #[derive(Debug, Clone, Eq, PartialEq, serde::Serialize, serde::Deserialize)] pub enum BankAccountAccessCreds { AccessToken(masking::Secret<String>), } #[derive(Debug, serde::Deserialize, serde::Serialize, Clone)] pub struct Card { pub card_number: CardNumber, pub name_on_card: Option<masking::Secret<String>>, pub card_exp_month: masking::Secret<String>, pub card_exp_year: masking::Secret<String>, pub card_brand: Option<String>, pub card_isin: Option<String>, pub nick_name: Option<String>, } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct CardDetailFromLocker { pub scheme: Option<String>, pub issuer_country: Option<String>, pub last4_digits: Option<String>, #[serde(skip)] #[schema(value_type=Option<String>)] pub card_number: Option<CardNumber>, #[schema(value_type=Option<String>)] pub expiry_month: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub expiry_year: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub card_token: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub card_holder_name: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub card_fingerprint: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub nick_name: Option<masking::Secret<String>>, #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, pub card_isin: Option<String>, pub card_issuer: Option<String>, pub card_type: Option<String>, pub saved_to_locker: bool, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct CardDetailFromLocker { #[schema(value_type = Option<CountryAlpha2>)] pub issuer_country: Option<api_enums::CountryAlpha2>, pub last4_digits: Option<String>, #[serde(skip)] #[schema(value_type=Option<String>)] pub card_number: Option<CardNumber>, #[schema(value_type=Option<String>)] pub expiry_month: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub expiry_year: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub card_holder_name: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub card_fingerprint: Option<masking::Secret<String>>, #[schema(value_type=Option<String>)] pub nick_name: Option<masking::Secret<String>>, #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, pub card_isin: Option<String>, pub card_issuer: Option<String>, pub card_type: Option<String>, pub saved_to_locker: bool, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, ToSchema)] pub struct NetworkTokenResponse { pub payment_method_data: NetworkTokenDetailsPaymentMethod, } fn saved_in_locker_default() -> bool { true } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] impl From<CardDetailFromLocker> for payments::AdditionalCardInfo { fn from(item: CardDetailFromLocker) -> Self { Self { card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, card_issuing_country: item.issuer_country, bank_code: None, last4: item.last4_digits, card_isin: item.card_isin, card_extended_bin: item .card_number .map(|card_number| card_number.get_extended_card_bin()), card_exp_month: item.expiry_month, card_exp_year: item.expiry_year, card_holder_name: item.card_holder_name, payment_checks: None, authentication_data: None, } } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl From<CardDetailFromLocker> for payments::AdditionalCardInfo { fn from(item: CardDetailFromLocker) -> Self { Self { card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, card_issuing_country: item.issuer_country.map(|country| country.to_string()), bank_code: None, last4: item.last4_digits, card_isin: item.card_isin, card_extended_bin: item .card_number .map(|card_number| card_number.get_extended_card_bin()), card_exp_month: item.expiry_month, card_exp_year: item.expiry_year, card_holder_name: item.card_holder_name, payment_checks: None, authentication_data: None, } } } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponse { /// The list of payment methods that are enabled for the business profile pub payment_methods_enabled: Vec<ResponsePaymentMethodTypes>, /// The list of saved payment methods of the customer pub customer_payment_methods: Vec<CustomerPaymentMethod>, } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { fn from(item: CardDetailsPaymentMethod) -> Self { Self { scheme: None, issuer_country: item.issuer_country, last4_digits: item.last4_digits, card_number: None, expiry_month: item.expiry_month, expiry_year: item.expiry_year, card_token: None, card_holder_name: item.card_holder_name, card_fingerprint: None, nick_name: item.nick_name, card_isin: item.card_isin, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, } } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl From<CardDetailsPaymentMethod> for CardDetailFromLocker { fn from(item: CardDetailsPaymentMethod) -> Self { Self { issuer_country: item .issuer_country .as_ref() .map(|c| api_enums::CountryAlpha2::from_str(c)) .transpose() .ok() .flatten(), last4_digits: item.last4_digits, card_number: None, expiry_month: item.expiry_month, expiry_year: item.expiry_year, card_holder_name: item.card_holder_name, card_fingerprint: None, nick_name: item.nick_name, card_isin: item.card_isin, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, } } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl From<CardDetail> for CardDetailFromLocker { fn from(item: CardDetail) -> Self { Self { issuer_country: item.card_issuing_country, last4_digits: Some(item.card_number.get_last4()), card_number: Some(item.card_number), expiry_month: Some(item.card_exp_month), expiry_year: Some(item.card_exp_year), card_holder_name: item.card_holder_name, nick_name: item.nick_name, card_isin: None, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, card_fingerprint: None, } } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl From<CardDetail> for CardDetailsPaymentMethod { fn from(item: CardDetail) -> Self { Self { issuer_country: item.card_issuing_country.map(|c| c.to_string()), last4_digits: Some(item.card_number.get_last4()), expiry_month: Some(item.card_exp_month), expiry_year: Some(item.card_exp_year), card_holder_name: item.card_holder_name, nick_name: item.nick_name, card_isin: None, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type.map(|card| card.to_string()), saved_to_locker: true, } } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { fn from(item: CardDetailFromLocker) -> Self { Self { issuer_country: item.issuer_country, last4_digits: item.last4_digits, expiry_month: item.expiry_month, expiry_year: item.expiry_year, nick_name: item.nick_name, card_holder_name: item.card_holder_name, card_isin: item.card_isin, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, } } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl From<CardDetailFromLocker> for CardDetailsPaymentMethod { fn from(item: CardDetailFromLocker) -> Self { Self { issuer_country: item.issuer_country.map(|country| country.to_string()), last4_digits: item.last4_digits, expiry_month: item.expiry_month, expiry_year: item.expiry_year, nick_name: item.nick_name, card_holder_name: item.card_holder_name, card_isin: item.card_isin, card_issuer: item.card_issuer, card_network: item.card_network, card_type: item.card_type, saved_to_locker: item.saved_to_locker, } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct PaymentExperienceTypes { /// The payment experience enabled #[schema(value_type = Option<PaymentExperience>, example = "redirect_to_url")] pub payment_experience_type: api_enums::PaymentExperience, /// The list of eligible connectors for a given payment experience #[schema(example = json!(["stripe", "adyen"]))] pub eligible_connectors: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct CardNetworkTypes { /// The card network enabled #[schema(value_type = Option<CardNetwork>, example = "Visa")] pub card_network: api_enums::CardNetwork, /// surcharge details for this card network pub surcharge_details: Option<SurchargeDetailsResponse>, /// The list of eligible connectors for a given card network #[schema(example = json!(["stripe", "adyen"]))] pub eligible_connectors: Vec<String>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankDebitTypes { pub eligible_connectors: Vec<String>, } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypes { /// The payment method type enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, /// The list of payment experiences enabled, if applicable for a payment method type pub payment_experience: Option<Vec<PaymentExperienceTypes>>, /// The list of card networks enabled, if applicable for a payment method type pub card_networks: Option<Vec<CardNetworkTypes>>, /// The list of banks enabled, if applicable for a payment method type pub bank_names: Option<Vec<BankCodeResponse>>, /// The Bank debit payment method information, if applicable for a payment method type. pub bank_debits: Option<BankDebitTypes>, /// The Bank transfer payment method information, if applicable for a payment method type. pub bank_transfers: Option<BankTransferTypes>, /// Required fields for the payment_method_type. pub required_fields: Option<HashMap<String, RequiredFieldInfo>>, /// surcharge details for this payment method type if exists pub surcharge_details: Option<SurchargeDetailsResponse>, /// auth service connector label for this payment method type, if exists pub pm_auth_connector: Option<String>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] #[serde(untagged)] // Untagged used for serialization only pub enum PaymentMethodSubtypeSpecificData { #[schema(title = "card")] Card { card_networks: Vec<CardNetworkTypes>, }, #[schema(title = "bank")] Bank { bank_names: Vec<BankCodeResponse> }, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema, PartialEq)] pub struct ResponsePaymentMethodTypes { /// The payment method type enabled #[schema(example = "pay_later", value_type = PaymentMethod)] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype enabled #[schema(example = "klarna", value_type = PaymentMethodType)] pub payment_method_subtype: common_enums::PaymentMethodType, /// payment method subtype specific information #[serde(flatten)] pub extra_information: Option<PaymentMethodSubtypeSpecificData>, /// Required fields for the payment_method_type. /// This is the union of all the required fields for the payment method type enabled in all the connectors. pub required_fields: Vec<RequiredFieldInfo>, } #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub struct SurchargeDetailsResponse { /// surcharge value pub surcharge: SurchargeResponse, /// tax on surcharge value pub tax_on_surcharge: Option<SurchargePercentage>, /// surcharge amount for this payment pub display_surcharge_amount: f64, /// tax on surcharge amount for this payment pub display_tax_on_surcharge_amount: f64, /// sum of display_surcharge_amount and display_tax_on_surcharge_amount pub display_total_surcharge_amount: f64, } #[derive(Clone, Debug, PartialEq, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type", content = "value")] pub enum SurchargeResponse { /// Fixed Surcharge value Fixed(MinorUnit), /// Surcharge percentage Rate(SurchargePercentage), } impl From<Surcharge> for SurchargeResponse { fn from(value: Surcharge) -> Self { match value { Surcharge::Fixed(amount) => Self::Fixed(amount), Surcharge::Rate(percentage) => Self::Rate(percentage.into()), } } } #[derive(Clone, Default, Debug, PartialEq, serde::Serialize, ToSchema)] pub struct SurchargePercentage { percentage: f32, } impl From<Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>> for SurchargePercentage { fn from(value: Percentage<SURCHARGE_PERCENTAGE_PRECISION_LENGTH>) -> Self { Self { percentage: value.get_percentage(), } } } /// Required fields info used while listing the payment_method_data #[derive(Debug, serde::Deserialize, serde::Serialize, Clone, PartialEq, Eq, ToSchema)] pub struct RequiredFieldInfo { /// Required field for a payment_method through a payment_method_type pub required_field: String, /// Display name of the required field in the front-end pub display_name: String, /// Possible field type of required field #[schema(value_type = FieldType)] pub field_type: api_enums::FieldType, #[schema(value_type = Option<String>)] pub value: Option<masking::Secret<String>>, } #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct ResponsePaymentMethodsEnabled { /// The payment method enabled #[schema(value_type = PaymentMethod)] pub payment_method: api_enums::PaymentMethod, /// The list of payment method types enabled for a connector account pub payment_method_types: Vec<ResponsePaymentMethodTypes>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq)] pub struct BankTransferTypes { /// The list of eligible connectors for a given payment experience #[schema(example = json!(["stripe", "adyen"]))] pub eligible_connectors: Vec<String>, } #[derive(Clone, Debug)] pub struct ResponsePaymentMethodIntermediate { pub payment_method_type: api_enums::PaymentMethodType, pub payment_experience: Option<api_enums::PaymentExperience>, pub card_networks: Option<Vec<api_enums::CardNetwork>>, pub payment_method: api_enums::PaymentMethod, pub connector: String, pub merchant_connector_id: String, } impl ResponsePaymentMethodIntermediate { pub fn new( pm_type: RequestPaymentMethodTypes, connector: String, merchant_connector_id: String, pm: api_enums::PaymentMethod, ) -> Self { Self { payment_method_type: pm_type.payment_method_type, payment_experience: pm_type.payment_experience, card_networks: pm_type.card_networks, payment_method: pm, connector, merchant_connector_id, } } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema, PartialEq, Eq, Hash)] pub struct RequestPaymentMethodTypes { #[schema(value_type = PaymentMethodType)] pub payment_method_type: api_enums::PaymentMethodType, #[schema(value_type = Option<PaymentExperience>)] pub payment_experience: Option<api_enums::PaymentExperience>, #[schema(value_type = Option<Vec<CardNetwork>>)] pub card_networks: Option<Vec<api_enums::CardNetwork>>, /// List of currencies accepted or has the processing capabilities of the processor #[schema(example = json!( { "type": "specific_accepted", "list": ["USD", "INR"] } ), value_type = Option<AcceptedCurrencies>)] pub accepted_currencies: Option<admin::AcceptedCurrencies>, /// List of Countries accepted or has the processing capabilities of the processor #[schema(example = json!( { "type": "specific_accepted", "list": ["UK", "AU"] } ), value_type = Option<AcceptedCountries>)] pub accepted_countries: Option<admin::AcceptedCountries>, /// Minimum amount supported by the processor. To be represented in the lowest denomination of the target currency (For example, for USD it should be in cents) #[schema(example = 1)] pub minimum_amount: Option<MinorUnit>, /// Maximum amount supported by the processor. To be represented in the lowest denomination of /// the target currency (For example, for USD it should be in cents) #[schema(example = 1313)] pub maximum_amount: Option<MinorUnit>, /// Boolean to enable recurring payments / mandates. Default is true. #[schema(default = true, example = false)] pub recurring_enabled: bool, /// Boolean to enable installment / EMI / BNPL payments. Default is true. #[schema(default = true, example = false)] pub installment_payment_enabled: bool, } impl RequestPaymentMethodTypes { /// Get payment_method_type #[cfg(feature = "v1")] pub fn get_payment_method_type(&self) -> Option<api_enums::PaymentMethodType> { Some(self.payment_method_type) } } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] //List Payment Method #[derive(Debug, Clone, serde::Serialize, Default, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodListRequest { /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")] pub client_secret: Option<String>, /// The two-letter ISO currency code #[schema(value_type = Option<Vec<CountryAlpha2>>, example = json!(["US", "UK", "IN"]))] pub accepted_countries: Option<Vec<api_enums::CountryAlpha2>>, /// The three-letter ISO currency code #[schema(value_type = Option<Vec<Currency>>,example = json!(["USD", "EUR"]))] pub accepted_currencies: Option<Vec<api_enums::Currency>>, /// Filter by amount #[schema(example = 60)] pub amount: Option<MinorUnit>, /// Indicates whether the payment method is eligible for recurring payments #[schema(example = true)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for installment payments #[schema(example = true)] pub installment_payment_enabled: Option<bool>, /// Indicates whether the payment method is eligible for card netwotks #[schema(value_type = Option<Vec<CardNetwork>>, example = json!(["visa", "mastercard"]))] pub card_networks: Option<Vec<api_enums::CardNetwork>>, /// Indicates the limit of last used payment methods #[schema(example = 1)] pub limit: Option<i64>, } #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] impl<'de> serde::Deserialize<'de> for PaymentMethodListRequest { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct FieldVisitor; impl<'de> de::Visitor<'de> for FieldVisitor { type Value = PaymentMethodListRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = PaymentMethodListRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "installment_payment_enabled" => { set_or_reject_duplicate( &mut output.installment_payment_enabled, "installment_payment_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } } deserializer.deserialize_identifier(FieldVisitor) } } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] //List Payment Method #[derive(Debug, Clone, serde::Serialize, Default, ToSchema)] #[serde(deny_unknown_fields)] pub struct PaymentMethodListRequest { /// This is a 15 minute expiry token which shall be used from the client to authenticate and perform sessions from the SDK #[schema(max_length = 30, min_length = 30, example = "secret_k2uj3he2893eiu2d")] pub client_secret: Option<String>, /// The two-letter ISO currency code #[schema(value_type = Option<Vec<CountryAlpha2>>, example = json!(["US", "UK", "IN"]))] pub accepted_countries: Option<Vec<api_enums::CountryAlpha2>>, /// Filter by amount #[schema(example = 60)] pub amount: Option<MinorUnit>, /// The three-letter ISO currency code #[schema(value_type = Option<Vec<Currency>>,example = json!(["USD", "EUR"]))] pub accepted_currencies: Option<Vec<api_enums::Currency>>, /// Indicates whether the payment method is eligible for recurring payments #[schema(example = true)] pub recurring_enabled: Option<bool>, /// Indicates whether the payment method is eligible for card netwotks #[schema(value_type = Option<Vec<CardNetwork>>, example = json!(["visa", "mastercard"]))] pub card_networks: Option<Vec<api_enums::CardNetwork>>, /// Indicates the limit of last used payment methods #[schema(example = 1)] pub limit: Option<i64>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl<'de> serde::Deserialize<'de> for PaymentMethodListRequest { fn deserialize<D>(deserializer: D) -> Result<Self, D::Error> where D: serde::Deserializer<'de>, { struct FieldVisitor; impl<'de> de::Visitor<'de> for FieldVisitor { type Value = PaymentMethodListRequest; fn expecting(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { formatter.write_str("Failed while deserializing as map") } fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error> where A: de::MapAccess<'de>, { let mut output = PaymentMethodListRequest::default(); while let Some(key) = map.next_key()? { match key { "client_secret" => { set_or_reject_duplicate( &mut output.client_secret, "client_secret", map.next_value()?, )?; } "accepted_countries" => match output.accepted_countries.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_countries = Some(vec![map.next_value()?]); } }, "amount" => { set_or_reject_duplicate( &mut output.amount, "amount", map.next_value()?, )?; } "accepted_currencies" => match output.accepted_currencies.as_mut() { Some(inner) => inner.push(map.next_value()?), None => { output.accepted_currencies = Some(vec![map.next_value()?]); } }, "recurring_enabled" => { set_or_reject_duplicate( &mut output.recurring_enabled, "recurring_enabled", map.next_value()?, )?; } "card_network" => match output.card_networks.as_mut() { Some(inner) => inner.push(map.next_value()?), None => output.card_networks = Some(vec![map.next_value()?]), }, "limit" => { set_or_reject_duplicate(&mut output.limit, "limit", map.next_value()?)?; } _ => {} } } Ok(output) } } deserializer.deserialize_identifier(FieldVisitor) } } // Try to set the provided value to the data otherwise throw an error fn set_or_reject_duplicate<T, E: de::Error>( data: &mut Option<T>, name: &'static str, value: T, ) -> Result<(), E> { match data { Some(_inner) => Err(de::Error::duplicate_field(name)), None => { *data = Some(value); Ok(()) } } } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodListResponse { /// Redirect URL of the merchant #[schema(example = "https://www.google.com")] pub redirect_url: Option<String>, /// currency of the Payment to be done #[schema(example = "USD", value_type = Currency)] pub currency: Option<api_enums::Currency>, /// Information about the payment method pub payment_methods: Vec<ResponsePaymentMethodsEnabled>, /// Value indicating if the current payment is a mandate payment #[schema(value_type = MandateType)] pub mandate_payment: Option<payments::MandateType>, #[schema(value_type = Option<String>)] pub merchant_name: OptionalEncryptableName, /// flag to indicate if surcharge and tax breakup screen should be shown or not #[schema(value_type = bool)] pub show_surcharge_breakup_screen: bool, #[schema(value_type = Option<PaymentType>)] pub payment_type: Option<api_enums::PaymentType>, /// flag to indicate whether to perform external 3ds authentication #[schema(example = true)] pub request_external_three_ds_authentication: bool, /// flag that indicates whether to collect shipping details from wallets or from the customer pub collect_shipping_details_from_wallets: Option<bool>, /// flag that indicates whether to collect billing details from wallets or from the customer pub collect_billing_details_from_wallets: Option<bool>, /// flag that indicates whether to calculate tax on the order amount pub is_tax_calculation_enabled: bool, } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] #[derive(Debug, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethodsListResponse { /// List of payment methods for customer pub customer_payment_methods: Vec<CustomerPaymentMethod>, /// Returns whether a customer id is not tied to a payment intent (only when the request is made against a client secret) pub is_guest_customer: Option<bool>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethodsListResponse { /// List of payment methods for customer pub customer_payment_methods: Vec<CustomerPaymentMethod>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Serialize, ToSchema)] pub struct TotalPaymentMethodCountResponse { /// total count of payment methods under the merchant pub total_count: i64, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] impl common_utils::events::ApiEventMetric for TotalPaymentMethodCountResponse {} #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodDeleteResponse { /// The unique identifier of the Payment method #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")] pub payment_method_id: String, /// Whether payment method was deleted or not #[schema(example = true)] pub deleted: bool, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodDeleteResponse { /// The unique identifier of the Payment method #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodId, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct CustomerDefaultPaymentMethodResponse { /// The unique identifier of the Payment method #[schema(example = "card_rGK4Vi5iSW70MY7J2mIg")] pub default_payment_method_id: Option<String>, /// The unique identifier of the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>,example = "credit")] pub payment_method_type: Option<api_enums::PaymentMethodType>, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethod { /// The unique identifier of the payment method. #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodId, /// The unique identifier of the customer. #[schema( min_length = 32, max_length = 64, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8", value_type = String )] pub customer_id: id_type::GlobalCustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method_type: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = PaymentMethodType,example = "credit")] pub payment_method_subtype: api_enums::PaymentMethodType, /// Indicates whether the payment method is eligible for recurring payments #[schema(example = true)] pub recurring_enabled: bool, /// PaymentMethod Data from locker pub payment_method_data: Option<PaymentMethodListData>, /// Masked bank details from PM auth services #[schema(example = json!({"mask": "0000"}))] pub bank: Option<MaskedBankDetails>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = PrimitiveDateTime, example = "2023-01-18T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: time::PrimitiveDateTime, /// Whether this payment method requires CVV to be collected #[schema(example = true)] pub requires_cvv: bool, /// A timestamp (ISO 8601 code) that determines when the payment method was last used #[schema(value_type = PrimitiveDateTime,example = "2024-02-24T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601")] pub last_used_at: time::PrimitiveDateTime, /// Indicates if the payment method has been set to default or not #[schema(example = true)] pub is_default: bool, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, ///The network token details for the payment method pub network_tokenization: Option<NetworkTokenResponse>, /// Whether psp_tokenization is enabled for the payment_method, this will be true when at least /// one multi-use token with status `Active` is available for the payment method pub psp_tokenization_enabled: bool, } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] #[derive(Debug, Clone, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum PaymentMethodListData { Card(CardDetailFromLocker), #[cfg(feature = "payouts")] #[schema(value_type = Bank)] Bank(payouts::Bank), } #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] #[derive(Debug, Clone, serde::Serialize, ToSchema)] pub struct CustomerPaymentMethod { /// Token for payment method in temporary card locker which gets refreshed often #[schema(example = "7ebf443f-a050-4067-84e5-e6f6d4800aef")] pub payment_token: String, /// The unique identifier of the customer. #[schema(example = "pm_iouuy468iyuowqs")] pub payment_method_id: String, /// The unique identifier of the customer. #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, /// The type of payment method use for the payment. #[schema(value_type = PaymentMethod,example = "card")] pub payment_method: api_enums::PaymentMethod, /// This is a sub-category of payment method. #[schema(value_type = Option<PaymentMethodType>,example = "credit_card")] pub payment_method_type: Option<api_enums::PaymentMethodType>, /// The name of the bank/ provider issuing the payment method to the end user #[schema(example = "Citibank")] pub payment_method_issuer: Option<String>, /// A standard code representing the issuer of payment method #[schema(value_type = Option<PaymentMethodIssuerCode>,example = "jp_applepay")] pub payment_method_issuer_code: Option<api_enums::PaymentMethodIssuerCode>, /// Indicates whether the payment method is eligible for recurring payments #[schema(example = true)] pub recurring_enabled: bool, /// Indicates whether the payment method is eligible for installment payments #[schema(example = true)] pub installment_payment_enabled: bool, /// Type of payment experience enabled with the connector #[schema(value_type = Option<Vec<PaymentExperience>>,example = json!(["redirect_to_url"]))] pub payment_experience: Option<Vec<api_enums::PaymentExperience>>, /// Card details from card locker #[schema(example = json!({"last4": "1142","exp_month": "03","exp_year": "2030"}))] pub card: Option<CardDetailFromLocker>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>,example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// A timestamp (ISO 8601 code) that determines when the payment method was created #[schema(value_type = Option<PrimitiveDateTime>,example = "2023-01-18T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created: Option<time::PrimitiveDateTime>, /// Payment method details from locker #[cfg(feature = "payouts")] #[schema(value_type = Option<Bank>)] #[serde(skip_serializing_if = "Option::is_none")] pub bank_transfer: Option<payouts::Bank>, /// Masked bank details from PM auth services #[schema(example = json!({"mask": "0000"}))] pub bank: Option<MaskedBankDetails>, /// Surcharge details for this saved card pub surcharge_details: Option<SurchargeDetailsResponse>, /// Whether this payment method requires CVV to be collected #[schema(example = true)] pub requires_cvv: bool, /// A timestamp (ISO 8601 code) that determines when the payment method was last used #[schema(value_type = Option<PrimitiveDateTime>,example = "2024-02-24T11:04:09.922Z")] #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub last_used_at: Option<time::PrimitiveDateTime>, /// Indicates if the payment method has been set to default or not #[schema(example = true)] pub default_payment_method_set: bool, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentMethodCollectLinkRequest { /// The unique identifier for the collect link. #[schema(value_type = Option<String>, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub pm_collect_link_id: Option<String>, /// The unique identifier of the customer. #[schema(value_type = String, example = "cus_92dnwed8s32bV9D8Snbiasd8v")] pub customer_id: id_type::CustomerId, #[serde(flatten)] #[schema(value_type = Option<GenericLinkUiConfig>)] pub ui_config: Option<link_utils::GenericLinkUiConfig>, /// Will be used to expire client secret after certain amount of time to be supplied in seconds /// (900) for 15 mins #[schema(value_type = Option<u32>, example = 900)] pub session_expiry: Option<u32>, /// Redirect to this URL post completion #[schema(value_type = Option<String>, example = "https://sandbox.hyperswitch.io/payment_method/collect/pm_collect_link_2bdacf398vwzq5n422S1/status")] pub return_url: Option<String>, /// List of payment methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentMethodCollectLinkResponse { /// The unique identifier for the collect link. #[schema(value_type = String, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub pm_collect_link_id: String, /// The unique identifier of the customer. #[schema(value_type = String, example = "cus_92dnwed8s32bV9D8Snbiasd8v")] pub customer_id: id_type::CustomerId, /// Time when this link will be expired in ISO8601 format #[schema(value_type = PrimitiveDateTime, example = "2025-01-18T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub expiry: time::PrimitiveDateTime, /// URL to the form's link generated for collecting payment method details. #[schema(value_type = String, example = "https://sandbox.hyperswitch.io/payment_method/collect/pm_collect_link_2bdacf398vwzq5n422S1")] pub link: masking::Secret<url::Url>, /// Redirect to this URL post completion #[schema(value_type = Option<String>, example = "https://sandbox.hyperswitch.io/payment_method/collect/pm_collect_link_2bdacf398vwzq5n422S1/status")] pub return_url: Option<String>, /// Collect link config used #[serde(flatten)] #[schema(value_type = GenericLinkUiConfig)] pub ui_config: link_utils::GenericLinkUiConfig, /// List of payment methods shown on collect UI #[schema(value_type = Option<Vec<EnabledPaymentMethod>>, example = r#"[{"payment_method": "bank_transfer", "payment_method_types": ["ach", "bacs"]}]"#)] pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct PaymentMethodCollectLinkRenderRequest { /// Unique identifier for a merchant. #[schema(example = "merchant_1671528864", value_type = String)] pub merchant_id: id_type::MerchantId, /// The unique identifier for the collect link. #[schema(value_type = String, example = "pm_collect_link_2bdacf398vwzq5n422S1")] pub pm_collect_link_id: String, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentMethodCollectLinkDetails { pub publishable_key: masking::Secret<String>, pub client_secret: masking::Secret<String>, pub pm_collect_link_id: String, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: time::PrimitiveDateTime, pub return_url: Option<String>, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, pub enabled_payment_methods: Option<Vec<link_utils::EnabledPaymentMethod>>, } #[derive(Clone, Debug, serde::Serialize)] pub struct PaymentMethodCollectLinkStatusDetails { pub pm_collect_link_id: String, pub customer_id: id_type::CustomerId, #[serde(with = "common_utils::custom_serde::iso8601")] pub session_expiry: time::PrimitiveDateTime, pub return_url: Option<url::Url>, pub status: link_utils::PaymentMethodCollectStatus, #[serde(flatten)] pub ui_config: link_utils::GenericLinkUiConfigFormData, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct MaskedBankDetails { pub mask: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] pub struct PaymentMethodId { pub payment_method_id: String, } #[cfg(feature = "v1")] #[derive(Debug, serde::Serialize, serde::Deserialize, Clone, ToSchema)] pub struct DefaultPaymentMethod { #[schema(value_type = String, max_length = 64, min_length = 1, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::CustomerId, pub payment_method_id: String, } //------------------------------------------------TokenizeService------------------------------------------------ #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizePayloadEncrypted { pub payload: String, pub key_id: String, pub version: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizePayloadRequest { pub value1: String, pub value2: String, pub lookup_key: String, pub service_name: String, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct GetTokenizePayloadRequest { pub lookup_key: String, pub service_name: String, pub get_value2: bool, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct DeleteTokenizeByTokenRequest { pub lookup_key: String, pub service_name: String, } #[derive(Debug, serde::Serialize)] // Blocked: Yet to be implemented by `basilisk` pub struct DeleteTokenizeByDateRequest { pub buffer_minutes: i32, pub service_name: String, pub max_rows: i32, } #[derive(Debug, serde::Deserialize)] pub struct GetTokenizePayloadResponse { pub lookup_key: String, pub get_value2: Option<bool>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCardValue1 { pub card_number: String, pub exp_year: String, pub exp_month: String, pub name_on_card: Option<String>, pub nickname: Option<String>, pub card_last_four: Option<String>, pub card_token: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ListCountriesCurrenciesRequest { pub connector: api_enums::Connector, pub payment_method_type: api_enums::PaymentMethodType, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ListCountriesCurrenciesResponse { pub currencies: HashSet<api_enums::Currency>, pub countries: HashSet<CountryCodeWithName>, } #[derive(Debug, serde::Serialize, serde::Deserialize, Eq, Hash, PartialEq)] pub struct CountryCodeWithName { pub code: api_enums::CountryAlpha2, pub name: api_enums::Country, } #[derive(Debug, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct TokenizedCardValue2 { pub card_security_code: Option<String>, pub card_fingerprint: Option<String>, pub external_id: Option<String>, pub customer_id: Option<id_type::CustomerId>, pub payment_method_id: Option<String>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedWalletValue1 { pub data: payments::WalletData, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedWalletValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankTransferValue1 { pub data: payments::BankTransferData, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankTransferValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankRedirectValue1 { pub data: payments::BankRedirectData, } #[derive(Debug, serde::Serialize, serde::Deserialize)] pub struct TokenizedBankRedirectValue2 { pub customer_id: Option<id_type::CustomerId>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct PaymentMethodRecord { pub customer_id: id_type::CustomerId, pub name: Option<masking::Secret<String>>, pub email: Option<pii::Email>, pub phone: Option<masking::Secret<String>>, pub phone_country_code: Option<String>, pub merchant_id: Option<id_type::MerchantId>, pub payment_method: Option<api_enums::PaymentMethod>, pub payment_method_type: Option<api_enums::PaymentMethodType>, pub nick_name: masking::Secret<String>, pub payment_instrument_id: Option<masking::Secret<String>>, pub card_number_masked: masking::Secret<String>, pub card_expiry_month: masking::Secret<String>, pub card_expiry_year: masking::Secret<String>, pub card_scheme: Option<String>, pub original_transaction_id: Option<String>, pub billing_address_zip: masking::Secret<String>, pub billing_address_state: masking::Secret<String>, pub billing_address_first_name: masking::Secret<String>, pub billing_address_last_name: masking::Secret<String>, pub billing_address_city: String, pub billing_address_country: Option<api_enums::CountryAlpha2>, pub billing_address_line1: masking::Secret<String>, pub billing_address_line2: Option<masking::Secret<String>>, pub billing_address_line3: Option<masking::Secret<String>>, pub raw_card_number: Option<masking::Secret<String>>, pub merchant_connector_id: Option<id_type::MerchantConnectorAccountId>, pub original_transaction_amount: Option<i64>, pub original_transaction_currency: Option<common_enums::Currency>, pub line_number: Option<i64>, pub network_token_number: Option<CardNumber>, pub network_token_expiry_month: Option<masking::Secret<String>>, pub network_token_expiry_year: Option<masking::Secret<String>>, pub network_token_requestor_ref_id: Option<String>, } #[derive(Debug, Default, serde::Serialize)] pub struct PaymentMethodMigrationResponse { pub line_number: Option<i64>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_method_id: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_method: Option<api_enums::PaymentMethod>, #[serde(skip_serializing_if = "Option::is_none")] pub payment_method_type: Option<api_enums::PaymentMethodType>, pub customer_id: Option<id_type::CustomerId>, pub migration_status: MigrationStatus, #[serde(skip_serializing_if = "Option::is_none")] pub migration_error: Option<String>, pub card_number_masked: Option<masking::Secret<String>>, pub card_migrated: Option<bool>, pub network_token_migrated: Option<bool>, pub connector_mandate_details_migrated: Option<bool>, pub network_transaction_id_migrated: Option<bool>, } #[derive(Debug, Default, serde::Serialize)] pub enum MigrationStatus { Success, #[default] Failed, } type PaymentMethodMigrationResponseType = ( Result<PaymentMethodMigrateResponse, String>, PaymentMethodRecord, ); #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] impl From<PaymentMethodMigrationResponseType> for PaymentMethodMigrationResponse { fn from((response, record): PaymentMethodMigrationResponseType) -> Self { match response { Ok(res) => Self { payment_method_id: Some(res.payment_method_response.payment_method_id), payment_method: res.payment_method_response.payment_method, payment_method_type: res.payment_method_response.payment_method_type, customer_id: res.payment_method_response.customer_id, migration_status: MigrationStatus::Success, migration_error: None, card_number_masked: Some(record.card_number_masked), line_number: record.line_number, card_migrated: res.card_migrated, network_token_migrated: res.network_token_migrated, connector_mandate_details_migrated: res.connector_mandate_details_migrated, network_transaction_id_migrated: res.network_transaction_id_migrated, }, Err(e) => Self { customer_id: Some(record.customer_id), migration_status: MigrationStatus::Failed, migration_error: Some(e), card_number_masked: Some(record.card_number_masked), line_number: record.line_number, ..Self::default() }, } } } impl TryFrom<( PaymentMethodRecord, id_type::MerchantId, Option<id_type::MerchantConnectorAccountId>, )> for PaymentMethodMigrate { type Error = error_stack::Report<errors::ValidationError>; fn try_from( item: ( PaymentMethodRecord, id_type::MerchantId, Option<id_type::MerchantConnectorAccountId>, ), ) -> Result<Self, Self::Error> { let (record, merchant_id, mca_id) = item; // if payment instrument id is present then only construct this let connector_mandate_details = if record.payment_instrument_id.is_some() { Some(PaymentsMandateReference(HashMap::from([( mca_id.get_required_value("merchant_connector_id")?, PaymentsMandateReferenceRecord { connector_mandate_id: record .payment_instrument_id .get_required_value("payment_instrument_id")? .peek() .to_string(), payment_method_type: record.payment_method_type, original_payment_authorized_amount: record.original_transaction_amount, original_payment_authorized_currency: record.original_transaction_currency, }, )]))) } else { None }; Ok(Self { merchant_id, customer_id: Some(record.customer_id), card: Some(MigrateCardDetail { card_number: record.raw_card_number.unwrap_or(record.card_number_masked), card_exp_month: record.card_expiry_month, card_exp_year: record.card_expiry_year, card_holder_name: record.name.clone(), card_network: None, card_type: None, card_issuer: None, card_issuing_country: None, nick_name: Some(record.nick_name.clone()), }), network_token: Some(MigrateNetworkTokenDetail { network_token_data: MigrateNetworkTokenData { network_token_number: record.network_token_number.unwrap_or_default(), network_token_exp_month: record.network_token_expiry_month.unwrap_or_default(), network_token_exp_year: record.network_token_expiry_year.unwrap_or_default(), card_holder_name: record.name, nick_name: Some(record.nick_name.clone()), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, }, network_token_requestor_ref_id: record .network_token_requestor_ref_id .unwrap_or_default(), }), payment_method: record.payment_method, payment_method_type: record.payment_method_type, payment_method_issuer: None, billing: Some(payments::Address { address: Some(payments::AddressDetails { city: Some(record.billing_address_city), country: record.billing_address_country, line1: Some(record.billing_address_line1), line2: record.billing_address_line2, state: Some(record.billing_address_state), line3: record.billing_address_line3, zip: Some(record.billing_address_zip), first_name: Some(record.billing_address_first_name), last_name: Some(record.billing_address_last_name), }), phone: Some(payments::PhoneDetails { number: record.phone, country_code: record.phone_country_code, }), email: record.email, }), connector_mandate_details: connector_mandate_details.map( |payments_mandate_reference| { CommonMandateReference::from(payments_mandate_reference) }, ), metadata: None, payment_method_issuer_code: None, card_network: None, #[cfg(feature = "payouts")] bank_transfer: None, #[cfg(feature = "payouts")] wallet: None, payment_method_data: None, network_transaction_id: record.original_transaction_id, }) } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl From<(PaymentMethodRecord, id_type::MerchantId)> for customers::CustomerRequest { fn from(value: (PaymentMethodRecord, id_type::MerchantId)) -> Self { let (record, merchant_id) = value; Self { customer_id: Some(record.customer_id), merchant_id, name: record.name, email: record.email, phone: record.phone, description: None, phone_country_code: record.phone_country_code, address: Some(payments::AddressDetails { city: Some(record.billing_address_city), country: record.billing_address_country, line1: Some(record.billing_address_line1), line2: record.billing_address_line2, state: Some(record.billing_address_state), line3: record.billing_address_line3, zip: Some(record.billing_address_zip), first_name: Some(record.billing_address_first_name), last_name: Some(record.billing_address_last_name), }), metadata: None, } } } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardNetworkTokenizeRequest { /// Merchant ID associated with the tokenization request #[schema(example = "merchant_1671528864", value_type = String)] pub merchant_id: id_type::MerchantId, /// Details of the card or payment method to be tokenized #[serde(flatten)] pub data: TokenizeDataRequest, /// Customer details #[schema(value_type = CustomerDetails)] pub customer: payments::CustomerDetails, /// The billing details of the payment method #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// You can specify up to 50 keys, with key names up to 40 characters long and values up to 500 characters long. Metadata is useful for storing additional, structured information on an object. #[schema(value_type = Option<Object>, example = json!({ "city": "NY", "unit": "245" }))] pub metadata: Option<pii::SecretSerdeValue>, /// The name of the bank/ provider issuing the payment method to the end user pub payment_method_issuer: Option<String>, } impl common_utils::events::ApiEventMetric for CardNetworkTokenizeRequest {} #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum TokenizeDataRequest { Card(TokenizeCardRequest), ExistingPaymentMethod(TokenizePaymentMethodRequest), } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(deny_unknown_fields)] pub struct TokenizeCardRequest { /// Card Number #[schema(value_type = String, example = "4111111145551142")] pub raw_card_number: CardNumber, /// Card Expiry Month #[schema(value_type = String, example = "10")] pub card_expiry_month: masking::Secret<String>, /// Card Expiry Year #[schema(value_type = String, example = "25")] pub card_expiry_year: masking::Secret<String>, /// The CVC number for the card #[schema(value_type = Option<String>, example = "242")] pub card_cvc: Option<masking::Secret<String>>, /// Card Holder Name #[schema(value_type = Option<String>, example = "John Doe")] pub card_holder_name: Option<masking::Secret<String>>, /// Card Holder's Nick Name #[schema(value_type = Option<String>, example = "John Doe")] pub nick_name: Option<masking::Secret<String>>, /// Card Issuing Country pub card_issuing_country: Option<String>, /// Card's Network #[schema(value_type = Option<CardNetwork>)] pub card_network: Option<api_enums::CardNetwork>, /// Issuer Bank for Card pub card_issuer: Option<String>, /// Card Type pub card_type: Option<CardType>, } #[derive(Default, Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct TokenizePaymentMethodRequest { /// Payment method's ID #[serde(skip_deserializing)] pub payment_method_id: String, /// The CVC number for the card #[schema(value_type = Option<String>, example = "242")] pub card_cvc: Option<masking::Secret<String>>, } #[derive(Debug, Default, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardNetworkTokenizeResponse { /// Response for payment method entry in DB pub payment_method_response: Option<PaymentMethodResponse>, /// Customer details #[schema(value_type = CustomerDetails)] pub customer: Option<payments::CustomerDetails>, /// Card network tokenization status pub card_tokenized: bool, /// Error code #[serde(skip_serializing_if = "Option::is_none")] pub error_code: Option<String>, /// Error message #[serde(skip_serializing_if = "Option::is_none")] pub error_message: Option<String>, /// Details that were sent for tokenization #[serde(skip_serializing_if = "Option::is_none")] pub tokenization_data: Option<TokenizeDataRequest>, } impl common_utils::events::ApiEventMetric for CardNetworkTokenizeResponse {} impl From<&Card> for MigrateCardDetail { fn from(card: &Card) -> Self { Self { card_number: masking::Secret::new(card.card_number.get_card_no()), card_exp_month: card.card_exp_month.clone(), card_exp_year: card.card_exp_year.clone(), card_holder_name: card.name_on_card.clone(), nick_name: card .nick_name .as_ref() .map(|name| masking::Secret::new(name.clone())), card_issuing_country: None, card_network: None, card_issuer: None, card_type: None, } } } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionRequest { /// The customer id for which the payment methods session is to be created #[schema(value_type = String, example = "cus_y3oqhf46pyzuxjbcn2giaqnb44")] pub customer_id: id_type::GlobalCustomerId, /// The billing address details of the customer. This will also be used for any new payment methods added during the session #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// The return url to which the customer should be redirected to after adding the payment method #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The tokenization type to be applied #[schema(value_type = Option<PspTokenization>)] pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, /// The network tokenization configuration if applicable #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, /// The time (seconds ) when the session will expire /// If not provided, the session will expire in 15 minutes #[schema(example = 900, default = 900)] pub expires_in: Option<u32>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodsSessionUpdateRequest { /// The billing address details of the customer. This will also be used for any new payment methods added during the session #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// The tokenization type to be applied #[schema(value_type = Option<PspTokenization>)] pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, /// The network tokenization configuration if applicable #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionUpdateSavedPaymentMethod { /// The payment method id of the payment method to be updated #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: id_type::GlobalPaymentMethodId, /// The update request for the payment method update #[serde(flatten)] pub payment_method_update_request: PaymentMethodUpdate, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionDeleteSavedPaymentMethod { /// The payment method id of the payment method to be updated #[schema(value_type = String, example = "12345_pm_01926c58bc6e77c09e809964e72af8c8")] pub payment_method_id: id_type::GlobalPaymentMethodId, } #[cfg(feature = "v2")] #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionConfirmRequest { /// The payment method type #[schema(value_type = PaymentMethod, example = "card")] pub payment_method_type: common_enums::PaymentMethod, /// The payment method subtype #[schema(value_type = PaymentMethodType, example = "google_pay")] pub payment_method_subtype: common_enums::PaymentMethodType, /// The payment instrument data to be used for the payment #[schema(value_type = PaymentMethodDataRequest)] pub payment_method_data: payments::PaymentMethodDataRequest, /// The return url to which the customer should be redirected to after adding the payment method #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema)] pub struct PaymentMethodSessionResponse { #[schema(value_type = String, example = "12345_pms_01926c58bc6e77c09e809964e72af8c8")] pub id: id_type::GlobalPaymentMethodSessionId, /// The customer id for which the payment methods session is to be created #[schema(value_type = String, example = "12345_cus_01926c58bc6e77c09e809964e72af8c8")] pub customer_id: id_type::GlobalCustomerId, /// The billing address details of the customer. This will also be used for any new payment methods added during the session #[schema(value_type = Option<Address>)] pub billing: Option<payments::Address>, /// The tokenization type to be applied #[schema(value_type = Option<PspTokenization>)] pub psp_tokenization: Option<common_types::payment_methods::PspTokenization>, /// The network tokenization configuration if applicable #[schema(value_type = Option<NetworkTokenization>)] pub network_tokenization: Option<common_types::payment_methods::NetworkTokenization>, /// The iso timestamp when the session will expire /// Trying to retrieve the session or any operations on the session after this time will result in an error #[schema(value_type = PrimitiveDateTime, example = "2023-01-18T11:04:09.922Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub expires_at: time::PrimitiveDateTime, /// Client Secret #[schema(value_type = String)] pub client_secret: masking::Secret<String>, /// The return url to which the user should be redirected to #[schema(value_type = Option<String>)] pub return_url: Option<common_utils::types::Url>, /// The next action details for the payment method session #[schema(value_type = Option<NextActionData>)] pub next_action: Option<payments::NextActionData>, /// The customer authentication details for the payment method /// This refers to either the payment / external authentication details pub authentication_details: Option<AuthenticationDetails>, /// The payment method that was created using this payment method session #[schema(value_type = Option<Vec<String>>)] pub associated_payment_methods: Option<Vec<id_type::GlobalPaymentMethodId>>, } #[cfg(feature = "v2")] #[derive(Debug, serde::Serialize, ToSchema, Clone)] pub struct AuthenticationDetails { /// The status of authentication for the payment method #[schema(value_type = IntentStatus)] pub status: common_enums::IntentStatus, /// Error details of the authentication #[schema(value_type = Option<ErrorDetails>)] pub error: Option<payments::ErrorDetails>, }
25,714
1,977
hyperswitch
crates/api_models/src/blocklist.rs
.rs
use common_enums::enums; use common_utils::events::ApiEventMetric; use masking::StrongSecret; use utoipa::ToSchema; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] #[serde(rename_all = "snake_case", tag = "type", content = "data")] pub enum BlocklistRequest { CardBin(String), Fingerprint(String), ExtendedCardBin(String), } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct GenerateFingerprintRequest { pub card: Card, pub hash_key: StrongSecret<String>, } #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] pub struct Card { pub card_number: StrongSecret<String>, } pub type AddToBlocklistRequest = BlocklistRequest; pub type DeleteFromBlocklistRequest = BlocklistRequest; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct BlocklistResponse { pub fingerprint_id: String, #[schema(value_type = BlocklistDataKind)] pub data_kind: enums::BlocklistDataKind, #[serde(with = "common_utils::custom_serde::iso8601")] pub created_at: time::PrimitiveDateTime, } #[derive(Clone, Debug, serde::Deserialize, serde::Serialize)] #[serde(rename_all = "snake_case")] pub struct GenerateFingerprintResponsePayload { pub card_fingerprint: String, } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ToggleBlocklistResponse { pub blocklist_guard_status: String, } pub type AddToBlocklistResponse = BlocklistResponse; pub type DeleteFromBlocklistResponse = BlocklistResponse; #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ListBlocklistQuery { #[schema(value_type = BlocklistDataKind)] pub data_kind: enums::BlocklistDataKind, #[serde(default = "default_list_limit")] pub limit: u16, #[serde(default)] pub offset: u16, } fn default_list_limit() -> u16 { 10 } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, ToSchema)] pub struct ToggleBlocklistQuery { #[schema(value_type = BlocklistDataKind)] pub status: bool, } impl ApiEventMetric for BlocklistRequest {} impl ApiEventMetric for BlocklistResponse {} impl ApiEventMetric for ToggleBlocklistResponse {} impl ApiEventMetric for ListBlocklistQuery {} impl ApiEventMetric for GenerateFingerprintRequest {} impl ApiEventMetric for ToggleBlocklistQuery {} impl ApiEventMetric for GenerateFingerprintResponsePayload {} impl ApiEventMetric for Card {}
576
1,978
hyperswitch
crates/api_models/src/webhook_events.rs
.rs
use common_enums::{EventClass, EventType, WebhookDeliveryAttempt}; use masking::Secret; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; /// The constraints to apply when filtering events. #[derive(Clone, Debug, Serialize, Deserialize, ToSchema)] pub struct EventListConstraints { /// Filter events created after the specified time. #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created_after: Option<PrimitiveDateTime>, /// Filter events created before the specified time. #[serde(default, with = "common_utils::custom_serde::iso8601::option")] pub created_before: Option<PrimitiveDateTime>, /// Include at most the specified number of events. pub limit: Option<u16>, /// Include events after the specified offset. pub offset: Option<u16>, /// Filter all events associated with the specified object identifier (Payment Intent ID, /// Refund ID, etc.) pub object_id: Option<String>, /// Filter all events associated with the specified business profile ID. #[schema(value_type = Option<String>)] pub profile_id: Option<common_utils::id_type::ProfileId>, /// Filter all events by `is_overall_delivery_successful` field of the event. pub is_delivered: Option<bool>, } #[derive(Debug)] pub enum EventListConstraintsInternal { GenericFilter { created_after: Option<PrimitiveDateTime>, created_before: Option<PrimitiveDateTime>, limit: Option<i64>, offset: Option<i64>, is_delivered: Option<bool>, }, ObjectIdFilter { object_id: String, }, } /// The response body for each item when listing events. #[derive(Debug, Serialize, ToSchema)] pub struct EventListItemResponse { /// The identifier for the Event. #[schema(max_length = 64, example = "evt_018e31720d1b7a2b82677d3032cab959")] pub event_id: String, /// The identifier for the Merchant Account. #[schema(max_length = 64, example = "y3oqhf46pyzuxjbcn2giaqnb44", value_type = String)] pub merchant_id: common_utils::id_type::MerchantId, /// The identifier for the Business Profile. #[schema(max_length = 64, value_type = String, example = "SqB0zwDGR5wHppWf0bx7GKr1f2")] pub profile_id: common_utils::id_type::ProfileId, /// The identifier for the object (Payment Intent ID, Refund ID, etc.) #[schema(max_length = 64, example = "QHrfd5LUDdZaKtAjdJmMu0dMa1")] pub object_id: String, /// Specifies the type of event, which includes the object and its status. pub event_type: EventType, /// Specifies the class of event (the type of object: Payment, Refund, etc.) pub event_class: EventClass, /// Indicates whether the webhook was ultimately delivered or not. pub is_delivery_successful: Option<bool>, /// The identifier for the initial delivery attempt. This will be the same as `event_id` for /// the initial delivery attempt. #[schema(max_length = 64, example = "evt_018e31720d1b7a2b82677d3032cab959")] pub initial_attempt_id: String, /// Time at which the event was created. #[schema(example = "2022-09-10T10:11:12Z")] #[serde(with = "common_utils::custom_serde::iso8601")] pub created: PrimitiveDateTime, } /// The response body of list initial delivery attempts api call. #[derive(Debug, Serialize, ToSchema)] pub struct TotalEventsResponse { /// The list of events pub events: Vec<EventListItemResponse>, /// Count of total events pub total_count: i64, } impl TotalEventsResponse { pub fn new(total_count: i64, events: Vec<EventListItemResponse>) -> Self { Self { events, total_count, } } } impl common_utils::events::ApiEventMetric for TotalEventsResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.events.first().map(|event| event.merchant_id.clone())?, }) } } /// The response body for retrieving an event. #[derive(Debug, Serialize, ToSchema)] pub struct EventRetrieveResponse { #[serde(flatten)] pub event_information: EventListItemResponse, /// The request information (headers and body) sent in the webhook. pub request: OutgoingWebhookRequestContent, /// The response information (headers, body and status code) received for the webhook sent. pub response: OutgoingWebhookResponseContent, /// Indicates the type of delivery attempt. pub delivery_attempt: Option<WebhookDeliveryAttempt>, } impl common_utils::events::ApiEventMetric for EventRetrieveResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.event_information.merchant_id.clone(), }) } } /// The request information (headers and body) sent in the webhook. #[derive(Debug, Serialize, Deserialize, ToSchema)] pub struct OutgoingWebhookRequestContent { /// The request body sent in the webhook. #[schema(value_type = String)] #[serde(alias = "payload")] pub body: Secret<String>, /// The request headers sent in the webhook. #[schema( value_type = Vec<(String, String)>, example = json!([["content-type", "application/json"], ["content-length", "1024"]])) ] pub headers: Vec<(String, Secret<String>)>, } /// The response information (headers, body and status code) received for the webhook sent. #[derive(Debug, serde::Serialize, serde::Deserialize, ToSchema)] pub struct OutgoingWebhookResponseContent { /// The response body received for the webhook sent. #[schema(value_type = Option<String>)] #[serde(alias = "payload")] pub body: Option<Secret<String>>, /// The response headers received for the webhook sent. #[schema( value_type = Option<Vec<(String, String)>>, example = json!([["content-type", "application/json"], ["content-length", "1024"]])) ] pub headers: Option<Vec<(String, Secret<String>)>>, /// The HTTP status code for the webhook sent. #[schema(example = 200)] pub status_code: Option<u16>, /// Error message in case any error occurred when trying to deliver the webhook. #[schema(example = 200)] pub error_message: Option<String>, } #[derive(Debug, serde::Serialize)] pub struct EventListRequestInternal { pub merchant_id: common_utils::id_type::MerchantId, pub constraints: EventListConstraints, } impl common_utils::events::ApiEventMetric for EventListRequestInternal { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.merchant_id.clone(), }) } } #[derive(Debug, serde::Serialize)] pub struct WebhookDeliveryAttemptListRequestInternal { pub merchant_id: common_utils::id_type::MerchantId, pub initial_attempt_id: String, } impl common_utils::events::ApiEventMetric for WebhookDeliveryAttemptListRequestInternal { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.merchant_id.clone(), }) } } #[derive(Debug, serde::Serialize)] pub struct WebhookDeliveryRetryRequestInternal { pub merchant_id: common_utils::id_type::MerchantId, pub event_id: String, } impl common_utils::events::ApiEventMetric for WebhookDeliveryRetryRequestInternal { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::Events { merchant_id: self.merchant_id.clone(), }) } }
1,884
1,979
hyperswitch
crates/api_models/src/poll.rs
.rs
use common_utils::events::{ApiEventMetric, ApiEventsType}; use serde::Serialize; use utoipa::ToSchema; #[derive(Debug, ToSchema, Clone, Serialize)] pub struct PollResponse { /// The poll id pub poll_id: String, /// Status of the poll pub status: PollStatus, } #[derive(Debug, strum::Display, strum::EnumString, Clone, serde::Serialize, ToSchema)] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum PollStatus { Pending, Completed, NotFound, } impl ApiEventMetric for PollResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Poll { poll_id: self.poll_id.clone(), }) } }
177
1,980
hyperswitch
crates/api_models/src/files.rs
.rs
use utoipa::ToSchema; #[derive(Debug, serde::Serialize, ToSchema)] pub struct CreateFileResponse { /// ID of the file created pub file_id: String, } #[derive(Debug, serde::Serialize, ToSchema, Clone)] pub struct FileMetadataResponse { /// ID of the file created pub file_id: String, /// Name of the file pub file_name: Option<String>, /// Size of the file pub file_size: i32, /// Type of the file pub file_type: String, /// File availability pub available: bool, }
132
1,981
hyperswitch
crates/api_models/src/cards_info.rs
.rs
use std::fmt::Debug; use common_utils::events::ApiEventMetric; use utoipa::ToSchema; use crate::enums; #[derive(serde::Deserialize, ToSchema)] pub struct CardsInfoRequestParams { #[schema(example = "pay_OSERgeV9qAy7tlK7aKpc_secret_TuDUoh11Msxh12sXn3Yp")] pub client_secret: Option<String>, } #[derive(serde::Deserialize, Debug, serde::Serialize)] pub struct CardsInfoRequest { pub client_secret: Option<String>, pub card_iin: String, } #[derive(serde::Serialize, Debug, ToSchema)] pub struct CardInfoResponse { #[schema(example = "374431")] pub card_iin: String, #[schema(example = "AMEX")] pub card_issuer: Option<String>, #[schema(example = "AMEX")] pub card_network: Option<String>, #[schema(example = "CREDIT")] pub card_type: Option<String>, #[schema(example = "CLASSIC")] pub card_sub_type: Option<String>, #[schema(example = "INDIA")] pub card_issuing_country: Option<String>, } #[derive(serde::Serialize, Debug, ToSchema)] pub struct CardInfoMigrateResponseRecord { pub card_iin: Option<String>, pub card_issuer: Option<String>, pub card_network: Option<String>, pub card_type: Option<String>, pub card_sub_type: Option<String>, pub card_issuing_country: Option<String>, } #[derive(Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardInfoCreateRequest { pub card_iin: String, pub card_issuer: Option<String>, pub card_network: Option<enums::CardNetwork>, pub card_type: Option<String>, pub card_subtype: Option<String>, pub card_issuing_country: Option<String>, pub bank_code_id: Option<String>, pub bank_code: Option<String>, pub country_code: Option<String>, pub last_updated_provider: Option<String>, } impl ApiEventMetric for CardInfoCreateRequest {} #[derive(Debug, Clone, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardInfoUpdateRequest { pub card_iin: String, pub card_issuer: Option<String>, pub card_network: Option<enums::CardNetwork>, pub card_type: Option<String>, pub card_subtype: Option<String>, pub card_issuing_country: Option<String>, pub bank_code_id: Option<String>, pub bank_code: Option<String>, pub country_code: Option<String>, pub last_updated_provider: Option<String>, pub line_number: Option<i64>, } impl ApiEventMetric for CardInfoUpdateRequest {} #[derive(Debug, Default, serde::Serialize)] pub enum CardInfoMigrationStatus { Success, #[default] Failed, } #[derive(Debug, Default, serde::Serialize)] pub struct CardInfoMigrationResponse { pub line_number: Option<i64>, pub card_iin: String, pub card_issuer: Option<String>, pub card_network: Option<String>, pub card_type: Option<String>, pub card_sub_type: Option<String>, pub card_issuing_country: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub migration_error: Option<String>, pub migration_status: CardInfoMigrationStatus, } impl ApiEventMetric for CardInfoMigrationResponse {} type CardInfoMigrationResponseType = ( Result<CardInfoMigrateResponseRecord, String>, CardInfoUpdateRequest, ); impl From<CardInfoMigrationResponseType> for CardInfoMigrationResponse { fn from((response, record): CardInfoMigrationResponseType) -> Self { match response { Ok(res) => Self { card_iin: record.card_iin, line_number: record.line_number, card_issuer: res.card_issuer, card_network: res.card_network, card_type: res.card_type, card_sub_type: res.card_sub_type, card_issuing_country: res.card_issuing_country, migration_status: CardInfoMigrationStatus::Success, migration_error: None, }, Err(e) => Self { card_iin: record.card_iin, migration_status: CardInfoMigrationStatus::Failed, migration_error: Some(e), line_number: record.line_number, ..Self::default() }, } } }
955
1,982
hyperswitch
crates/api_models/src/verifications.rs
.rs
use common_utils::id_type; /// The request body for verification of merchant (everything except domain_names are prefilled) #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] pub struct ApplepayMerchantVerificationConfigs { pub domain_names: Vec<String>, pub encrypt_to: String, pub partner_internal_merchant_identifier: String, pub partner_merchant_name: String, } /// The derivation point for domain names from request body #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct ApplepayMerchantVerificationRequest { pub domain_names: Vec<String>, pub merchant_connector_account_id: id_type::MerchantConnectorAccountId, } /// Response to be sent for the verify/applepay api #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct ApplepayMerchantResponse { pub status_message: String, } /// QueryParams to be send by the merchant for fetching the verified domains #[derive(Debug, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct ApplepayGetVerifiedDomainsParam { pub merchant_id: id_type::MerchantId, pub merchant_connector_account_id: id_type::MerchantConnectorAccountId, } /// Response to be sent for derivation of the already verified domains #[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "snake_case")] pub struct ApplepayVerifiedDomainsResponse { pub verified_domains: Vec<String>, }
325
1,983
hyperswitch
crates/api_models/src/payments/additional_info.rs
.rs
use common_utils::new_type::{ MaskedBankAccount, MaskedIban, MaskedRoutingNumber, MaskedSortCode, MaskedUpiVpaId, }; use masking::Secret; use utoipa::ToSchema; use crate::enums as api_enums; #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankDebitAdditionalData { Ach(Box<AchBankDebitAdditionalData>), Bacs(Box<BacsBankDebitAdditionalData>), Becs(Box<BecsBankDebitAdditionalData>), Sepa(Box<SepaBankDebitAdditionalData>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct AchBankDebitAdditionalData { /// Partially masked account number for ach bank debit payment #[schema(value_type = String, example = "0001****3456")] pub account_number: MaskedBankAccount, /// Partially masked routing number for ach bank debit payment #[schema(value_type = String, example = "110***000")] pub routing_number: MaskedRoutingNumber, /// Card holder's name #[schema(value_type = Option<String>, example = "John Doe")] pub card_holder_name: Option<Secret<String>>, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, /// Name of the bank #[schema(value_type = Option<BankNames>, example = "ach")] pub bank_name: Option<common_enums::BankNames>, /// Bank account type #[schema(value_type = Option<BankType>, example = "checking")] pub bank_type: Option<common_enums::BankType>, /// Bank holder entity type #[schema(value_type = Option<BankHolderType>, example = "personal")] pub bank_holder_type: Option<common_enums::BankHolderType>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BacsBankDebitAdditionalData { /// Partially masked account number for Bacs payment method #[schema(value_type = String, example = "0001****3456")] pub account_number: MaskedBankAccount, /// Partially masked sort code for Bacs payment method #[schema(value_type = String, example = "108800")] pub sort_code: MaskedSortCode, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BecsBankDebitAdditionalData { /// Partially masked account number for Becs payment method #[schema(value_type = String, example = "0001****3456")] pub account_number: MaskedBankAccount, /// Bank-State-Branch (bsb) number #[schema(value_type = String, example = "000000")] pub bsb_number: Secret<String>, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct SepaBankDebitAdditionalData { /// Partially masked international bank account number (iban) for SEPA #[schema(value_type = String, example = "DE8937******013000")] pub iban: MaskedIban, /// Bank account's owner name #[schema(value_type = Option<String>, example = "John Doe")] pub bank_account_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub enum BankRedirectDetails { BancontactCard(Box<BancontactBankRedirectAdditionalData>), Blik(Box<BlikBankRedirectAdditionalData>), Giropay(Box<GiropayBankRedirectAdditionalData>), } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BancontactBankRedirectAdditionalData { /// Last 4 digits of the card number #[schema(value_type = Option<String>, example = "4242")] pub last4: Option<String>, /// The card's expiry month #[schema(value_type = Option<String>, example = "12")] pub card_exp_month: Option<Secret<String>>, /// The card's expiry year #[schema(value_type = Option<String>, example = "24")] pub card_exp_year: Option<Secret<String>>, /// The card holder's name #[schema(value_type = Option<String>, example = "John Test")] pub card_holder_name: Option<Secret<String>>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct BlikBankRedirectAdditionalData { #[schema(value_type = Option<String>, example = "3GD9MO")] pub blik_code: Option<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GiropayBankRedirectAdditionalData { #[schema(value_type = Option<String>)] /// Masked bank account bic code pub bic: Option<MaskedSortCode>, /// Partially masked international bank account number (iban) for SEPA #[schema(value_type = Option<String>)] pub iban: Option<MaskedIban>, /// Country for bank payment #[schema(value_type = Option<CountryAlpha2>, example = "US")] pub country: Option<api_enums::CountryAlpha2>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum BankTransferAdditionalData { Ach {}, Sepa {}, Bacs {}, Multibanco {}, Permata {}, Bca {}, BniVa {}, BriVa {}, CimbVa {}, DanamonVa {}, MandiriVa {}, Pix(Box<PixBankTransferAdditionalData>), Pse {}, LocalBankTransfer(Box<LocalBankTransferAdditionalData>), InstantBankTransfer {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct PixBankTransferAdditionalData { /// Partially masked unique key for pix transfer #[schema(value_type = Option<String>, example = "a1f4102e ****** 6fa48899c1d1")] pub pix_key: Option<MaskedBankAccount>, /// Partially masked CPF - CPF is a Brazilian tax identification number #[schema(value_type = Option<String>, example = "**** 124689")] pub cpf: Option<MaskedBankAccount>, /// Partially masked CNPJ - CNPJ is a Brazilian company tax identification number #[schema(value_type = Option<String>, example = "**** 417312")] pub cnpj: Option<MaskedBankAccount>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct LocalBankTransferAdditionalData { /// Partially masked bank code #[schema(value_type = Option<String>, example = "**** OA2312")] pub bank_code: Option<MaskedBankAccount>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum GiftCardAdditionalData { Givex(Box<GivexGiftCardAdditionalData>), PaySafeCard {}, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct GivexGiftCardAdditionalData { /// Last 4 digits of the gift card number #[schema(value_type = String, example = "4242")] pub last4: Secret<String>, } #[derive(Eq, PartialEq, Clone, Debug, serde::Deserialize, serde::Serialize, ToSchema)] pub struct CardTokenAdditionalData { /// The card holder's name #[schema(value_type = String, example = "John Test")] pub card_holder_name: Option<Secret<String>>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] #[serde(rename_all = "snake_case")] pub enum UpiAdditionalData { UpiCollect(Box<UpiCollectAdditionalData>), #[schema(value_type = UpiIntentData)] UpiIntent(Box<super::UpiIntentData>), } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct UpiCollectAdditionalData { /// Masked VPA ID #[schema(value_type = Option<String>, example = "ab********@okhdfcbank")] pub vpa_id: Option<MaskedUpiVpaId>, } #[derive(Debug, Clone, Eq, PartialEq, serde::Deserialize, serde::Serialize, ToSchema)] pub struct WalletAdditionalDataForCard { /// Last 4 digits of the card number pub last4: String, /// The information of the payment method pub card_network: String, /// The type of payment method #[serde(rename = "type")] pub card_type: Option<String>, }
2,127
1,984
hyperswitch
crates/api_models/src/payments/trait_impls.rs
.rs
#[cfg(feature = "v1")] use common_enums::enums; #[cfg(feature = "v1")] use common_utils::errors; #[cfg(feature = "v1")] use crate::payments; #[cfg(feature = "v1")] impl crate::ValidateFieldAndGet<payments::PaymentsRequest> for common_types::primitive_wrappers::RequestExtendedAuthorizationBool { fn validate_field_and_get( &self, request: &payments::PaymentsRequest, ) -> errors::CustomResult<Self, errors::ValidationError> where Self: Sized, { match request.capture_method{ Some(enums::CaptureMethod::Automatic) | Some(enums::CaptureMethod::Scheduled) | Some(enums::CaptureMethod::SequentialAutomatic) | None => Err(error_stack::report!(errors::ValidationError::InvalidValue { message: "request_extended_authorization must be sent only if capture method is manual or manual_multiple".to_string() })), Some(enums::CaptureMethod::Manual) | Some(enums::CaptureMethod::ManualMultiple) => Ok(*self) } } }
233
1,985
hyperswitch
crates/api_models/src/user_role/role.rs
.rs
use common_enums::{ EntityType, ParentGroup, PermissionGroup, PermissionScope, Resource, RoleScope, }; #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct CreateRoleRequest { pub role_name: String, pub groups: Vec<PermissionGroup>, pub role_scope: RoleScope, pub entity_type: Option<EntityType>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct UpdateRoleRequest { pub groups: Option<Vec<PermissionGroup>>, pub role_name: Option<String>, } #[derive(Debug, serde::Serialize)] pub struct RoleInfoWithGroupsResponse { pub role_id: String, pub groups: Vec<PermissionGroup>, pub role_name: String, pub role_scope: RoleScope, pub entity_type: EntityType, } #[derive(Debug, serde::Serialize)] pub struct RoleInfoWithParents { pub role_id: String, pub parent_groups: Vec<ParentGroupInfo>, pub role_name: String, pub role_scope: RoleScope, } #[derive(Debug, serde::Serialize)] pub struct ParentGroupInfo { pub name: ParentGroup, pub description: String, pub scopes: Vec<PermissionScope>, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ListRolesRequest { pub entity_type: Option<EntityType>, } #[derive(Debug, serde::Serialize)] pub struct RoleInfoResponseNew { pub role_id: String, pub role_name: String, pub entity_type: EntityType, pub groups: Vec<PermissionGroup>, pub scope: RoleScope, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct GetRoleRequest { pub role_id: String, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub struct ListRolesAtEntityLevelRequest { pub entity_type: EntityType, } #[derive(Debug, serde::Deserialize, serde::Serialize)] pub enum RoleCheckType { Invite, Update, } #[derive(Debug, serde::Serialize, Clone)] pub struct MinimalRoleInfo { pub role_id: String, pub role_name: String, } #[derive(Debug, serde::Serialize)] pub struct GroupsAndResources { pub groups: Vec<PermissionGroup>, pub resources: Vec<Resource>, }
476
1,986
hyperswitch
crates/api_models/src/errors/actix.rs
.rs
use super::types::ApiErrorResponse; impl actix_web::ResponseError for ApiErrorResponse { fn status_code(&self) -> reqwest::StatusCode { use reqwest::StatusCode; match self { Self::Unauthorized(_) => StatusCode::UNAUTHORIZED, Self::ForbiddenCommonResource(_) => StatusCode::FORBIDDEN, Self::ForbiddenPrivateResource(_) => StatusCode::NOT_FOUND, Self::Conflict(_) => StatusCode::CONFLICT, Self::Gone(_) => StatusCode::GONE, Self::Unprocessable(_) => StatusCode::UNPROCESSABLE_ENTITY, Self::InternalServerError(_) => StatusCode::INTERNAL_SERVER_ERROR, Self::NotImplemented(_) => StatusCode::NOT_IMPLEMENTED, Self::ConnectorError(_, code) => *code, Self::MethodNotAllowed(_) => StatusCode::METHOD_NOT_ALLOWED, Self::NotFound(_) => StatusCode::NOT_FOUND, Self::BadRequest(_) => StatusCode::BAD_REQUEST, Self::DomainError(_) => StatusCode::OK, } } fn error_response(&self) -> actix_web::HttpResponse { use actix_web::http::header; actix_web::HttpResponseBuilder::new(self.status_code()) .insert_header((header::CONTENT_TYPE, mime::APPLICATION_JSON)) .body(self.to_string()) } }
267
1,987
hyperswitch
crates/api_models/src/errors/types.rs
.rs
use std::borrow::Cow; use reqwest::StatusCode; use serde::Serialize; #[derive(Debug, serde::Serialize)] pub enum ErrorType { InvalidRequestError, RouterError, ConnectorError, } #[derive(Debug, serde::Serialize, Clone)] pub struct ApiError { pub sub_code: &'static str, pub error_identifier: u16, pub error_message: String, pub extra: Option<Extra>, #[cfg(feature = "detailed_errors")] pub stacktrace: Option<serde_json::Value>, } impl ApiError { pub fn new( sub_code: &'static str, error_identifier: u16, error_message: impl ToString, extra: Option<Extra>, ) -> Self { Self { sub_code, error_identifier, error_message: error_message.to_string(), extra, #[cfg(feature = "detailed_errors")] stacktrace: None, } } } #[derive(Debug, serde::Serialize)] struct ErrorResponse<'a> { #[serde(rename = "type")] error_type: &'static str, message: Cow<'a, str>, code: String, #[serde(flatten)] extra: &'a Option<Extra>, #[cfg(feature = "detailed_errors")] #[serde(skip_serializing_if = "Option::is_none")] stacktrace: Option<&'a serde_json::Value>, } impl<'a> From<&'a ApiErrorResponse> for ErrorResponse<'a> { fn from(value: &'a ApiErrorResponse) -> Self { let error_info = value.get_internal_error(); let error_type = value.error_type(); Self { code: format!("{}_{:02}", error_info.sub_code, error_info.error_identifier), message: Cow::Borrowed(value.get_internal_error().error_message.as_str()), error_type, extra: &error_info.extra, #[cfg(feature = "detailed_errors")] stacktrace: error_info.stacktrace.as_ref(), } } } #[derive(Debug, serde::Serialize, Default, Clone)] pub struct Extra { #[serde(skip_serializing_if = "Option::is_none")] pub payment_id: Option<common_utils::id_type::PaymentId>, #[serde(skip_serializing_if = "Option::is_none")] pub data: Option<serde_json::Value>, #[serde(skip_serializing_if = "Option::is_none")] pub connector: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub reason: Option<String>, #[serde(skip_serializing_if = "Option::is_none")] pub connector_transaction_id: Option<String>, } #[derive(Serialize, Debug, Clone)] #[serde(tag = "type", content = "value")] pub enum ApiErrorResponse { Unauthorized(ApiError), ForbiddenCommonResource(ApiError), ForbiddenPrivateResource(ApiError), Conflict(ApiError), Gone(ApiError), Unprocessable(ApiError), InternalServerError(ApiError), NotImplemented(ApiError), ConnectorError(ApiError, #[serde(skip_serializing)] StatusCode), NotFound(ApiError), MethodNotAllowed(ApiError), BadRequest(ApiError), DomainError(ApiError), } impl ::core::fmt::Display for ApiErrorResponse { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let error_response: ErrorResponse<'_> = self.into(); write!( f, r#"{{"error":{}}}"#, serde_json::to_string(&error_response) .unwrap_or_else(|_| "API error response".to_string()) ) } } impl ApiErrorResponse { pub(crate) fn get_internal_error(&self) -> &ApiError { match self { Self::Unauthorized(i) | Self::ForbiddenCommonResource(i) | Self::ForbiddenPrivateResource(i) | Self::Conflict(i) | Self::Gone(i) | Self::Unprocessable(i) | Self::InternalServerError(i) | Self::NotImplemented(i) | Self::NotFound(i) | Self::MethodNotAllowed(i) | Self::BadRequest(i) | Self::DomainError(i) | Self::ConnectorError(i, _) => i, } } pub fn get_internal_error_mut(&mut self) -> &mut ApiError { match self { Self::Unauthorized(i) | Self::ForbiddenCommonResource(i) | Self::ForbiddenPrivateResource(i) | Self::Conflict(i) | Self::Gone(i) | Self::Unprocessable(i) | Self::InternalServerError(i) | Self::NotImplemented(i) | Self::NotFound(i) | Self::MethodNotAllowed(i) | Self::BadRequest(i) | Self::DomainError(i) | Self::ConnectorError(i, _) => i, } } pub(crate) fn error_type(&self) -> &'static str { match self { Self::Unauthorized(_) | Self::ForbiddenCommonResource(_) | Self::ForbiddenPrivateResource(_) | Self::Conflict(_) | Self::Gone(_) | Self::Unprocessable(_) | Self::NotImplemented(_) | Self::MethodNotAllowed(_) | Self::NotFound(_) | Self::BadRequest(_) => "invalid_request", Self::InternalServerError(_) => "api", Self::DomainError(_) => "blocked", Self::ConnectorError(_, _) => "connector", } } } impl std::error::Error for ApiErrorResponse {}
1,178
1,988
hyperswitch
crates/api_models/src/events/apple_pay_certificates_migration.rs
.rs
use common_utils::events::ApiEventMetric; use crate::apple_pay_certificates_migration::ApplePayCertificatesMigrationResponse; impl ApiEventMetric for ApplePayCertificatesMigrationResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::ApplePayCertificatesMigration) } }
77
1,989
hyperswitch
crates/api_models/src/events/refund.rs
.rs
use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::refunds::{ RefundAggregateResponse, RefundListFilters, RefundListMetaData, RefundListRequest, RefundListResponse, RefundManualUpdateRequest, RefundRequest, RefundResponse, RefundUpdateRequest, RefundsRetrieveRequest, }; #[cfg(feature = "v1")] impl ApiEventMetric for RefundRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { let payment_id = self.payment_id.clone(); self.refund_id .clone() .map(|refund_id| ApiEventsType::Refund { payment_id: Some(payment_id), refund_id, }) } } #[cfg(feature = "v1")] impl ApiEventMetric for RefundResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Refund { payment_id: Some(self.payment_id.clone()), refund_id: self.refund_id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for RefundResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Refund { payment_id: self.payment_id.clone(), refund_id: self.id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for RefundsRetrieveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Refund { payment_id: None, refund_id: self.refund_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for RefundUpdateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Refund { payment_id: None, refund_id: self.refund_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for RefundManualUpdateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Refund { payment_id: None, refund_id: self.refund_id.clone(), }) } } impl ApiEventMetric for RefundListRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for RefundListResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for RefundAggregateResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for RefundListMetaData { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for RefundListFilters { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } }
687
1,990
hyperswitch
crates/api_models/src/events/external_service_auth.rs
.rs
use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::external_service_auth::{ ExternalSignoutTokenRequest, ExternalTokenResponse, ExternalVerifyTokenRequest, ExternalVerifyTokenResponse, }; impl ApiEventMetric for ExternalTokenResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ExternalServiceAuth) } } impl ApiEventMetric for ExternalVerifyTokenRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ExternalServiceAuth) } } impl ApiEventMetric for ExternalVerifyTokenResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ExternalServiceAuth) } } impl ApiEventMetric for ExternalSignoutTokenRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ExternalServiceAuth) } }
204
1,991
hyperswitch
crates/api_models/src/events/connector_onboarding.rs
.rs
use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::connector_onboarding::{ ActionUrlRequest, ActionUrlResponse, OnboardingStatus, OnboardingSyncRequest, ResetTrackingIdRequest, }; common_utils::impl_api_event_type!( Miscellaneous, ( ActionUrlRequest, ActionUrlResponse, OnboardingSyncRequest, OnboardingStatus, ResetTrackingIdRequest ) );
89
1,992
hyperswitch
crates/api_models/src/events/user.rs
.rs
use common_utils::events::{ApiEventMetric, ApiEventsType}; #[cfg(feature = "dummy_connector")] use crate::user::sample_data::SampleDataRequest; #[cfg(feature = "control_center_theme")] use crate::user::theme::{ CreateThemeRequest, GetThemeResponse, UpdateThemeRequest, UploadFileRequest, }; use crate::user::{ dashboard_metadata::{ GetMetaDataRequest, GetMetaDataResponse, GetMultipleMetaDataPayload, SetMetaDataRequest, }, AcceptInviteFromEmailRequest, AuthSelectRequest, AuthorizeResponse, BeginTotpResponse, ChangePasswordRequest, ConnectAccountRequest, CreateInternalUserRequest, CreateTenantUserRequest, CreateUserAuthenticationMethodRequest, ForgotPasswordRequest, GetSsoAuthUrlRequest, GetUserAuthenticationMethodsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponseV2, InviteUserRequest, ReInviteUserRequest, RecoveryCodes, ResetPasswordRequest, RotatePasswordRequest, SendVerifyEmailRequest, SignUpRequest, SignUpWithMerchantIdRequest, SsoSignInRequest, SwitchMerchantRequest, SwitchOrganizationRequest, SwitchProfileRequest, TokenResponse, TwoFactorAuthStatusResponse, TwoFactorStatus, UpdateUserAccountDetailsRequest, UpdateUserAuthenticationMethodRequest, UserFromEmailRequest, UserMerchantAccountResponse, UserMerchantCreate, UserOrgMerchantCreateRequest, VerifyEmailRequest, VerifyRecoveryCodeRequest, VerifyTotpRequest, }; common_utils::impl_api_event_type!( Miscellaneous, ( SignUpRequest, SignUpWithMerchantIdRequest, ChangePasswordRequest, GetMultipleMetaDataPayload, GetMetaDataResponse, GetMetaDataRequest, SetMetaDataRequest, SwitchOrganizationRequest, SwitchMerchantRequest, SwitchProfileRequest, CreateInternalUserRequest, CreateTenantUserRequest, UserOrgMerchantCreateRequest, UserMerchantAccountResponse, UserMerchantCreate, AuthorizeResponse, ConnectAccountRequest, ForgotPasswordRequest, ResetPasswordRequest, RotatePasswordRequest, InviteUserRequest, ReInviteUserRequest, VerifyEmailRequest, SendVerifyEmailRequest, AcceptInviteFromEmailRequest, UpdateUserAccountDetailsRequest, GetUserDetailsResponse, GetUserRoleDetailsRequest, GetUserRoleDetailsResponseV2, TokenResponse, TwoFactorAuthStatusResponse, TwoFactorStatus, UserFromEmailRequest, BeginTotpResponse, VerifyRecoveryCodeRequest, VerifyTotpRequest, RecoveryCodes, GetUserAuthenticationMethodsRequest, CreateUserAuthenticationMethodRequest, UpdateUserAuthenticationMethodRequest, GetSsoAuthUrlRequest, SsoSignInRequest, AuthSelectRequest ) ); #[cfg(feature = "control_center_theme")] common_utils::impl_api_event_type!( Miscellaneous, ( GetThemeResponse, UploadFileRequest, CreateThemeRequest, UpdateThemeRequest ) ); #[cfg(feature = "dummy_connector")] common_utils::impl_api_event_type!(Miscellaneous, (SampleDataRequest));
625
1,993
hyperswitch
crates/api_models/src/events/locker_migration.rs
.rs
use common_utils::events::ApiEventMetric; use crate::locker_migration::MigrateCardResponse; impl ApiEventMetric for MigrateCardResponse { fn get_api_event_type(&self) -> Option<common_utils::events::ApiEventsType> { Some(common_utils::events::ApiEventsType::RustLocker) } }
71
1,994
hyperswitch
crates/api_models/src/events/recon.rs
.rs
use common_utils::events::{ApiEventMetric, ApiEventsType}; use masking::PeekInterface; use crate::recon::{ ReconStatusResponse, ReconTokenResponse, ReconUpdateMerchantRequest, VerifyTokenResponse, }; impl ApiEventMetric for ReconUpdateMerchantRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Recon) } } impl ApiEventMetric for ReconTokenResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Recon) } } impl ApiEventMetric for ReconStatusResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Recon) } } impl ApiEventMetric for VerifyTokenResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::User { user_id: self.user_email.peek().to_string(), }) } }
212
1,995
hyperswitch
crates/api_models/src/events/routing.rs
.rs
use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::routing::{ ContractBasedRoutingPayloadWrapper, ContractBasedRoutingSetupPayloadWrapper, DynamicRoutingUpdateConfigQuery, LinkedRoutingConfigRetrieveResponse, MerchantRoutingAlgorithm, ProfileDefaultRoutingConfig, RoutingAlgorithmId, RoutingConfigRequest, RoutingDictionaryRecord, RoutingKind, RoutingLinkWrapper, RoutingPayloadWrapper, RoutingRetrieveLinkQuery, RoutingRetrieveLinkQueryWrapper, RoutingRetrieveQuery, RoutingVolumeSplitWrapper, SuccessBasedRoutingConfig, SuccessBasedRoutingPayloadWrapper, ToggleDynamicRoutingQuery, ToggleDynamicRoutingWrapper, }; impl ApiEventMetric for RoutingKind { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for MerchantRoutingAlgorithm { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingAlgorithmId { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingDictionaryRecord { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for LinkedRoutingConfigRetrieveResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingPayloadWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for ProfileDefaultRoutingConfig { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingRetrieveQuery { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingConfigRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingRetrieveLinkQuery { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingLinkWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingRetrieveLinkQueryWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for ToggleDynamicRoutingQuery { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for SuccessBasedRoutingConfig { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for SuccessBasedRoutingPayloadWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for ContractBasedRoutingPayloadWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for ContractBasedRoutingSetupPayloadWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for ToggleDynamicRoutingWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for DynamicRoutingUpdateConfigQuery { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } } impl ApiEventMetric for RoutingVolumeSplitWrapper { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Routing) } }
883
1,996
hyperswitch
crates/api_models/src/events/payment.rs
.rs
use common_utils::events::{ApiEventMetric, ApiEventsType}; #[cfg(feature = "v2")] use super::{ PaymentStartRedirectionRequest, PaymentsCreateIntentRequest, PaymentsGetIntentRequest, PaymentsIntentResponse, PaymentsRequest, }; #[cfg(all( any(feature = "v2", feature = "v1"), not(feature = "payment_methods_v2") ))] use crate::payment_methods::CustomerPaymentMethodsListResponse; #[cfg(feature = "v1")] use crate::payments::{PaymentListFilterConstraints, PaymentListResponseV2}; #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] use crate::{events, payment_methods::CustomerPaymentMethodsListResponse}; use crate::{ payment_methods::{ self, ListCountriesCurrenciesRequest, ListCountriesCurrenciesResponse, PaymentMethodCollectLinkRenderRequest, PaymentMethodCollectLinkRequest, PaymentMethodCollectLinkResponse, PaymentMethodDeleteResponse, PaymentMethodListRequest, PaymentMethodListResponse, PaymentMethodMigrateResponse, PaymentMethodResponse, PaymentMethodUpdate, }, payments::{ self, ExtendedCardInfoResponse, PaymentIdType, PaymentListConstraints, PaymentListFilters, PaymentListFiltersV2, PaymentListResponse, PaymentsAggregateResponse, PaymentsApproveRequest, PaymentsCancelRequest, PaymentsCaptureRequest, PaymentsCompleteAuthorizeRequest, PaymentsDynamicTaxCalculationRequest, PaymentsDynamicTaxCalculationResponse, PaymentsExternalAuthenticationRequest, PaymentsExternalAuthenticationResponse, PaymentsIncrementalAuthorizationRequest, PaymentsManualUpdateRequest, PaymentsManualUpdateResponse, PaymentsPostSessionTokensRequest, PaymentsPostSessionTokensResponse, PaymentsRejectRequest, PaymentsRetrieveRequest, PaymentsSessionResponse, PaymentsStartRequest, RedirectionResponse, }, }; #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsRetrieveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { match self.resource_id { PaymentIdType::PaymentIntentId(ref id) => Some(ApiEventsType::Payment { payment_id: id.clone(), }), _ => None, } } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsStartRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsCaptureRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.to_owned(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsCompleteAuthorizeRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsDynamicTaxCalculationRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsPostSessionTokensRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsPostSessionTokensResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsDynamicTaxCalculationResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsCancelRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsApproveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsRejectRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for payments::PaymentsRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { match self.payment_id { Some(PaymentIdType::PaymentIntentId(ref id)) => Some(ApiEventsType::Payment { payment_id: id.clone(), }), _ => None, } } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentsCreateIntentRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentsRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentsGetIntentRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentsIntentResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for payments::PaymentsResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for payments::PaymentsResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } impl ApiEventMetric for PaymentMethodResponse { #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_id.clone(), payment_method: self.payment_method, payment_method_type: self.payment_method_type, }) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.id.clone(), payment_method_type: self.payment_method_type, payment_method_subtype: self.payment_method_subtype, }) } } impl ApiEventMetric for PaymentMethodMigrateResponse { #[cfg(all( any(feature = "v1", feature = "v2"), not(feature = "payment_methods_v2") ))] fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_response.payment_method_id.clone(), payment_method: self.payment_method_response.payment_method, payment_method_type: self.payment_method_response.payment_method_type, }) } #[cfg(all(feature = "v2", feature = "payment_methods_v2"))] fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_response.id.clone(), payment_method_type: self.payment_method_response.payment_method_type, payment_method_subtype: self.payment_method_response.payment_method_subtype, }) } } impl ApiEventMetric for PaymentMethodUpdate {} #[cfg(feature = "v1")] impl ApiEventMetric for payment_methods::DefaultPaymentMethod { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_id.clone(), payment_method: None, payment_method_type: None, }) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentMethodDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.id.clone(), payment_method_type: None, payment_method_subtype: None, }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentMethodDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.payment_method_id.clone(), payment_method: None, payment_method_type: None, }) } } impl ApiEventMetric for CustomerPaymentMethodsListResponse {} impl ApiEventMetric for PaymentMethodListRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethodList { payment_id: self .client_secret .as_ref() .and_then(|cs| cs.rsplit_once("_secret_")) .map(|(pid, _)| pid.to_string()), }) } } impl ApiEventMetric for ListCountriesCurrenciesRequest {} impl ApiEventMetric for ListCountriesCurrenciesResponse {} impl ApiEventMetric for PaymentMethodListResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for payment_methods::CustomerDefaultPaymentMethodResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethod { payment_method_id: self.default_payment_method_id.clone().unwrap_or_default(), payment_method: Some(self.payment_method), payment_method_type: self.payment_method_type, }) } } impl ApiEventMetric for PaymentMethodCollectLinkRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { self.pm_collect_link_id .as_ref() .map(|id| ApiEventsType::PaymentMethodCollectLink { link_id: id.clone(), }) } } impl ApiEventMetric for PaymentMethodCollectLinkRenderRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethodCollectLink { link_id: self.pm_collect_link_id.clone(), }) } } impl ApiEventMetric for PaymentMethodCollectLinkResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::PaymentMethodCollectLink { link_id: self.pm_collect_link_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentListFilterConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PaymentListFilters { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PaymentListFiltersV2 { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PaymentListConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PaymentListResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentListResponseV2 { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PaymentsAggregateResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for RedirectionResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsIncrementalAuthorizationRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsExternalAuthenticationResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsExternalAuthenticationRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for ExtendedCardInfoResponse {} #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsManualUpdateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v1")] impl ApiEventMetric for PaymentsManualUpdateResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } impl ApiEventMetric for PaymentsSessionResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.payment_id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for PaymentStartRedirectionRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } } #[cfg(feature = "v2")] impl ApiEventMetric for payments::PaymentMethodListResponseForPayments { // Payment id would be populated by the request fn get_api_event_type(&self) -> Option<ApiEventsType> { None } } #[cfg(feature = "v2")] impl ApiEventMetric for payments::PaymentsCaptureResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payment { payment_id: self.id.clone(), }) } }
3,148
1,997
hyperswitch
crates/api_models/src/events/customer.rs
.rs
use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::customers::{ CustomerDeleteResponse, CustomerRequest, CustomerResponse, CustomerUpdateRequestInternal, }; #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl ApiEventMetric for CustomerDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Customer { customer_id: self.customer_id.clone(), }) } } #[cfg(all(feature = "v2", feature = "customer_v2"))] impl ApiEventMetric for CustomerDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Customer { customer_id: Some(self.id.clone()), }) } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl ApiEventMetric for CustomerRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { self.get_merchant_reference_id() .clone() .map(|cid| ApiEventsType::Customer { customer_id: cid }) } } #[cfg(all(feature = "v2", feature = "customer_v2"))] impl ApiEventMetric for CustomerRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Customer { customer_id: None }) } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl ApiEventMetric for CustomerResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { self.get_merchant_reference_id() .clone() .map(|cid| ApiEventsType::Customer { customer_id: cid }) } } #[cfg(all(feature = "v2", feature = "customer_v2"))] impl ApiEventMetric for CustomerResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Customer { customer_id: Some(self.id.clone()), }) } } #[cfg(all(any(feature = "v1", feature = "v2"), not(feature = "customer_v2")))] impl ApiEventMetric for CustomerUpdateRequestInternal { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Customer { customer_id: self.customer_id.clone(), }) } } #[cfg(all(feature = "v2", feature = "customer_v2"))] impl ApiEventMetric for CustomerUpdateRequestInternal { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Customer { customer_id: Some(self.id.clone()), }) } }
600
1,998
hyperswitch
crates/api_models/src/events/dispute.rs
.rs
use common_utils::events::{ApiEventMetric, ApiEventsType}; use super::{ DeleteEvidenceRequest, DisputeResponse, DisputeResponsePaymentsRetrieve, DisputesAggregateResponse, SubmitEvidenceRequest, }; impl ApiEventMetric for SubmitEvidenceRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Dispute { dispute_id: self.dispute_id.clone(), }) } } impl ApiEventMetric for DisputeResponsePaymentsRetrieve { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Dispute { dispute_id: self.dispute_id.clone(), }) } } impl ApiEventMetric for DisputeResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Dispute { dispute_id: self.dispute_id.clone(), }) } } impl ApiEventMetric for DeleteEvidenceRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Dispute { dispute_id: self.dispute_id.clone(), }) } } impl ApiEventMetric for DisputesAggregateResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } }
287
1,999
hyperswitch
crates/api_models/src/events/revenue_recovery.rs
.rs
use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::process_tracker::revenue_recovery::{RevenueRecoveryId, RevenueRecoveryResponse}; impl ApiEventMetric for RevenueRecoveryResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ProcessTracker) } } impl ApiEventMetric for RevenueRecoveryId { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ProcessTracker) } }
112
2,000
hyperswitch
crates/api_models/src/events/gsm.rs
.rs
use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::gsm; impl ApiEventMetric for gsm::GsmCreateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Gsm) } } impl ApiEventMetric for gsm::GsmUpdateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Gsm) } } impl ApiEventMetric for gsm::GsmRetrieveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Gsm) } } impl ApiEventMetric for gsm::GsmDeleteRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Gsm) } } impl ApiEventMetric for gsm::GsmDeleteResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Gsm) } } impl ApiEventMetric for gsm::GsmResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Gsm) } }
271
2,001
hyperswitch
crates/api_models/src/events/payouts.rs
.rs
use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::payouts::{ PayoutActionRequest, PayoutCreateRequest, PayoutCreateResponse, PayoutLinkInitiateRequest, PayoutListConstraints, PayoutListFilterConstraints, PayoutListFilters, PayoutListResponse, PayoutRetrieveRequest, }; impl ApiEventMetric for PayoutRetrieveRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payout { payout_id: self.payout_id.clone(), }) } } impl ApiEventMetric for PayoutCreateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { self.payout_id.as_ref().map(|id| ApiEventsType::Payout { payout_id: id.clone(), }) } } impl ApiEventMetric for PayoutCreateResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payout { payout_id: self.payout_id.clone(), }) } } impl ApiEventMetric for PayoutActionRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payout { payout_id: self.payout_id.clone(), }) } } impl ApiEventMetric for PayoutListConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PayoutListFilterConstraints { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PayoutListResponse { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PayoutListFilters { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::ResourceListAPI) } } impl ApiEventMetric for PayoutLinkInitiateRequest { fn get_api_event_type(&self) -> Option<ApiEventsType> { Some(ApiEventsType::Payout { payout_id: self.payout_id.clone(), }) } }
498
2,002
hyperswitch
crates/api_models/src/events/user_role.rs
.rs
use common_utils::events::{ApiEventMetric, ApiEventsType}; use crate::user_role::{ role::{ CreateRoleRequest, GetRoleRequest, GroupsAndResources, ListRolesAtEntityLevelRequest, ListRolesRequest, RoleInfoResponseNew, RoleInfoWithGroupsResponse, RoleInfoWithParents, UpdateRoleRequest, }, AuthorizationInfoResponse, DeleteUserRoleRequest, ListUsersInEntityRequest, UpdateUserRoleRequest, }; common_utils::impl_api_event_type!( Miscellaneous, ( GetRoleRequest, AuthorizationInfoResponse, UpdateUserRoleRequest, DeleteUserRoleRequest, CreateRoleRequest, UpdateRoleRequest, ListRolesAtEntityLevelRequest, RoleInfoResponseNew, RoleInfoWithGroupsResponse, ListUsersInEntityRequest, ListRolesRequest, GroupsAndResources, RoleInfoWithParents ) );
182
2,003
hyperswitch
crates/api_models/src/process_tracker/revenue_recovery.rs
.rs
use common_utils::id_type; use serde::{Deserialize, Serialize}; use time::PrimitiveDateTime; use utoipa::ToSchema; use crate::enums; #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct RevenueRecoveryResponse { pub id: String, pub name: Option<String>, pub schedule_time_for_payment: Option<PrimitiveDateTime>, pub schedule_time_for_psync: Option<PrimitiveDateTime>, #[schema(value_type = ProcessTrackerStatus, example = "finish")] pub status: enums::ProcessTrackerStatus, pub business_status: String, } #[derive(Debug, Clone, Serialize, Deserialize, ToSchema)] pub struct RevenueRecoveryId { pub revenue_recovery_id: id_type::GlobalPaymentId, }
158
2,004
hyperswitch
crates/api_models/src/analytics/frm.rs
.rs
use std::{ collections::hash_map::DefaultHasher, hash::{Hash, Hasher}, }; use common_enums::enums::FraudCheckStatus; #[derive( Clone, Copy, Debug, Default, Eq, PartialEq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumString, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmTransactionType { #[default] PreFrm, PostFrm, } use super::{NameDescription, TimeRange}; #[derive(Clone, Debug, Default, serde::Deserialize, serde::Serialize)] pub struct FrmFilters { #[serde(default)] pub frm_status: Vec<FraudCheckStatus>, #[serde(default)] pub frm_name: Vec<String>, #[serde(default)] pub frm_transaction_type: Vec<FrmTransactionType>, } #[derive( Debug, serde::Serialize, serde::Deserialize, strum::AsRefStr, PartialEq, PartialOrd, Eq, Ord, strum::Display, strum::EnumIter, Clone, Copy, )] #[serde(rename_all = "snake_case")] #[strum(serialize_all = "snake_case")] pub enum FrmDimensions { FrmStatus, FrmName, FrmTransactionType, } #[derive( Clone, Debug, Hash, PartialEq, Eq, serde::Serialize, serde::Deserialize, strum::Display, strum::EnumIter, strum::AsRefStr, )] #[strum(serialize_all = "snake_case")] #[serde(rename_all = "snake_case")] pub enum FrmMetrics { FrmTriggeredAttempts, FrmBlockedRate, } pub mod metric_behaviour { pub struct FrmTriggeredAttempts; pub struct FrmBlockRate; } impl From<FrmMetrics> for NameDescription { fn from(value: FrmMetrics) -> Self { Self { name: value.to_string(), desc: String::new(), } } } impl From<FrmDimensions> for NameDescription { fn from(value: FrmDimensions) -> Self { Self { name: value.to_string(), desc: String::new(), } } } #[derive(Debug, serde::Serialize, Eq)] pub struct FrmMetricsBucketIdentifier { pub frm_status: Option<String>, pub frm_name: Option<String>, pub frm_transaction_type: Option<String>, #[serde(rename = "time_range")] pub time_bucket: TimeRange, #[serde(rename = "time_bucket")] #[serde(with = "common_utils::custom_serde::iso8601custom")] pub start_time: time::PrimitiveDateTime, } impl Hash for FrmMetricsBucketIdentifier { fn hash<H: Hasher>(&self, state: &mut H) { self.frm_status.hash(state); self.frm_name.hash(state); self.frm_transaction_type.hash(state); self.time_bucket.hash(state); } } impl PartialEq for FrmMetricsBucketIdentifier { 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() } } impl FrmMetricsBucketIdentifier { pub fn new( frm_status: Option<String>, frm_name: Option<String>, frm_transaction_type: Option<String>, normalized_time_range: TimeRange, ) -> Self { Self { frm_status, frm_name, frm_transaction_type, time_bucket: normalized_time_range, start_time: normalized_time_range.start_time, } } } #[derive(Debug, serde::Serialize)] pub struct FrmMetricsBucketValue { pub frm_triggered_attempts: Option<u64>, pub frm_blocked_rate: Option<f64>, } #[derive(Debug, serde::Serialize)] pub struct FrmMetricsBucketResponse { #[serde(flatten)] pub values: FrmMetricsBucketValue, #[serde(flatten)] pub dimensions: FrmMetricsBucketIdentifier, }
885
2,005